# Claude Code Source: https://docs.vibekit.sh/agents/claude-code Run Claude Code in a secure and private sandbox Claude Code ## How it works VibeKit runs Anthropic's Claude Code in headless mode, with the `--dangerously-skip-permissions` flag enabled. This means that the agent will automatically create, edit and delete files if it's in `code` mode. The Claude Code CLI runs in the configured environment and has access to the network, which means it could be used to connect to the outside world. This is a powerful feature that can be used to build powerful applications and should be used with caution. [Read more about Claude Code](https://docs.anthropic.com/en/docs/claude-code/overview) ## Authentication Claude Code agent supports OAuth and API key authentication. Authentication is now handled by the separate `@vibe-kit/auth` package. ### Installation ```bash theme={"dark"} # Install both packages npm install @vibe-kit/sdk @vibe-kit/auth ``` ### 1. OAuth Token Authentication (Recommended) Authenticate with your Claude Pro/Max account for better rate limits. > **Security Note**: OAuth tokens are stored locally at `~/.vibekit/claude-oauth-token.json` with restricted permissions (600). For production environments, consider using environment variables or a secrets manager. #### Using OAuth in Code Get an OAuth token and pass it as the API key: ```typescript theme={"dark"} import { VibeKit } from '@vibe-kit/sdk'; import { ClaudeAuth } from '@vibe-kit/auth'; // Get OAuth token const accessToken = await ClaudeAuth.getValidToken(); if (!accessToken) { await ClaudeAuth.authenticate(); accessToken = await ClaudeAuth.getValidToken(); } // Use token with VibeKit const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", providerApiKey: accessToken, // Pass OAuth token as API key model: "claude-sonnet-4-20250514", }) .withSandbox(sandboxProvider); ``` #### Using OAuth Token via Environment Variable You can also provide the OAuth token directly via environment variable: ```typescript theme={"dark"} import { ClaudeAuth } from '@vibe-kit/auth'; // Import token from environment await ClaudeAuth.importToken({ fromEnv: true }); const accessToken = await ClaudeAuth.getValidToken(); // Use with VibeKit const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", providerApiKey: accessToken, model: "claude-sonnet-4-20250514", }) .withSandbox(sandboxProvider); ``` #### Multi-Instance Usage For using OAuth tokens across multiple instances (CI/CD, containers, etc.): 1. **Quick sharing**: Set `CLAUDE_CODE_OAUTH_TOKEN` environment variable 2. **With auto-refresh**: Copy `~/.vibekit/claude-oauth-token.json` between instances 3. **Production**: Use a secrets manager or API keys #### Library API Usage You can use OAuth authentication programmatically with the auth package: ```typescript theme={"dark"} import { ClaudeAuth } from '@vibe-kit/auth'; // Authenticate and get token const token = await ClaudeAuth.authenticate(); // Check if authenticated const isAuthenticated = await ClaudeAuth.isAuthenticated(); // Get valid token (auto-refresh if needed) const accessToken = await ClaudeAuth.getValidToken(); // Export token const exportedToken = await ClaudeAuth.exportToken('full'); // Import token await ClaudeAuth.importToken({ refreshToken: 'your-refresh-token' }); // Clear authentication await ClaudeAuth.logout(); ``` #### Web OAuth Usage For web applications, OAuth authentication works the same way as CLI - users copy and paste the authentication code: ```typescript theme={"dark"} import { ClaudeWebAuth, MemoryTokenStorage } from '@vibe-kit/auth'; // Frontend - Generate OAuth URL const { url, state, codeVerifier } = ClaudeWebAuth.createAuthorizationUrl(); // Store for later use sessionStorage.setItem('oauth_state', state); sessionStorage.setItem('oauth_code_verifier', codeVerifier); // Open Claude authentication in new tab window.open(url, '_blank'); // After user copies the authentication code (format: code#state) const authCode = "paste-authentication-code-here"; // Backend - Authenticate with the code const storage = new MemoryTokenStorage(sessionId); const auth = new ClaudeWebAuth(storage); await auth.authenticate(authCode, codeVerifier, state); // Use the token with VibeKit const accessToken = await auth.getValidToken(); // Pass token as API key to VibeKit const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", providerApiKey: accessToken, // Pass OAuth token as API key model: "claude-sonnet-4-20250514", }) .withSandbox(sandboxProvider); ``` ### 2. API Key Authentication Use your Anthropic API key directly: ```typescript theme={"dark"} const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", providerApiKey: process.env.ANTHROPIC_API_KEY, // Traditional API key model: "claude-sonnet-4-20250514", }) .withSandbox(sandboxProvider); ``` Both OAuth tokens and API keys are passed the same way to VibeKit - as the `providerApiKey` parameter. # OpenAI Codex Source: https://docs.vibekit.sh/agents/codex Run OpenAI Codex in a secure and private sandbox Hero Light ## How it works VibeKit runs OpenAI Codex in headless mode with the `auto-edit` flag enabled. This means that the agent will automatically create, edit and delete files if it's in `code` mode. The Codex CLI runs in the configured environment and has access to the network, which means it could be used to connect to the outside world. This is a powerful feature that can be used to build powerful applications and should be used with caution. [Read more about OpenAI Codex CLI](https://github.com/openai/codex) # Google Gemini Source: https://docs.vibekit.sh/agents/gemini Run Google Gemini CLI in a secure and private sandbox Gemini ## How it works VibeKit runs Gemini CLI in headless mode with the `--yolo` flag enabled. This means that the agent will automatically create, edit and delete files if it's in `code` mode. The Gemini CLI runs in the configured environment and has access to the network, which means it could be used to connect to the outside world. This is a powerful feature that can be used to build powerful applications and should be used with caution. [Read more about Gemini CLI](https://t.co/R2CsgNMA3A) # Grok CLI Source: https://docs.vibekit.sh/agents/grok Run Grok CLI in a secure and private sandbox Grok ## How it works VibeKit runs the Grok CLI in headless mode. This means that the agent will automatically create, edit and delete files if it's in `code` mode. The Grok CLI runs in the configured environment and has access to the network, which means it could be used to connect to the outside world. This is a powerful feature that can be used to build powerful applications and should be used with caution. [Read more about Grok CLI](https://github.com/superagent-ai/grok-cli) ## Authentication Grok CLI requires an API key from xAI (X.AI). You can obtain one from the [xAI Console](https://console.x.ai/). ### Environment Variable Authentication Set your xAI API key as an environment variable: ```bash theme={"dark"} export GROK_API_KEY="your-xai-api-key-here" # or alternatively export XAI_API_KEY="your-xai-api-key-here" ``` ### Using in Code ```typescript theme={"dark"} const vibeKit = new VibeKit() .withAgent({ type: "grok", provider: "xai", apiKey: process.env.GROK_API_KEY, model: "grok-beta", // or "grok-2-latest", "grok-2-mini" }) .withSandbox(sandboxProvider); ``` ## Configuration Options ### Available Models * `grok-4` - Grok-4 model (default) * `grok-3` - Grok-3 model * `grok-code-fast-1` - Grok code model ### Custom Base URL If you're using a custom xAI API endpoint: ```typescript theme={"dark"} const vibeKit = new VibeKit() .withAgent({ type: "grok", provider: "xai", apiKey: process.env.GROK_API_KEY, model: "grok-beta", baseUrl: "https://your-custom-api-url.com", // optional }) .withSandbox(sandboxProvider); ``` ## Example Usage ### Basic Code Generation ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY!, templateId: "vibekit-grok", }); const vibeKit = new VibeKit() .withAgent({ type: "grok", provider: "xai", apiKey: process.env.GROK_API_KEY!, model: "grok-beta", }) .withSandbox(e2bProvider); // Generate code const result = await vibeKit.generateCode({ prompt: "Create a simple React component that displays a hello world message", mode: "code" }); console.log(result.stdout); ``` ### Ask Mode (Research Only) ```typescript theme={"dark"} // Ask questions without modifying files const result = await vibeKit.generateCode({ prompt: "What is the current project structure?", mode: "ask" }); console.log(result.stdout); ``` ## Environment Variables The Grok agent supports the following environment variables: * `GROK_API_KEY` - Your xAI API key (required) * `XAI_API_KEY` - Alternative name for your xAI API key * `GROK_BASE_URL` - Custom API base URL (optional) ## Security Considerations * API keys are passed to the sandbox environment and should be treated as sensitive information * The Grok CLI has network access and can make external API calls * Always use proper secrets management in production environments * Consider using environment-specific API keys with appropriate rate limits ## Troubleshooting ### Common Issues 1. **"grok command not found"**: Ensure the Grok CLI is installed in your sandbox template 2. **Authentication errors**: Verify your API key is correct and has sufficient credits 3. **Rate limiting**: xAI has rate limits; consider implementing retry logic for production use 4. **Model not available**: Check that the specified model is available in your xAI account ### Debug Mode To see detailed output from the Grok CLI, you can enable streaming callbacks: ```typescript theme={"dark"} vibeKit.on("update", (message) => { console.log("Grok output:", message); }); vibeKit.on("error", (error) => { console.error("Grok error:", error); }); ``` # Opencode Source: https://docs.vibekit.sh/agents/opencode Run Opencode in a secure and private sandbox Opencode ## How it works VibeKit runs Opencode in headless mode. This means that the agent will automatically create, edit and delete files if it's in `code` mode. The Opencode CLI runs in the configured environment and has access to the network, which means it could be used to connect to the outside world. This is a powerful feature that can be used to build powerful applications and should be used with caution. [Read more about Opencode](https://github.com/sst/opencode) # Configuration Source: https://docs.vibekit.sh/api-reference/configuration VibeKit configuration reference ## Overview VibeKit provides a fluent interface for configuration. You can chain methods to configure the agent, sandbox provider, GitHub integration, and other options. ## Basic configuration ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY\!, templateId: "vibekit-claude", }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY\!, model: "claude-sonnet-4-20250514", }) .withSandbox(e2bProvider) .withGithub({ token: process.env.GITHUB_TOKEN\!, repository: "your-org/your-repo", }); ``` ## Configuration reference ### Agent Configuration Use the `withAgent()` method to configure which AI model to use. ```typescript theme={"dark"} .withAgent({ type: "claude", provider: "anthropic", apiKey: "your-api-key", model: "claude-sonnet-4-20250514", }) ``` #### Agent Configuration Options | Property | Type | Required | Description | | ---------- | --------------- | -------- | ------------------------------------- | | `type` | `AgentType` | Yes | The type of AI agent to use | | `provider` | `ModelProvider` | Yes | The AI provider service | | `apiKey` | `string` | Yes | API key for the chosen agent provider | | `model` | `string` | Yes | Specific model to use | **Available agent types:** * `"claude"` - Anthropic Claude agent * `"codex"` - OpenAI Codex agent * `"opencode"` - Opencode agent * `"gemini"` - Google Gemini agent **Available providers:** * `"anthropic"` - Anthropic * `"openai"` - OpenAI * `"openrouter"` - OpenRouter * `"azure"` - Azure * `"gemini"` - Google Gemini * `"ollama"` - Ollama * `"mistral"` - Mistral AI * `"deepseek"` - DeepSeek * `"xai"` - xAI * `"groq"` - Groq ### Sandbox Configuration Use the `withSandbox()` method to configure the sandbox environment where code execution happens. You'll need to install and import the specific provider package. #### E2B Configuration ```typescript theme={"dark"} import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: "e2b_****", templateId: "custom-template-id" // optional }); .withSandbox(e2bProvider) ``` #### Northflank Configuration ```typescript theme={"dark"} import { createNorthflankProvider } from "@vibe-kit/northflank"; const northflankProvider = createNorthflankProvider({ apiKey: "nf_****", image: "your-custom-image", // optional projectId: "your-project-id", // optional billingPlan: "nf-compute-200", // optional persistentVolumeStorage: 10240 // optional }); .withSandbox(northflankProvider) ``` #### Daytona Configuration ```typescript theme={"dark"} import { createDaytonaProvider } from "@vibe-kit/daytona"; const daytonaProvider = createDaytonaProvider({ apiKey: "daytona_****", image: "my-codex-image", // optional serverUrl: "https://app.daytona.io/api" // optional }); .withSandbox(daytonaProvider) ``` #### Cloudflare Configuration ```typescript theme={"dark"} import { createCloudflareProvider } from "@vibe-kit/cloudflare"; // Must be used within a Cloudflare Worker const cloudflareProvider = createCloudflareProvider({ env: env, // Worker env object with Sandbox binding hostname: "your-worker.domain.workers.dev" }); .withSandbox(cloudflareProvider) ``` ### Modal Configuration ```typescript theme={"dark"} import { createModalProvider } from "@vibe-kit/modal"; const modalProvider = createModalProvider({}); //refer to https://modal.com/docs/reference/cli/setup for CLI setup beforehand .withSandbox(modalProvider); ``` For detailed configuration options for each provider, see the [Supported Sandboxes](/supported-sandboxes) section. ### GitHub Integration Use the `withGithub()` method to configure repository integration for pull request creation and code management. ```typescript theme={"dark"} .withGithub({ token: "ghp_****", repository: "superagent-ai/vibekit" }) ``` | Property | Type | Required | Description | | ------------ | -------- | -------- | -------------------------------------------------------- | | `token` | `string` | Yes | GitHub personal access token with repository permissions | | `repository` | `string` | Yes | Repository in the format "owner/repo-name" | ### Session Management (Optional) Use the `withSession()` method to specify a sandbox session to reuse. ```typescript theme={"dark"} .withSession("existing-sandbox-id") ``` | Property | Type | Required | Description | | ----------- | -------- | -------- | ---------------------------- | | `sandboxId` | `string` | Yes | Existing sandbox ID to reuse | ### Working Directory Use the `withWorkingDirectory()` method to specify the directory where the agent should execute commands and work with files. ```typescript theme={"dark"} .withWorkingDirectory("/path/to/your/project") ``` | Property | Type | Required | Default | Description | | -------- | -------- | -------- | ------- | ------------------------------------------------------------------------- | | `path` | `string` | Yes | - | The directory path where the agent will execute commands and access files | ### Secrets Management Use the `withSecrets()` method to provide environment variables and secrets to the sandbox. ```typescript theme={"dark"} .withSecrets({ "DATABASE_URL": "postgresql://...", "API_KEY": "secret-key", "NODE_ENV": "production" }) ``` | Property | Type | Required | Description | | --------- | ------------------------ | -------- | -------------------------------------------------------------- | | `secrets` | `Record` | Yes | Key-value pairs of environment variables to set in the sandbox | ## Complete Example ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY\!, templateId: "vibekit-claude", }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY\!, model: "claude-sonnet-4-20250514", }) .withSandbox(e2bProvider) .withGithub({ token: process.env.GITHUB_TOKEN\!, repository: "your-org/your-repo", }) .withWorkingDirectory("/app") .withSecrets({ "DATABASE_URL": process.env.DATABASE_URL\!, "API_KEY": process.env.API_KEY\!, }); // Use the configured VibeKit instance const result = await vibeKit.generateCode({ prompt: "Create a web server", mode: "ask" }); ``` EOF \< /dev/null # createPullRequest Source: https://docs.vibekit.sh/api-reference/create-pull-request Create a pull request after generating code changes. ## Method signature ```typescript theme={"dark"} async createPullRequest( repository: string, labelOptions?: LabelOptions, branchPrefix?: string ): Promise ``` ## Description The `createPullRequest` method allows you to create a GitHub pull request after code changes have been generated using any supported agent (Codex, Claude, OpenCode, or Gemini). This method streamlines the process of submitting code changes for review by automatically creating a pull request with the generated modifications. ## Parameters | Parameter | Type | Required | Description | | -------------- | -------------- | -------- | -------------------------------------------------------- | | `repository` | `string` | Yes | The GitHub repository in format "owner/repo" | | `labelOptions` | `LabelOptions` | No | Optional label configuration for the pull request | | `branchPrefix` | `string` | No | Optional prefix for the branch name that will be created | ### LabelOptions Interface | Property | Type | Required | Description | | ------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------- | | `name` | `string` | Yes | The name of the label to create/apply to the pull request | | `color` | `string` | Yes | The color of the label in hex format (without #). Examples: "0e8a16" (green), "d73a49" (red), "0366d6" (blue) | | `description` | `string` | Yes | A description of what this label represents | ## Return type | Type | Description | | ------------------------------ | ------------------------------------------------------- | | `Promise` | Promise that resolves to a pull request response object | ### PullRequestResponse Interface | Property | Type | Required | Description | | ------------------ | ----------------- | -------- | ------------------------------------------------------ | | `id` | `number` | Yes | The unique identifier of the pull request | | `number` | `number` | Yes | The pull request number | | `state` | `string` | Yes | The state of the pull request (e.g., "open", "closed") | | `title` | `string` | Yes | The title of the pull request | | `body` | `string` | Yes | The body/description of the pull request | | `html_url` | `string` | Yes | The URL to view the pull request on GitHub | | `head` | `object` | Yes | Information about the head branch of the PR | | `base` | `object` | Yes | Information about the base branch of the PR | | `user` | `object` | Yes | Information about the user who created the PR | | `created_at` | `string` | Yes | ISO timestamp when the PR was created | | `updated_at` | `string` | Yes | ISO timestamp when the PR was last updated | | `merged` | `boolean` | Yes | Whether the pull request has been merged | | `mergeable` | `boolean \| null` | Yes | Whether the pull request can be merged | | `merge_commit_sha` | `string \| null` | Yes | The SHA of the merge commit if merged | | `branchName` | `string` | Yes | The name of the branch created for the PR | | `commitSha` | `string` | No | The SHA of the commit | ## Requirements * **Agent Type**: This method is available for all supported agents (Codex, Claude, OpenCode, and Gemini) * **Initialization**: The VibeKit instance must be properly initialized with valid agent configuration * **Code Generation**: Code changes should be generated before creating a pull request * **GitHub Integration**: A valid GitHub token must be configured using `withSecrets({ GH_TOKEN: "your_token" })` * **Repository Access**: The provided GitHub token must have access to the specified repository ## Error handling The method throws errors in the following scenarios: ### Initialization Error ```typescript theme={"dark"} throw new Error("Agent not initialized") ``` * **When**: The agent is not properly initialized * **Resolution**: Verify your VibeKit configuration includes valid agent settings and GitHub configuration ## Usage examples ### Basic Usage ```typescript theme={"dark"} import { VibeKit } from 'vibekit'; import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY!, }); const vibekit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(e2bProvider) .withSecrets({ GH_TOKEN: process.env.GITHUB_TOKEN!, }); // Clone repository first await vibekit.cloneRepository("your-org/your-repo"); // Generate code changes await vibekit.generateCode({ prompt: "Add a new user registration feature", mode: "code" }); // Create pull request with default settings try { const prResponse = await vibekit.createPullRequest("your-org/your-repo"); console.log(`Pull request created: ${prResponse.html_url}`); console.log(`PR ID: ${prResponse.id}`); console.log(`PR Number: ${prResponse.number}`); console.log(`Title: ${prResponse.title}`); console.log(`State: ${prResponse.state}`); console.log(`Branch: ${prResponse.branchName}`); console.log(`Commit SHA: ${prResponse.commitSha}`); console.log(`Created at: ${prResponse.created_at}`); console.log(`Mergeable: ${prResponse.mergeable}`); } catch (error) { console.error("Failed to create pull request:", error.message); } ``` ### Advanced Usage with Parameters ```typescript theme={"dark"} import { VibeKit, LabelOptions } from 'vibekit'; import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY!, }); const vibekit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(e2bProvider) .withSecrets({ GH_TOKEN: process.env.GITHUB_TOKEN!, }); // Clone repository first await vibekit.cloneRepository("your-org/your-repo"); // Generate code changes await vibekit.generateCode({ prompt: "Add authentication middleware", mode: "code" }); // Create pull request with custom parameters const labelOptions: LabelOptions = { name: "ai-generated", color: "0e8a16", description: "Code generated by AI agent" }; try { const prResponse = await vibekit.createPullRequest( "your-org/your-repo", // Repository parameter (required) labelOptions, // Custom label options "feature" // Branch prefix (will create feature/xyz branch) ); console.log(`Pull request created: ${prResponse.html_url}`); console.log(`PR Number: ${prResponse.number}`); console.log(`Branch: ${prResponse.branchName}`); // Access additional GitHub API data console.log(`PR Title: ${prResponse.title}`); console.log(`PR Body: ${prResponse.body}`); console.log(`Author: ${prResponse.user.login}`); console.log(`Head branch: ${prResponse.head.ref}`); console.log(`Base branch: ${prResponse.base.ref}`); } catch (error) { console.error("Failed to create pull request:", error.message); } ``` ### Additional Label Examples ```typescript theme={"dark"} // Different label configurations const bugfixLabel: LabelOptions = { name: "bug-fix", color: "d73a49", description: "Fixes a bug in the codebase" }; const featureLabel: LabelOptions = { name: "new-feature", color: "0366d6", description: "Adds new functionality" }; const refactorLabel: LabelOptions = { name: "refactor", color: "f9d71c", description: "Code refactoring without functional changes" }; ``` ### Using with Different Agents ```typescript theme={"dark"} // Works with any agent type const vibekitClaude = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", model: "claude-sonnet-4-20250514", apiKey: "..." }) .withSecrets({ GH_TOKEN: process.env.GITHUB_TOKEN }) .withSandbox(sandbox); const vibekitCodex = new VibeKit() .withAgent({ type: "codex", provider: "openai", model: "codex-mini-latest", apiKey: "..." }) .withSecrets({ GH_TOKEN: process.env.GITHUB_TOKEN }) .withSandbox(sandbox); // Both agents support createPullRequest (now requires repository parameter) await vibekitClaude.cloneRepository("your-org/your-repo"); await vibekitClaude.createPullRequest("your-org/your-repo"); await vibekitCodex.cloneRepository("your-org/your-repo"); await vibekitCodex.createPullRequest("your-org/your-repo"); ``` ## Notes * The pull request is automatically labeled with the agent type ('codex', 'claude', 'opencode', or 'gemini') to indicate which agent created it * Ensure your GitHub token has the necessary permissions to create pull requests in the target repository * The method creates a new branch for the pull request automatically * Code changes must be generated before calling this method * Repository must be explicitly cloned using `cloneRepository()` before generating code * When using `branchPrefix`, the final branch name will be in the format `{branchPrefix}/{generated-suffix}` * The `labelOptions` parameter creates a new label if it doesn't exist in the repository and applies it to the pull request * The response includes the complete GitHub API pull request data, allowing access to detailed information like user details, branch information, timestamps, and merge status * The `repository` parameter is now required and specifies which repository to create the pull request in # executeCommand Source: https://docs.vibekit.sh/api-reference/execute-command Run arbitrary shell commands in the sandbox environment. ## Method signature ```typescript theme={"dark"} public async executeCommand( command: string, options: { timeoutMs?: number; background?: boolean; branch?: string; callbacks?: StreamCallbacks; } = {} ): Promise ``` ## Parameters | Parameter | Type | Required | Default | Description | | --------- | -------- | -------- | ------- | ------------------------------------------------------- | | `command` | `string` | Yes | - | The shell command to execute in the sandbox environment | | `options` | `object` | No | `{}` | Configuration options for command execution | ### Options Object | Property | Type | Required | Default | Description | | ------------ | ----------------- | -------- | ------- | ------------------------------------------------------------- | | `timeoutMs` | `number` | No | - | Maximum time in milliseconds to wait for command completion | | `background` | `boolean` | No | `false` | Whether to run the command in the background (non-blocking) | | `branch` | `string` | No | - | Git branch to checkout or create before executing the command | | `callbacks` | `StreamCallbacks` | No | - | Streaming callbacks for real-time command output | ### StreamCallbacks Interface | Property | Type | Required | Description | | ---------- | --------------------------- | -------- | ---------------------------------------------------------- | | `onUpdate` | `(message: string) => void` | No | Called with streaming updates from command output (stdout) | | `onError` | `(error: string) => void` | No | Called when errors occur during command execution (stderr) | ## Return value | Type | Description | | ------------------------ | ------------------------------------------------------ | | `Promise` | Promise that resolves to the command execution results | ### AgentResponse Interface | Property | Type | Description | | ----------- | -------- | ---------------------------------------------------------- | | `sandboxId` | `string` | Unique identifier for the sandbox environment | | `stdout` | `string` | Standard output from the command execution | | `stderr` | `string` | Standard error from the command execution | | `exitCode` | `number` | Exit code from the command execution (0 indicates success) | ## Examples ### Basic Command Execution ```typescript theme={"dark"} import { VibeKit } from 'vibekit'; const vibekit = new VibeKit(config); // Execute a simple command const result = await vibekit.executeCommand('ls -la'); console.log('Command output:', result.stdout); console.log('Exit code:', result.exitCode); ``` ### Command with Timeout ```typescript theme={"dark"} // Execute command with a timeout const result = await vibekit.executeCommand('npm install', { timeoutMs: 30000 // 30 seconds timeout }); if (result.exitCode === 0) { console.log('Installation completed successfully'); } else { console.log('Installation failed:', result.stderr); } ``` ### Background Command Execution ```typescript theme={"dark"} // Run a long-running command in the background const result = await vibekit.executeCommand('npm run dev', { background: true }); console.log('Background process started with sandbox ID:', result.sandboxId); ``` ### Streaming Command Output ```typescript theme={"dark"} // Execute command with streaming output using stdout/stderr events vibekit.on('stdout', (output) => { console.log('Command output:', output); }); vibekit.on('stderr', (error) => { console.error('Command error:', error); }); const result = await vibekit.executeCommand('npm test'); console.log('Final test result:', result.exitCode === 0 ? 'PASSED' : 'FAILED'); ``` ### Streaming with Callbacks (Legacy) ```typescript theme={"dark"} // Execute command with streaming output using callbacks (deprecated approach) const result = await vibekit.executeCommand('npm test', { callbacks: { onUpdate: (message) => { console.log('Test output:', message); }, onError: (error) => { console.error('Test error:', error); } } }); console.log('Final test result:', result.exitCode === 0 ? 'PASSED' : 'FAILED'); ``` ### Command with Branch Switching ```typescript theme={"dark"} // Execute command on a specific git branch const result = await vibekit.executeCommand('npm run build', { branch: 'feature-new-ui', timeoutMs: 60000 }); if (result.exitCode === 0) { console.log('Build completed successfully on feature-new-ui branch'); } else { console.log('Build failed:', result.stderr); } ``` ### Complex Command with All Options ```typescript theme={"dark"} // Execute a complex command with multiple options vibekit.on('stdout', (output) => { console.log('pytest:', output); }); vibekit.on('stderr', (error) => { console.error('pytest error:', error); }); const result = await vibekit.executeCommand('python -m pytest tests/', { timeoutMs: 60000, background: false, branch: 'test-improvements' }); console.log(`Tests completed with exit code: ${result.exitCode}`); ``` ## Error handling The method throws errors in the following cases: * **Sandbox not available:** When no active sandbox environment exists * **Command timeout:** When the command exceeds the specified timeout * **Invalid command:** When the command syntax is invalid or command not found * **Permission errors:** When the command requires elevated permissions not available in the sandbox * **Resource limitations:** When the command exceeds sandbox resource limits ```typescript theme={"dark"} try { const result = await vibekit.executeCommand('sudo rm -rf /', { timeoutMs: 5000 }); } catch (error) { if (error.message.includes('timeout')) { console.error('Command timed out'); } else if (error.message.includes('permission')) { console.error('Permission denied'); } else { console.error('Command execution failed:', error.message); } } ``` ## Security considerations * Commands are executed within a sandboxed environment for security * Elevated privileges (sudo) may not be available depending on sandbox configuration * File system access is limited to the sandbox environment * Network access may be restricted based on sandbox configuration ## Notes * **Sandbox Environment:** Commands are executed within the active sandbox environment * **Working Directory:** Commands execute in the sandbox's default working directory * **Branch Support:** Automatically switches to the specified branch (creates if it doesn't exist) * **Environment Variables:** Sandbox environment variables are available to executed commands * **Resource Limits:** Commands are subject to sandbox CPU, memory, and time limitations * **Background Execution:** Background commands continue running after the method returns * **Streaming Support:** Real-time output streaming is available through stdout/stderr events or callbacks * **Exit Codes:** Standard Unix exit codes apply (0 = success, non-zero = error) * **Event Handling:** Prefer using `vibekit.on('stdout')` and `vibekit.on('stderr')` over callback options # generateCode (Deprecated) Source: https://docs.vibekit.sh/api-reference/generate-code Generates code using the configured AI agent (Codex or Claude) with optional streaming callbacks and conversation history. **⚠️ DEPRECATED**: The `generateCode` method is deprecated and will be removed in a future version. Please migrate to [`executeCommand`](/api-reference/execute-command) for better flexibility and control. [See migration guide below](#migration-to-executecommand) for how to update your code. ## Method signature ```typescript theme={"dark"} async generateCode({ prompt, mode, branch, history, callbacks, }: { prompt: string; mode: "ask" | "code"; branch?: string; history?: Conversation[]; callbacks?: VibeKitStreamCallbacks; }): Promise ``` ## Parameters | Parameter | Type | Required | Default | Description | | ----------- | ------------------------ | -------- | ------- | ------------------------------------------------------------------- | | `prompt` | `string` | Yes | - | The text prompt describing what code to generate or question to ask | | `mode` | `"ask" \| "code"` | Yes | - | Interactive Q\&A mode (`"ask"`) or code generation mode (`"code"`) | | `branch` | `string` | No | - | Branch identifier for version control or environment context | | `history` | `Conversation[]` | No | - | Previous conversation history to provide context for the generation | | `callbacks` | `VibeKitStreamCallbacks` | No | - | Streaming callbacks for real-time updates | ### VibeKitStreamCallbacks Interface | Property | Type | Required | Description | | ---------- | --------------------------- | -------- | ----------------------------- | | `onUpdate` | `(message: string) => void` | No | Called with streaming updates | | `onError` | `(error: string) => void` | No | Called when errors occur | ## Return value | Type | Description | | ------------------------ | --------------------------------------------------------------------------------------------------- | | `Promise` | Promise that resolves to either a CodexResponse or ClaudeResponse depending on the configured agent | ### CodexResponse (for Codex Agent) | Property | Type | Description | | ----------- | -------- | --------------------------------------------- | | `sandboxId` | `string` | Unique identifier for the sandbox environment | | `stdout` | `string` | Standard output from code execution | | `stderr` | `string` | Standard error from code execution | | `exitCode` | `number` | Exit code from code execution | ### ClaudeResponse (for Claude Agent) | Property | Type | Description | | -------- | -------- | ----------------------- | | `code` | `string` | Generated code response | ## Agent-specific behavior ### Codex Agent * **Streaming Support:** Full streaming support with real-time updates * **Sandbox Environment:** Executes code in isolated E2B sandbox * **Mode Support:** Both "ask" and "code" modes fully supported ### Claude Agent * **Streaming Support:** Limited - provides start/end notifications only * **Execution:** Direct API calls without sandbox environment * **Mode Support:** Both modes supported with fallback behavior ## Examples ### Basic Code Generation ```typescript theme={"dark"} const vibeKit = new VibeKit(config); const response = await vibeKit.generateCode({ prompt: "Create a React component for a todo list", mode: "code" }); console.log(response); ``` ### With Streaming Callbacks ```typescript theme={"dark"} const response = await vibeKit.generateCode({ prompt: "Explain how React hooks work", mode: "ask", callbacks: { onUpdate: (message) => { console.log("Update:", message); }, onError: (error) => { console.error("Error:", error); } } }); ``` ### With Conversation History and Branch ```typescript theme={"dark"} const history = [ { role: "user", content: "What is React?" }, { role: "assistant", content: "React is a JavaScript library..." } ]; const response = await vibeKit.generateCode({ prompt: "Now show me a React component example", mode: "code", branch: "feature-react-components", history }); ``` ## Error handling The method throws errors in the following cases: * **Agent not initialized:** When the configured agent type doesn't match the initialized agent * **Agent-specific errors:** * Codex: Sandbox creation/execution failures, API errors * Claude: API authentication issues, rate limits * **Configuration errors:** Missing required API keys or invalid setup ```typescript theme={"dark"} try { const response = await vibeKit.generateCode({ prompt, mode: "code" }); } catch (error) { if (error.message.includes('not initialized')) { // Handle initialization error } else { // Handle generation error } } ``` ## Migration to executeCommand The `generateCode` method has been deprecated in favor of the more flexible `executeCommand` method. Here's how to migrate your code: ### Basic Migration **Before (generateCode):** ```typescript theme={"dark"} const response = await vibeKit.generateCode({ prompt: "Create a React component for a todo list", mode: "code" }); ``` **After (executeCommand):** ```typescript theme={"dark"} const claudeCommand = `echo "Create a React component for a todo list" | claude -p --output-format stream-json --verbose --allowedTools "Edit,Write,MultiEdit,Read,Bash" --model claude-sonnet-4-20250514`; const response = await vibeKit.executeCommand(claudeCommand); ``` ### With Branch Support **Before (generateCode):** ```typescript theme={"dark"} const response = await vibeKit.generateCode({ prompt: "Create a React component", mode: "code", branch: "feature-react-components" }); ``` **After (executeCommand):** ```typescript theme={"dark"} const claudeCommand = `echo "Create a React component" | claude -p --output-format stream-json --verbose --allowedTools "Edit,Write,MultiEdit,Read,Bash" --model claude-sonnet-4-20250514`; const response = await vibeKit.executeCommand(claudeCommand, { branch: "feature-react-components" }); ``` ### Event Handling Migration **Before (generateCode with callbacks):** ```typescript theme={"dark"} const response = await vibeKit.generateCode({ prompt: "Explain React hooks", mode: "ask", callbacks: { onUpdate: (message) => console.log("Update:", message), onError: (error) => console.error("Error:", error) } }); ``` **After (executeCommand with events):** ```typescript theme={"dark"} vibeKit.on('stdout', (message) => console.log("Update:", message)); vibeKit.on('stderr', (error) => console.error("Error:", error)); const claudeCommand = `echo "Explain React hooks" | claude -p --disallowedTools "Edit" "Replace" "Write" --output-format stream-json --verbose --allowedTools "Edit,Write,MultiEdit,Read,Bash" --model claude-sonnet-4-20250514`; const response = await vibeKit.executeCommand(claudeCommand); ``` ### Agent-Specific Commands For different agents, use these command patterns: **Claude:** ```typescript theme={"dark"} const claudeCommand = `echo "${prompt}" | claude -p --output-format stream-json --verbose --allowedTools "Edit,Write,MultiEdit,Read,Bash" --model claude-sonnet-4-20250514`; ``` **Codex:** ```typescript theme={"dark"} const codexCommand = `codex exec --full-auto --skip-git-repo-check "${prompt}"`; ``` **Gemini:** ```typescript theme={"dark"} const geminiCommand = `echo "${prompt}" | gemini --model gemini-2.5-pro --yolo`; ``` **OpenCode:** ```typescript theme={"dark"} const opencodeCommand = `echo "${prompt}" | opencode run`; ``` **Grok:** ```typescript theme={"dark"} const grokCommand = `echo "${prompt}" | grok --prompt "Help with the following request by providing code or guidance."`; ``` ## Benefits of executeCommand * **More Control:** Direct access to agent CLI commands * **Branch Support:** Automatic git branch switching * **Better Events:** Use standard `stdout`/`stderr` events instead of custom callbacks * **Flexibility:** Execute any shell command in the sandbox environment * **Consistency:** Single method for all command execution needs ## Notes * **Required Mode:** The `mode` parameter is now required and must be specified * **Object Parameters:** All parameters are now passed as a destructured object for better API consistency * **Branch Support:** The optional `branch` parameter allows for version control or environment context * **Streaming Differences:** Codex provides real-time streaming, while Claude only provides start/end notifications * **Environment Support:** Daytona environment is not yet supported and will throw an error * **Conversation Context:** History is preserved across calls to maintain conversation context # getHost Source: https://docs.vibekit.sh/api-reference/get-host Get the host URL for a specific port in the sandbox environment. ## Method signature ```typescript theme={"dark"} public getHost(port: number): string ``` ## Parameters | Parameter | Type | Required | Description | | --------- | -------- | -------- | --------------------------------------- | | `port` | `number` | Yes | The port number to get the host URL for | ## Return value | Type | Description | | -------- | ------------------------------------------------------------------------- | | `string` | The host URL that can be used to access the specified port in the sandbox | ## Examples ### Get Host for Web Server ```typescript theme={"dark"} import { VibeKit } from 'vibekit'; const vibekit = new VibeKit(config); // Start a web server on port 3000 await vibekit.executeCommand('npm run dev -- --port 3000', { background: true }); // Get the host URL for the web server const hostUrl = vibekit.getHost(3000); console.log('Web server accessible at:', hostUrl); // Output: https://3000-sandbox-id.e2b.dev ``` ### Get Host for API Server ```typescript theme={"dark"} // Start an API server await vibekit.executeCommand('python -m http.server 8080', { background: true }); // Get the host URL for the API const apiUrl = vibekit.getHost(8080); console.log('API server accessible at:', apiUrl); // Output: https://8080-sandbox-id.e2b.dev ``` ### Get Host for Database Connection ```typescript theme={"dark"} // Start a database server await vibekit.executeCommand('mongod --port 27017', { background: true }); // Get the host URL for database access const dbHost = vibekit.getHost(27017); console.log('Database accessible at:', dbHost); // Output: https://27017-sandbox-id.e2b.dev ``` ## Error handling The method throws errors in the following cases: * **Sandbox not active:** When called without an active sandbox environment * **Unsupported sandbox:** When called with unsupported sandbox environments (FlyIO, Modal) * **Invalid port:** When the port number is invalid or out of range ```typescript theme={"dark"} try { const hostUrl = vibekit.getHost(3000); console.log('Host URL:', hostUrl); } catch (error) { if (error.message.includes('sandbox')) { console.error('Active sandbox required for getHost functionality'); } else if (error.message.includes('port')) { console.error('Invalid port number provided'); } else { console.error('Failed to get host URL:', error.message); } } ``` ## Sandbox compatibility | Sandbox Type | Supported | Notes | | -------------- | --------- | ------------------------------------------ | | **E2B** | ✅ Yes | Full support with automatic URL generation | | **Daytona** | ✅ Yes | Full support with automatic URL generation | | **Cloudflare** | ✅ Yes | Full support with automatic URL generation | | **Northflank** | ✅ Yes | Full support with automatic URL generation | | **FlyIO** | ❌ No | Port forwarding not yet implemented | | **Modal** | ❌ No | Port forwarding not yet implemented | ## Use cases * **Web Development:** Access development servers running in the sandbox * **API Testing:** Get URLs for API servers to test endpoints * **Database Access:** Connect to databases running in the sandbox * **Microservices:** Access multiple services running on different ports * **Live Previews:** Generate URLs for real-time preview of web applications ## Notes * **Multi-Sandbox Support:** This method is available for E2B, Daytona, Cloudflare and Northflank sandbox environments * **Automatic URL Generation:** Supported sandboxes automatically generate secure HTTPS URLs for exposed ports * **Real-time Access:** URLs are immediately accessible once the service starts on the specified port * **Security:** All generated URLs use HTTPS and are scoped to the specific sandbox instance * **Port Range:** Standard port ranges (1-65535) are supported * **No Port Validation:** The method doesn't validate if a service is actually running on the specified port # getSession Source: https://docs.vibekit.sh/api-reference/get-session Retrieves the current session ID for the sandbox environment. ## Method signature ```typescript theme={"dark"} async getSession(): Promise ``` ## Parameters This method takes no parameters. ## Return value | Type | Description | | ------------------------- | ----------------------------------------------------------------------- | | `Promise` | The current session ID if one is set, or `null` if no session is active | ## Examples ### Basic Usage ```typescript theme={"dark"} const vibeKit = new VibeKit({ agent: { type: "codex", // or "claude" model: { apiKey: "sk-proj-****" }, mode: "code" }, environment: { e2b: { apiKey: "e2b_****" } } }); // Get the current session ID const sessionId = await vibeKit.getSession(); if (sessionId) { console.log("Current session:", sessionId); } else { console.log("No active session"); } ``` ### Session Management Workflow ```typescript theme={"dark"} // Check if there's an existing session let sessionId = await vibeKit.getSession(); if (!sessionId) { // No session exists, generate some code to create one await vibeKit.generateCode("console.log('Hello World')"); // Now get the new session ID sessionId = await vibeKit.getSession(); console.log("New session created:", sessionId); } // Store the session ID for later use localStorage.setItem('vibekit-session', sessionId); ``` ### Error handling ```typescript theme={"dark"} try { const sessionId = await vibeKit.getSession(); console.log("Session ID:", sessionId); } catch (error) { if (error.message.includes('not initialized')) { console.error("Agent is not properly initialized"); } else { console.error("Unexpected error:", error.message); } } ``` ## Error handling The method throws errors in the following cases: ### Initialization Error * **Condition:** When the agent is not properly initialized * **Error Message:** "Agent not initialized" * **Solution:** Verify your configuration includes valid credentials and the agent is properly set up ```typescript theme={"dark"} // Correct configuration for session management const config = { agent: { type: "codex", // or "claude" model: { apiKey: "your-api-key" }, mode: "code" }, environment: { e2b: { apiKey: "your-e2b-api-key" // For Codex agent } // Claude agent may have different environment requirements } }; ``` ## Use cases ### Session Persistence Store and retrieve session IDs to maintain continuity across application restarts: ```typescript theme={"dark"} // On app startup, try to restore previous session const storedSessionId = localStorage.getItem('vibekit-session'); if (storedSessionId) { await vibeKit.setSession(storedSessionId); } // Verify the session is active const currentSession = await vibeKit.getSession(); if (currentSession === storedSessionId) { console.log("Session restored successfully"); } ``` ### Multi-User Applications Track different user sessions in multi-user environments: ```typescript theme={"dark"} async function getUserSession(userId: string) { const currentSession = await vibeKit.getSession(); // Store session mapping if (currentSession) { await database.saveUserSession(userId, currentSession); } return currentSession; } ``` ## Related methods * [`setSession`](./set-session) - Set a specific session ID for the sandbox * [`generateCode`](./generate-code) - Generate code (creates a session if none exists) ## Notes * **Session Auto-Creation:** Sessions are automatically created when you first use `generateCode()` with either agent * **Session Persistence:** Sessions persist across multiple `generateCode()` calls until explicitly changed or the sandbox is terminated * **Null Return:** Returns `null` when no session has been established yet * **Cross-Agent Support:** This functionality works with both Codex and Claude agents # kill Source: https://docs.vibekit.sh/api-reference/kill-sandbox Terminates the active sandbox. ## Method signature ```typescript theme={"dark"} async kill(): Promise ``` ## Parameters This method takes no parameters. ## Return value | Type | Description | | --------------- | ---------------------------------------------------------------- | | `Promise` | The method completes successfully when the sandbox is terminated | ## Behavior The `kill()` method performs the following actions: 1. **Agent Type Validation**: Verifies that the current agent is of type "codex" 2. **Initialization Check**: Ensures the CodexAgent instance is properly initialized 3. **Sandbox Termination**: Calls the underlying `killSandbox()` method to terminate the active sandbox ## Examples ### Basic Usage ```typescript theme={"dark"} const vibeKit = new VibeKit({ agent: { type: "codex", // ... other config } }); // Generate some code first to create a sandbox await vibeKit.generateCode("console.log('Hello World')", "code"); // Kill the sandbox when done await vibeKit.kill(); console.log("Sandbox terminated successfully"); ``` ### With Error Handling ```typescript theme={"dark"} try { await vibeKit.kill(); console.log("Sandbox terminated"); } catch (error) { if (error.message.includes("only supported for the Codex agent")) { console.error("Kill operation requires Codex agent"); } else if (error.message.includes("not initialized")) { console.error("CodexAgent not properly initialized"); } else { console.error("Failed to kill sandbox:", error.message); } } ``` ### Cleanup Pattern ```typescript theme={"dark"} class CodeGenerator { private vibeKit: VibeKit; constructor(config: VibeKitConfig) { this.vibeKit = new VibeKit(config); } async generateAndCleanup(prompt: string) { try { // Generate code const response = await this.vibeKit.generateCode(prompt, "code"); // Process the response console.log("Generated code:", response); return response; } finally { // Always cleanup the sandbox await this.vibeKit.kill(); } } } ``` ## Error handling The method throws errors in the following cases: ### Agent Type Error ```typescript theme={"dark"} // When using non-Codex agent throw new Error("Sandbox management is only supported for the Codex agent"); ``` ### Initialization Error ```typescript theme={"dark"} // When CodexAgent is not initialized throw new Error("CodexAgent not initialized"); ``` ### Example Error Handling ```typescript theme={"dark"} try { await vibeKit.kill(); } catch (error) { switch (true) { case error.message.includes("only supported for the Codex agent"): // Handle agent type mismatch console.error("This operation requires a Codex agent"); break; case error.message.includes("not initialized"): // Handle initialization error console.error("Agent not properly initialized"); break; default: // Handle other sandbox-related errors console.error("Sandbox termination failed:", error.message); } } ``` ## Use cases ### Resource Management Perfect for cleaning up sandbox resources when your application is done with code generation: ```typescript theme={"dark"} // After batch processing const prompts = ["task1", "task2", "task3"]; for (const prompt of prompts) { await vibeKit.generateCode(prompt, "code"); } // Cleanup when done await vibeKit.kill(); ``` ### Error Recovery Use in error handling to ensure sandbox cleanup: ```typescript theme={"dark"} try { await vibeKit.generateCode(complexPrompt, "code"); } catch (generationError) { console.error("Generation failed:", generationError); // Cleanup potentially corrupted sandbox await vibeKit.kill(); throw generationError; } ``` ## Notes * **Resource Cleanup**: Always call `kill()` when you're done with sandbox operations to free up resources * **State Reset**: Killing a sandbox destroys all its state and files * **Irreversible**: Once killed, the sandbox cannot be resumed - you'll need to generate new code to create a fresh sandbox * **Best Practice**: Use in cleanup routines and error handlers to prevent resource leaks # mergePullRequest Source: https://docs.vibekit.sh/api-reference/merge-pull-request Merge an existing pull request on GitHub ## Overview The `mergePullRequest` method allows you to programmatically merge an existing pull request on GitHub. It supports different merge methods (merge, squash, rebase) and allows customization of the commit message. ## Method Signature ```typescript theme={"dark"} async mergePullRequest( options: MergePullRequestOptions & { repository: string } ): Promise ``` ## Parameters ### MergePullRequestOptions | Parameter | Type | Required | Description | | --------------- | --------------------------------- | -------- | --------------------------------------------- | | `repository` | `string` | Yes | The GitHub repository in format "owner/repo" | | `pullNumber` | `number` | Yes | The number of the pull request to merge | | `commitTitle` | `string` | No | Custom title for the merge commit | | `commitMessage` | `string` | No | Custom message for the merge commit | | `mergeMethod` | `'merge' \| 'squash' \| 'rebase'` | No | The merge method to use (defaults to 'merge') | ### Merge Methods * **`merge`**: Creates a merge commit with all commits from the feature branch * **`squash`**: Squashes all commits into a single commit before merging * **`rebase`**: Rebases the commits onto the base branch ## Return Value ### MergePullRequestResult | Property | Type | Description | | --------- | --------- | ------------------------------------------------ | | `sha` | `string` | The SHA of the merge commit | | `merged` | `boolean` | Whether the pull request was successfully merged | | `message` | `string` | A message describing the merge result | ## Prerequisites Before using this method, ensure: 1. **GitHub Configuration**: You only need to configure GitHub credentials using secrets: ```typescript theme={"dark"} vibekit.withSecrets({ GH_TOKEN: "your-github-token" }) ``` Note: Unlike other methods, `mergePullRequest` does NOT require agent or sandbox configuration. 2. **Pull Request State**: The pull request must be: * Open and not already merged * Free of merge conflicts * Passing all required status checks * Approved if required by branch protection rules ## Usage Examples ### Basic Merge ```typescript theme={"dark"} import { VibeKit } from "vibekit"; const vibekit = new VibeKit() .withSecrets({ GH_TOKEN: process.env.GITHUB_TOKEN, }); // Merge a pull request with default settings const mergeResult = await vibekit.mergePullRequest({ repository: "myorg/myrepo", pullNumber: 42 }); console.log(`PR merged with commit SHA: ${mergeResult.sha}`); ``` ### Squash and Merge ```typescript theme={"dark"} // Squash all commits and merge with a custom message const mergeResult = await vibekit.mergePullRequest({ repository: "myorg/myrepo", pullNumber: 42, mergeMethod: "squash", commitTitle: "feat: Add new feature", commitMessage: "This PR adds the new feature with the following changes:\n- Added X\n- Updated Y\n- Fixed Z" }); ``` ### Complete Workflow Example ```typescript theme={"dark"} import { VibeKit } from "vibekit"; import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY!, }); // For operations that require code generation, you'll need agent and sandbox const vibkitWithAgent = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY, model: "claude-sonnet-4-20250514" }) .withSandbox(e2bProvider) .withSecrets({ GH_TOKEN: process.env.GITHUB_TOKEN, }); // Clone repository and generate code changes await vibkitWithAgent.cloneRepository("myorg/myrepo"); await vibkitWithAgent.generateCode({ prompt: "Add a new user authentication feature", mode: "code", branch: "feature/auth" }); await vibkitWithAgent.pushToBranch(); const prResponse = await vibkitWithAgent.createPullRequest( "myorg/myrepo", // Repository parameter now required { name: "feature", color: "0366d6", description: "New feature" }, "feature" ); console.log(`Created PR #${prResponse.number}`); // After review and approval, merge the PR (only needs GitHub config) const vibkitSimple = new VibeKit() .withSecrets({ GH_TOKEN: process.env.GITHUB_TOKEN, }); const mergeResult = await vibkitSimple.mergePullRequest({ repository: "myorg/myrepo", // Repository parameter now required pullNumber: prResponse.number, mergeMethod: "squash" }); if (mergeResult.merged) { console.log(`Successfully merged PR #${prResponse.number}`); } ``` ## Error Handling The method will throw an error in the following cases: ### Configuration Errors * Missing GitHub token or repository configuration * Invalid repository URL format ### Pull Request Errors * **404**: Pull request not found * **405**: Pull request is not mergeable (conflicts or failed checks) * **422**: Invalid merge parameters or validation failed ### Example Error Handling ```typescript theme={"dark"} try { const result = await vibekit.mergePullRequest({ repository: "myorg/myrepo", pullNumber: 42, mergeMethod: "squash" }); if (result.merged) { console.log("Pull request successfully merged!"); } } catch (error) { if (error.message.includes("not mergeable")) { console.error("PR has conflicts or failed status checks"); } else if (error.message.includes("not found")) { console.error("PR does not exist"); } else { console.error("Failed to merge PR:", error.message); } } ``` ## Notes * **No agent or sandbox required**: This method only needs GitHub configuration * The method requires appropriate GitHub permissions (write access to the repository) * Branch protection rules will be enforced * The merge will respect all repository settings and requirements * After a successful merge, the source branch may be automatically deleted depending on repository settings * This is a direct GitHub API call - no code execution or AI processing is involved ## Related Methods * [`createPullRequest`](/api-reference/create-pull-request) - Create a new pull request * [`pushToBranch`](/api-reference/push-to-branch) - Push changes to a branch * [`generateCode`](/api-reference/generate-code) - Generate code using AI agents # pause Source: https://docs.vibekit.sh/api-reference/pause-sandbox Pauses the active sandbox. ## Method signature ```typescript theme={"dark"} async pause(): Promise ``` ## Parameters This method takes no parameters. ## Return value | Type | Description | | --------------- | ------------------------------------------------------------ | | `Promise` | The method completes successfully when the sandbox is paused | ## Behavior The `pause()` method performs the following actions: 1. **Agent Type Validation**: Verifies that the current agent is of type "codex" 2. **Initialization Check**: Ensures the CodexAgent instance is properly initialized 3. **Sandbox Pausing**: Calls the underlying `pauseSandbox()` method to pause the active sandbox ## Examples ### Basic Usage ```typescript theme={"dark"} const vibeKit = new VibeKit({ agent: { type: "codex", // ... other config } }); // Generate some code first to create a sandbox await vibeKit.generateCode("console.log('Hello World')", "code"); // Pause the sandbox to save resources await vibeKit.pause(); console.log("Sandbox paused successfully"); // Later, resume the sandbox await vibeKit.resume(); ``` ### With Error Handling ```typescript theme={"dark"} try { await vibeKit.pause(); console.log("Sandbox paused"); } catch (error) { if (error.message.includes("only supported for the Codex agent")) { console.error("Pause operation requires Codex agent"); } else if (error.message.includes("not initialized")) { console.error("CodexAgent not properly initialized"); } else { console.error("Failed to pause sandbox:", error.message); } } ``` ### Resource Management Pattern ```typescript theme={"dark"} class SandboxManager { private vibeKit: VibeKit; private isPaused: boolean = false; constructor(config: VibeKitConfig) { this.vibeKit = new VibeKit(config); } async pauseForBreak() { if (!this.isPaused) { await this.vibeKit.pause(); this.isPaused = true; console.log("Sandbox paused for break"); } } async resumeFromBreak() { if (this.isPaused) { await this.vibeKit.resume(); this.isPaused = false; console.log("Sandbox resumed from break"); } } async generateCode(prompt: string) { // Resume if paused if (this.isPaused) { await this.resumeFromBreak(); } return await this.vibeKit.generateCode(prompt, "code"); } } ``` ### Auto-Pause on Inactivity ```typescript theme={"dark"} class AutoPausingSandbox { private vibeKit: VibeKit; private inactivityTimer: NodeJS.Timeout | null = null; private readonly INACTIVITY_TIMEOUT = 5 * 60 * 1000; // 5 minutes constructor(config: VibeKitConfig) { this.vibeKit = new VibeKit(config); } async generateCode(prompt: string) { // Clear existing timer this.clearInactivityTimer(); // Generate code const response = await this.vibeKit.generateCode(prompt, "code"); // Start new inactivity timer this.startInactivityTimer(); return response; } private startInactivityTimer() { this.inactivityTimer = setTimeout(async () => { try { await this.vibeKit.pause(); console.log("Sandbox auto-paused due to inactivity"); } catch (error) { console.error("Failed to auto-pause sandbox:", error); } }, this.INACTIVITY_TIMEOUT); } private clearInactivityTimer() { if (this.inactivityTimer) { clearTimeout(this.inactivityTimer); this.inactivityTimer = null; } } } ``` ## Error handling The method throws errors in the following cases: ### Agent Type Error ```typescript theme={"dark"} // When using non-Codex agent throw new Error("Sandbox management is only supported for the Codex agent"); ``` ### Initialization Error ```typescript theme={"dark"} // When CodexAgent is not initialized throw new Error("CodexAgent not initialized"); ``` ### Example Error Handling ```typescript theme={"dark"} try { await vibeKit.pause(); } catch (error) { switch (true) { case error.message.includes("only supported for the Codex agent"): // Handle agent type mismatch console.error("This operation requires a Codex agent"); break; case error.message.includes("not initialized"): // Handle initialization error console.error("Agent not properly initialized"); break; default: // Handle other sandbox-related errors console.error("Sandbox pause failed:", error.message); } } ``` ## Use cases ### Cost Optimization Pause sandboxes during periods of inactivity to reduce resource costs: ```typescript theme={"dark"} // During lunch break or after hours await vibeKit.pause(); console.log("Sandbox paused - resources saved"); ``` ### Batch Processing with Breaks Pause between processing batches to manage resource usage: ```typescript theme={"dark"} const batches = [batch1, batch2, batch3]; for (let i = 0; i < batches.length; i++) { const batch = batches[i]; // Process batch for (const prompt of batch) { await vibeKit.generateCode(prompt, "code"); } // Pause between batches (except for the last one) if (i < batches.length - 1) { await vibeKit.pause(); console.log(`Batch ${i + 1} completed. Sandbox paused.`); // Simulate break time await new Promise(resolve => setTimeout(resolve, 30000)); // 30 seconds await vibeKit.resume(); console.log(`Resuming for batch ${i + 2}`); } } ``` ### Conditional Resource Management Pause based on system conditions: ```typescript theme={"dark"} class ResourceAwareSandbox { private vibeKit: VibeKit; constructor(config: VibeKitConfig) { this.vibeKit = new VibeKit(config); } async smartPause() { const memoryUsage = process.memoryUsage(); const highMemoryUsage = memoryUsage.heapUsed > 100 * 1024 * 1024; // 100MB if (highMemoryUsage) { await this.vibeKit.pause(); console.log("Sandbox paused due to high memory usage"); // Force garbage collection if available if (global.gc) { global.gc(); } } } } ``` ## State preservation When a sandbox is paused, its state is preserved including: * File system contents * Environment variables * Running processes (suspended) * Network connections (may timeout) ## Notes * **State Preservation**: Pausing preserves the sandbox state, unlike `kill()` which destroys it * **Resource Savings**: Paused sandboxes consume significantly fewer resources * **Resumable**: Use `resume()` to continue from exactly where you left off * **Best Practice**: Pause during periods of inactivity to optimize resource usage and costs * **Automatic Cleanup**: Consider implementing auto-pause mechanisms for long-running applications # pushToBranch Source: https://docs.vibekit.sh/api-reference/push-to-branch Push code changes to a branch. ## Method signature ```typescript theme={"dark"} async pushToBranch(branch?: string): Promise ``` ## Description Pushes the current code changes from the sandbox environment to a specified Git branch. This method is useful when you want to save your generated code changes to a branch without creating a pull request. ## Parameters The name of the branch to push changes to. If not provided, pushes to the current active branch or the default branch configured in the agent. ## Return value Returns a `Promise` that resolves when the push operation completes successfully. ## Usage example ```typescript theme={"dark"} import { VibeKit } from "vibekit"; const vibekit = new VibeKit({ agent: { type: "claude", model: { name: "claude-3-5-sonnet-20241022", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY, }, }, github: { token: process.env.GITHUB_TOKEN, repository: "https://github.com/your-org/your-repo", }, environment: { e2b: { apiKey: process.env.E2B_API_KEY, }, }, sessionId: "unique-session-id", }); // Generate some code changes await vibekit.generateCode({ prompt: "Add a new React component for user profiles", mode: "code", branch: "feature/user-profiles", }); // Or push to the current/default branch await vibekit.pushToBranch(); ``` ## Notes * This method requires that the VibeKit instance is configured with GitHub credentials * The branch must exist in the repository, or the agent must have permissions to create it * Changes are pushed directly without creating a pull request - use `createPullRequest()` if you want to create a PR instead * This operation is available for both Codex and Claude agents ## Related methods * [`createPullRequest()`](/api-reference/create-pull-request) - Create a pull request with the current changes * [`generateCode()`](/api-reference/generate-code) - Generate code changes before pushing # resume Source: https://docs.vibekit.sh/api-reference/resume-sandbox Resumes the paused sandbox. ## Method signature ```typescript theme={"dark"} async resume(): Promise ``` ## Parameters This method takes no parameters. ## Return value | Type | Description | | --------------- | ------------------------------------------------------------- | | `Promise` | The method completes successfully when the sandbox is resumed | ## Behavior The `resume()` method performs the following actions: 1. **Agent Type Validation**: Verifies that the current agent is of type "codex" 2. **Initialization Check**: Ensures the CodexAgent instance is properly initialized 3. **Sandbox Resumption**: Calls the underlying `resumeSandbox()` method to resume the paused sandbox ## Examples ### Basic Usage ```typescript theme={"dark"} const vibeKit = new VibeKit({ agent: { type: "codex", // ... other config } }); // Generate some code first to create a sandbox await vibeKit.generateCode("console.log('Hello World')", "code"); // Pause the sandbox await vibeKit.pause(); console.log("Sandbox paused"); // Resume the sandbox await vibeKit.resume(); console.log("Sandbox resumed - ready for more operations"); // Continue generating code await vibeKit.generateCode("console.log('Back online!')", "code"); ``` ### With Error Handling ```typescript theme={"dark"} try { await vibeKit.resume(); console.log("Sandbox resumed successfully"); } catch (error) { if (error.message.includes("only supported for the Codex agent")) { console.error("Resume operation requires Codex agent"); } else if (error.message.includes("not initialized")) { console.error("CodexAgent not properly initialized"); } else { console.error("Failed to resume sandbox:", error.message); } } ``` ### State Management Pattern ```typescript theme={"dark"} class SandboxStateManager { private vibeKit: VibeKit; private state: 'active' | 'paused' | 'killed' = 'active'; constructor(config: VibeKitConfig) { this.vibeKit = new VibeKit(config); } async pause() { if (this.state === 'active') { await this.vibeKit.pause(); this.state = 'paused'; console.log("Sandbox paused"); } } async resume() { if (this.state === 'paused') { await this.vibeKit.resume(); this.state = 'active'; console.log("Sandbox resumed"); } } async generateCode(prompt: string) { // Auto-resume if paused if (this.state === 'paused') { await this.resume(); } if (this.state === 'killed') { throw new Error("Cannot generate code: sandbox has been killed"); } return await this.vibeKit.generateCode(prompt, "code"); } getState() { return this.state; } } ``` ### Auto-Resume on Activity ```typescript theme={"dark"} class SmartSandbox { private vibeKit: VibeKit; private isPaused: boolean = false; constructor(config: VibeKitConfig) { this.vibeKit = new VibeKit(config); } async ensureActive() { if (this.isPaused) { await this.vibeKit.resume(); this.isPaused = false; console.log("Sandbox auto-resumed"); } } async generateCode(prompt: string) { // Auto-resume before generating code await this.ensureActive(); return await this.vibeKit.generateCode(prompt, "code"); } async pauseManually() { if (!this.isPaused) { await this.vibeKit.pause(); this.isPaused = true; console.log("Sandbox paused manually"); } } } ``` ### Scheduled Resume ```typescript theme={"dark"} class ScheduledSandbox { private vibeKit: VibeKit; private resumeTimer: NodeJS.Timeout | null = null; constructor(config: VibeKitConfig) { this.vibeKit = new VibeKit(config); } async pauseWithScheduledResume(resumeInMinutes: number) { // Pause sandbox await this.vibeKit.pause(); console.log(`Sandbox paused. Will resume in ${resumeInMinutes} minutes.`); // Schedule resume this.resumeTimer = setTimeout(async () => { try { await this.vibeKit.resume(); console.log("Sandbox automatically resumed"); } catch (error) { console.error("Failed to auto-resume sandbox:", error); } }, resumeInMinutes * 60 * 1000); } async resumeNow() { // Clear scheduled resume if (this.resumeTimer) { clearTimeout(this.resumeTimer); this.resumeTimer = null; } // Resume immediately await this.vibeKit.resume(); console.log("Sandbox resumed immediately"); } async cleanup() { if (this.resumeTimer) { clearTimeout(this.resumeTimer); } await this.vibeKit.kill(); } } ``` ## Error handling The method throws errors in the following cases: ### Agent Type Error ```typescript theme={"dark"} // When using non-Codex agent throw new Error("Sandbox management is only supported for the Codex agent"); ``` ### Initialization Error ```typescript theme={"dark"} // When CodexAgent is not initialized throw new Error("CodexAgent not initialized"); ``` ### Example Error Handling ```typescript theme={"dark"} try { await vibeKit.resume(); } catch (error) { switch (true) { case error.message.includes("only supported for the Codex agent"): // Handle agent type mismatch console.error("This operation requires a Codex agent"); break; case error.message.includes("not initialized"): // Handle initialization error console.error("Agent not properly initialized"); break; default: // Handle other sandbox-related errors console.error("Sandbox resume failed:", error.message); } } ``` ## Use Cases ### Morning Startup Routine Resume sandboxes at the start of the workday: ```typescript theme={"dark"} class DailySandboxManager { private vibeKit: VibeKit; constructor(config: VibeKitConfig) { this.vibeKit = new VibeKit(config); } async morningStartup() { console.log("Starting daily sandbox routine..."); try { await this.vibeKit.resume(); console.log("✅ Sandbox resumed for the day"); // Run any initialization code await this.vibeKit.generateCode("echo 'Good morning! Sandbox is ready.'", "code"); } catch (error) { console.error("❌ Failed to start sandbox:", error); throw error; } } async eveningShutdown() { console.log("Ending daily sandbox routine..."); await this.vibeKit.pause(); console.log("✅ Sandbox paused for the night"); } } ``` ### On-Demand Resumption Resume only when needed to save resources: ```typescript theme={"dark"} class OnDemandSandbox { private vibeKit: VibeKit; private isActive: boolean = false; constructor(config: VibeKitConfig) { this.vibeKit = new VibeKit(config); } async processRequest(prompt: string) { if (!this.isActive) { console.log("Resuming sandbox for request..."); await this.vibeKit.resume(); this.isActive = true; } const response = await this.vibeKit.generateCode(prompt, "code"); // Auto-pause after 30 seconds of inactivity setTimeout(async () => { if (this.isActive) { await this.vibeKit.pause(); this.isActive = false; console.log("Sandbox auto-paused after inactivity"); } }, 30000); return response; } } ``` ### Recovery from Breaks Resume after planned breaks or maintenance: ```typescript theme={"dark"} class MaintenanceAwareSandbox { private vibeKit: VibeKit; constructor(config: VibeKitConfig) { this.vibeKit = new VibeKit(config); } async pauseForMaintenance(durationMinutes: number) { await this.vibeKit.pause(); console.log(`Sandbox paused for ${durationMinutes} minute maintenance window`); return new Promise((resolve) => { setTimeout(async () => { await this.vibeKit.resume(); console.log("Maintenance complete. Sandbox resumed."); resolve(void 0); }, durationMinutes * 60 * 1000); }); } async emergencyResume() { console.log("Emergency resume initiated..."); await this.vibeKit.resume(); console.log("Sandbox resumed for emergency operation"); } } ``` ## State Restoration When a sandbox is resumed, all previously saved state is restored including: * File system contents (exactly as they were when paused) * Environment variables * Working directory * Previously installed packages ## Performance Considerations ### Resume Time * **Cold Resume**: First resume after a long pause may take 10-30 seconds * **Warm Resume**: Subsequent resumes are typically faster (5-15 seconds) * **State Check**: The sandbox performs internal state validation during resume ### Resource Usage ```typescript theme={"dark"} // Monitor resume performance const startTime = Date.now(); await vibeKit.resume(); const resumeTime = Date.now() - startTime; console.log(`Sandbox resumed in ${resumeTime}ms`); ``` ## Notes * **State Continuity**: All sandbox state is preserved and restored exactly as it was when paused * **Process Restoration**: Running processes are resumed from their paused state * **Network Connections**: Some network connections may need to be re-established * **File System**: All files and directories remain exactly as they were * **Best Practice**: Always resume before attempting to generate new code on a paused sandbox * **Automatic Resume**: Consider implementing automatic resume logic in your application flow # runTests Source: https://docs.vibekit.sh/api-reference/run-tests Execute tests in the sandbox environment with automatic test runner detection ## Overview The `runTests` method executes tests in the sandbox environment and automatically detects the appropriate test runner (e.g., npm test, pytest, cargo test, etc.). This method supports both streaming and non-streaming execution modes. ## Method Signature ```typescript theme={"dark"} async runTests({ branch, history, callbacks, }: { branch?: string; history?: Conversation[]; callbacks?: VibeKitStreamCallbacks; }): Promise ``` ## Parameters The Git branch to run tests on. If not specified, tests will run on the current branch. Optional conversation history to provide context for the test execution. This can help the agent understand previous interactions and make more informed decisions about test execution. Optional callbacks for streaming updates during test execution. Callback function that receives streaming updates during test execution. Callback function that receives error messages during test execution. ## Return Value Returns a `Promise` containing the test execution results: The ID of the sandbox where tests were executed Standard output from the test execution Standard error output from the test execution Exit code from the test execution (0 indicates success) ## Examples ### Basic Test Execution ```typescript theme={"dark"} import { VibeKit } from 'vibekit'; const vibekit = new VibeKit({ agent: { type: 'codex', model: { provider: 'openai', name: 'gpt-4', apiKey: process.env.OPENAI_API_KEY } }, environment: 'e2b', sessionId: 'test-session' }); // Run tests on current branch const result = await vibekit.runTests({}); console.log('Tests completed with exit code:', result.exitCode); console.log('Test output:', result.stdout); ``` ### Run Tests on Specific Branch ```typescript theme={"dark"} // Run tests on a specific branch const result = await vibekit.runTests({ branch: 'feature/new-functionality' }); if (result.exitCode === 0) { console.log('All tests passed!'); } else { console.log('Some tests failed:', result.stderr); } ``` ### Streaming Test Execution ```typescript theme={"dark"} // Run tests with streaming updates const result = await vibekit.runTests({ callbacks: { onUpdate: (message) => { console.log('Test update:', message); }, onError: (error) => { console.error('Test error:', error); } } }); ``` ### Run Tests with Context ```typescript theme={"dark"} // Run tests with conversation history for context const history = [ { role: 'user', content: 'I just added a new authentication feature' }, { role: 'assistant', content: 'I understand. Let me run the tests to ensure everything works correctly.' } ]; const result = await vibekit.runTests({ branch: 'feature/auth', history: history, callbacks: { onUpdate: (message) => { console.log(message); } } }); ``` ## Test Runner Detection The `runTests` method automatically detects and uses the appropriate test runner based on the project structure: * **Node.js**: Runs `npm test` or `yarn test` * **Python**: Runs `pytest`, `python -m unittest`, or `python -m pytest` * **Rust**: Runs `cargo test` * **Go**: Runs `go test` * **And more**: Supports various other testing frameworks ## Error Handling ```typescript theme={"dark"} try { const result = await vibekit.runTests({ branch: 'main' }); if (result.exitCode !== 0) { console.log('Tests failed with errors:', result.stderr); } } catch (error) { console.error('Failed to run tests:', error.message); } ``` ## Notes * The method requires an active sandbox environment * Test execution is performed within the sandbox, ensuring a clean and isolated environment * The agent will attempt to install dependencies if they're missing * Streaming callbacks provide real-time feedback during test execution * The method works with both Codex and Claude agents # setSession Source: https://docs.vibekit.sh/api-reference/set-session Sets the session ID for the sandbox environment. This method allows you to restore or switch between existing sandbox sessions. ## Method signature ```typescript theme={"dark"} async setSession(sessionId: string): Promise ``` ## Parameters | Parameter | Type | Required | Description | | ----------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------ | | `sessionId` | `string` | Yes | The session ID to set for the sandbox environment. Must be a valid session identifier from a previously created session. | ## Return value | Type | Description | | --------------- | ------------------------------------------------------------------------------------ | | `Promise` | This method doesn't return a value but resolves when the session is successfully set | ## Examples ### Basic Usage ```typescript theme={"dark"} const vibeKit = new VibeKit({ agent: { type: "codex", // or "claude" model: { apiKey: "sk-proj-****" }, mode: "code" }, environment: { e2b: { apiKey: "e2b_****" } } }); // Set a specific session ID await vibeKit.setSession("session-abc123"); // Verify the session was set const currentSession = await vibeKit.getSession(); console.log("Active session:", currentSession); // "session-abc123" ``` ### Session Switching ```typescript theme={"dark"} // Get the current session const originalSession = await vibeKit.getSession(); console.log("Original session:", originalSession); // Switch to a different session await vibeKit.setSession("session-xyz789"); // Work in the new session await vibeKit.generateCode("print('Working in new session')"); // Switch back to the original session if (originalSession) { await vibeKit.setSession(originalSession); console.log("Switched back to original session"); } ``` ### Session Restoration ```typescript theme={"dark"} // Restore a session from storage const savedSessionId = localStorage.getItem('vibekit-session'); if (savedSessionId) { try { await vibeKit.setSession(savedSessionId); console.log("Session restored successfully"); // Continue work in the restored session await vibeKit.generateCode("# Continuing previous work"); } catch (error) { console.error("Failed to restore session:", error); // Handle invalid or expired session } } ``` ### Multi-Project Workflow ```typescript theme={"dark"} // Define session IDs for different projects const sessions = { projectA: "session-project-a-123", projectB: "session-project-b-456", projectC: "session-project-c-789" }; // Switch between projects async function switchToProject(projectName: keyof typeof sessions) { const sessionId = sessions[projectName]; await vibeKit.setSession(sessionId); console.log(`Switched to ${projectName} (${sessionId})`); // Generate project-specific code await vibeKit.generateCode(`# Working on ${projectName}`); } // Usage await switchToProject('projectA'); await switchToProject('projectB'); ``` ## Error handling The method throws errors in the following cases: ### Initialization Error * **Condition:** When the agent is not properly initialized * **Error Message:** "Agent not initialized" * **Solution:** Verify your configuration includes valid credentials and the agent is properly set up ### Invalid Session Error * **Condition:** When the provided session ID is invalid or expired * **Behavior:** May throw sandbox-specific errors or fail silently depending on the underlying implementation ```typescript theme={"dark"} try { await vibeKit.setSession("invalid-session-id"); } catch (error) { if (error.message.includes('not initialized')) { console.error("Agent is not properly initialized"); } else { console.error("Failed to set session:", error.message); // Handle invalid session ID } } ``` ## Configuration requirements ```typescript theme={"dark"} // Correct configuration for session management const config = { agent: { type: "codex", // or "claude" model: { apiKey: "your-api-key" }, mode: "code" }, environment: { e2b: { apiKey: "your-e2b-api-key" // For Codex agent } // Claude agent may have different environment requirements } }; ``` ## Use cases ### Session Persistence Across App Restarts ```typescript theme={"dark"} class SessionManager { private vibeKit: VibeKit; constructor(vibeKit: VibeKit) { this.vibeKit = vibeKit; } async saveCurrentSession(): Promise { const sessionId = await this.vibeKit.getSession(); if (sessionId) { localStorage.setItem('vibekit-session', sessionId); } } async restoreSession(): Promise { const savedSession = localStorage.getItem('vibekit-session'); if (savedSession) { try { await this.vibeKit.setSession(savedSession); return true; } catch (error) { console.error('Failed to restore session:', error); // Clean up invalid session localStorage.removeItem('vibekit-session'); } } return false; } } ``` ### Multi-User Session Management ```typescript theme={"dark"} class MultiUserSessionManager { private vibeKit: VibeKit; private userSessions = new Map(); constructor(vibeKit: VibeKit) { this.vibeKit = vibeKit; } async switchUser(userId: string): Promise { const userSessionId = this.userSessions.get(userId); if (userSessionId) { // User has an existing session await this.vibeKit.setSession(userSessionId); } else { // Create new session for user await this.vibeKit.generateCode("# Starting new session"); const newSessionId = await this.vibeKit.getSession(); if (newSessionId) { this.userSessions.set(userId, newSessionId); } } } async getCurrentUserSession(): Promise { return await this.vibeKit.getSession(); } } ``` ### Project-Based Session Isolation ```typescript theme={"dark"} interface ProjectSession { id: string; name: string; sessionId: string; lastAccessed: Date; } class ProjectManager { private vibeKit: VibeKit; private projects: ProjectSession[] = []; constructor(vibeKit: VibeKit) { this.vibeKit = vibeKit; } async switchToProject(projectId: string): Promise { const project = this.projects.find(p => p.id === projectId); if (project) { await this.vibeKit.setSession(project.sessionId); project.lastAccessed = new Date(); console.log(`Switched to project: ${project.name}`); } else { throw new Error(`Project ${projectId} not found`); } } async createProject(name: string): Promise { // Create a new session for the project await this.vibeKit.generateCode(`# Project: ${name}`); const sessionId = await this.vibeKit.getSession(); if (!sessionId) { throw new Error("Failed to create session for project"); } const project: ProjectSession = { id: crypto.randomUUID(), name, sessionId, lastAccessed: new Date() }; this.projects.push(project); return project.id; } } ``` ## Related methods * [`getSession`](./get-session) - Retrieve the current session ID * [`generateCode`](./generate-code) - Generate code (creates a session if none exists) ## Notes * **Session Validation:** The method doesn't validate if the session ID exists or is accessible until subsequent operations * **Session Switching:** You can switch between sessions at any time using this method * **State Isolation:** Each session maintains its own sandbox state and file system * **Cross-Agent Support:** This functionality works with both Codex and Claude agents * **No Return Value:** The method resolves with `void` when successful * **Immediate Effect:** The session change takes effect immediately for subsequent operations # null Source: https://docs.vibekit.sh/auth/browser # Browser Usage For browser/web applications, use the browser-safe import that works without Node.js-specific features like file system access. ## Basic Setup ```typescript theme={"dark"} import { ClaudeWebAuth, LocalStorageTokenStorage } from '@vibe-kit/auth/browser'; // OR use the default import which is browser-safe: // import { ClaudeAuth, LocalStorageTokenStorage } from '@vibe-kit/auth'; // Create storage const storage = new LocalStorageTokenStorage(); const auth = new ClaudeWebAuth(storage); ``` ## Authentication Flow ```typescript theme={"dark"} // Create authorization URL const { url, state, codeVerifier } = ClaudeWebAuth.createAuthorizationUrl(); // Open URL in browser for user authentication window.open(url, '_blank'); // After user authorizes and provides the code#state string: const authCode = 'code123#state456'; // From user input const token = await auth.authenticate(authCode, codeVerifier, state); ``` ## Token Management ```typescript theme={"dark"} // Check authentication status const isAuthenticated = await auth.isAuthenticated(); // Get valid token (auto-refresh if needed) const accessToken = await auth.getValidToken(); // Use token with AI provider APIs if (!accessToken) { // Handle authentication flow... } ``` ## Using with AI Provider APIs ### Claude AI (Available Now) ```typescript theme={"dark"} import { ClaudeWebAuth, LocalStorageTokenStorage } from '@vibe-kit/auth/browser'; const storage = new LocalStorageTokenStorage(); const auth = new ClaudeWebAuth(storage); // Get token (assumes user is already authenticated) const accessToken = await auth.getValidToken(); if (!accessToken) { // Handle authentication flow... } // Use with Claude Code CLI // First, export the token as an environment variable: // export CLAUDE_CODE_OAUTH_TOKEN=${accessToken} // claude -p 'Hello!' ``` ## Storage Options Browser environments support multiple storage options: * **LocalStorageTokenStorage**: Browser localStorage (client-side only) * **CookieTokenStorage**: Cookie-based storage for SSR applications ```typescript theme={"dark"} import { ClaudeWebAuth, LocalStorageTokenStorage, CookieTokenStorage } from '@vibe-kit/auth/browser'; // Using localStorage (most common) const localAuth = new ClaudeWebAuth(new LocalStorageTokenStorage()); // Using cookies (for SSR) const cookieAuth = new ClaudeWebAuth(new CookieTokenStorage()); ``` # Introduction Source: https://docs.vibekit.sh/auth/index Universal OAuth authentication library for AI providers' MAX subscriptions. Currently supports Claude AI with Gemini, Grok, and ChatGPT Max coming soon. The @vibe-kit/auth package provides secure OAuth authentication for AI providers' MAX subscriptions, allowing you to leverage your existing subscriptions programmatically instead of paying per API call. ## Key Features Use your existing AI provider MAX subscriptions instead of pay-per-use APIs Claude AI available now, with Gemini, Grok, and ChatGPT Max coming soon Industry-standard security with automatic token refresh and secure storage Works in both Node.js and browser environments with appropriate builds ## Getting Started Server-side authentication with automatic browser launching Client-side authentication for web applications ## Try It Out Experience the authentication flow with our interactive demo template: Complete Next.js application demonstrating OAuth flow with Claude AI ## Why Use MAX Subscriptions? Instead of paying per API call, leverage the subscriptions you already have: * **Cost Effective**: Use your existing MAX subscriptions instead of pay-per-use APIs * **Higher Limits**: MAX subscriptions often have higher rate limits and priority access * **Latest Models**: Access to the newest and most capable models in each provider's lineup * **Consistent Experience**: Same interface across different AI providers Whether you're building a CLI tool, web application, or any project that needs AI capabilities, @vibe-kit/auth provides a secure, scalable authentication foundation that works with your existing subscriptions. # null Source: https://docs.vibekit.sh/auth/node # Node.js Usage For Node.js applications (CLI tools, servers, etc.), use the Node.js-specific import for full functionality including file system access and automatic browser launching. ## Basic Usage ```typescript theme={"dark"} import { ClaudeAuth } from '@vibe-kit/auth/node'; // Start OAuth flow (opens browser automatically) const token = await ClaudeAuth.authenticate(); // Check if authenticated const isAuthenticated = await ClaudeAuth.isAuthenticated(); // Get valid token (auto-refresh if needed) const accessToken = await ClaudeAuth.getValidToken(); // Verify authentication const isValid = await ClaudeAuth.verify(); // Get authentication status const status = await ClaudeAuth.getStatus(); // Logout await ClaudeAuth.logout(); ``` ## Token Import/Export Node.js environments support importing and exporting tokens in various formats: ```typescript theme={"dark"} import { ClaudeAuth } from '@vibe-kit/auth/node'; // Export token in different formats const envToken = await ClaudeAuth.exportToken('env'); const jsonToken = await ClaudeAuth.exportToken('json'); const fullToken = await ClaudeAuth.exportToken('full'); // Import from various sources await ClaudeAuth.importToken({ fromEnv: true }); await ClaudeAuth.importToken({ fromFile: './token.json' }); await ClaudeAuth.importToken({ refreshToken: 'your-refresh-token' }); ``` ## Using with AI Provider APIs ### Claude AI (Available Now) ```typescript theme={"dark"} import { ClaudeAuth } from '@vibe-kit/auth/node'; // Authenticate and get token let accessToken = await ClaudeAuth.getValidToken(); if (!accessToken) { await ClaudeAuth.authenticate(); accessToken = await ClaudeAuth.getValidToken(); } // Use with Claude Code CLI // First, export the token as an environment variable: // export CLAUDE_CODE_OAUTH_TOKEN=${accessToken} // claude -p 'Hello, Claude!' ``` ### With Official SDKs ```typescript theme={"dark"} // Claude AI with Anthropic SDK import Anthropic from '@anthropic-ai/sdk'; import { ClaudeAuth } from '@vibe-kit/auth/node'; const accessToken = await ClaudeAuth.getValidToken(); const anthropic = new Anthropic({ apiKey: '', // Leave empty for OAuth authToken: accessToken, // Use your MAX subscription token }); const message = await anthropic.messages.create({ model: 'claude-sonnet-4-20250514', max_tokens: 1000, messages: [{ role: 'user', content: 'Hello!' }] }); ``` ## Storage Options Node.js environments use **MemoryTokenStorage** by default, providing in-memory storage for server-side applications with secure file system token persistence. # null Source: https://docs.vibekit.sh/auth/overview Universal OAuth authentication library for AI providers' MAX subscriptions. Currently supports Claude AI with Gemini, Grok, and ChatGPT Max coming soon. ## Features * **MAX Subscription Access**: Leverage your existing AI provider MAX subscriptions programmatically * **Multiple Providers**: Claude AI (available), Gemini, Grok, ChatGPT Max (coming soon) * **Environment-Specific Builds**: Separate Node.js and browser-compatible builds * **OAuth 2.0 + PKCE**: Secure authentication with industry standards * **Token Management**: Automatic token refresh and secure storage * **Browser & Node.js**: Works in both web applications and server environments ## Why Use MAX Subscriptions? Instead of paying per API call, leverage the subscriptions you already have: * **Cost Effective**: Use your existing MAX subscriptions instead of pay-per-use APIs * **Higher Limits**: MAX subscriptions often have higher rate limits and priority access * **Latest Models**: Access to the newest and most capable models in each provider's lineup * **Consistent Experience**: Same interface across different AI providers ## Installation ```bash theme={"dark"} npm install @vibe-kit/auth ``` ## Environment Compatibility * **Node.js**: Use `@vibe-kit/auth/node` for full functionality including file system access and browser launching * **Browser**: Use `@vibe-kit/auth/browser` or default import for browser-safe functionality * **Universal**: The default import provides browser-safe functionality that works everywhere ## Security * Tokens are stored with restricted file permissions (CLI) * Automatic token refresh prevents expired token usage * PKCE (Proof Key for Code Exchange) for secure OAuth flows * State parameter validation prevents CSRF attacks # null Source: https://docs.vibekit.sh/auth/types # Types & API Reference ## Core Types ### OAuthToken The main token interface used throughout the authentication library: ```typescript theme={"dark"} interface OAuthToken { access_token: string; token_type: string; expires_in?: number; refresh_token?: string; scope?: string; created_at: number; } ``` ## Authentication Methods ### ClaudeAuth (Node.js) Static methods available when using `@vibe-kit/auth/node`: ```typescript theme={"dark"} class ClaudeAuth { // Start OAuth flow (opens browser automatically) static authenticate(): Promise; // Check if user is authenticated static isAuthenticated(): Promise; // Get valid token (auto-refresh if needed) static getValidToken(): Promise; // Verify current authentication static verify(): Promise; // Get authentication status static getStatus(): Promise; // Logout and clear tokens static logout(): Promise; // Export token in different formats static exportToken(format: 'env' | 'json' | 'full'): Promise; // Import token from various sources static importToken(options: { fromEnv?: boolean; fromFile?: string; refreshToken?: string; }): Promise; } ``` ### ClaudeWebAuth (Browser) Instance-based authentication for browser environments: ```typescript theme={"dark"} class ClaudeWebAuth { constructor(storage: TokenStorage); // Create authorization URL with PKCE static createAuthorizationUrl(): { url: string; state: string; codeVerifier: string; }; // Complete authentication with auth code authenticate( authCode: string, codeVerifier: string, state: string ): Promise; // Check if authenticated isAuthenticated(): Promise; // Get valid token (auto-refresh if needed) getValidToken(): Promise; } ``` ## Storage Interfaces ### TokenStorage Base interface for token storage implementations: ```typescript theme={"dark"} interface TokenStorage { store(token: OAuthToken): Promise; retrieve(): Promise; clear(): Promise; } ``` ### Available Implementations * **MemoryTokenStorage**: In-memory storage for server-side use * **LocalStorageTokenStorage**: Browser localStorage (client-side only) * **CookieTokenStorage**: Cookie-based storage for SSR applications ## Coming Soon Additional provider support with similar interfaces: * **Gemini Max**: Access Google's most advanced AI models * **Grok Max**: Leverage xAI's premium models * **ChatGPT Max**: Use OpenAI's latest models # Universal Agent Support Source: https://docs.vibekit.sh/cli/agent-support Works with Claude Code, Gemini, Codex, Cursor Agent, and OpenCode - providing consistent security and observability across all coding agents. VibeKit CLI provides universal support for popular coding agents, giving you consistent security, observability, and management features regardless of which AI coding assistant you use. ## Supported Agents ### Claude Code Anthropic's Claude Code CLI with enhanced security: ```bash theme={"dark"} # Run Claude Code through VibeKit vibekit claude "Help me refactor this React component" # With sandbox enabled vibekit claude --sandbox "Debug this API issue" # Pass arguments directly to Claude CLI vibekit claude --help ``` ### Gemini Google's Gemini with VibeKit protection: ```bash theme={"dark"} # Run Gemini with VibeKit features vibekit gemini "Generate a Python data analysis script" # With sandbox isolation vibekit gemini --sandbox-type docker "Write comprehensive tests" ``` ### Codex OpenAI's Codex with monitoring: ```bash theme={"dark"} # Run Codex through VibeKit vibekit codex "Convert this JavaScript to TypeScript" # All VibeKit features apply to Codex vibekit codex --sandbox "Generate production-ready code" ``` ### Grok [Grok](https://x.ai/grok) by xAI with VibeKit protection: ```bash theme={"dark"} # Run Grok with VibeKit features vibekit grok "Generate a Go microservice" # With sandbox isolation vibekit grok --sandbox-type docker "Write comprehensive tests for the new microservice" ``` ### Cursor Agent Cursor's AI agent with VibeKit wrapper: ```bash theme={"dark"} # Run Cursor Agent through VibeKit vibekit cursor-agent "Help me implement this feature" # With logging and proxy features vibekit cursor-agent --sandbox-type podman "Review this code" ``` ### OpenCode Open-source coding agent integration: ```bash theme={"dark"} # OpenCode with VibeKit features vibekit opencode "Help with Rust memory management" # Full VibeKit feature support vibekit opencode --sandbox "Optimize this algorithm" ``` ## Universal Features ### Consistent Security Every agent gets the same security protections: * **Proxy Server**: All agent traffic routed through redaction proxy * **Sandbox Support**: Optional Docker/Podman isolation for all agents * **Redaction**: Sensitive data removal across all agents * **Logging**: Structured logging for all agent interactions ### Common Options All agents support the same VibeKit options: ```bash theme={"dark"} # Sandbox options work with any agent vibekit [agent] --sandbox vibekit [agent] --sandbox-type docker # Global proxy configuration applies to all vibekit [agent] --proxy http://localhost:8080 ``` ### Unified Logging Same observability features for all agents: ```bash theme={"dark"} # View logs from any agent vibekit logs --agent claude vibekit logs --agent gemini vibekit logs --agent codex vibekit logs --agent grok # Analytics for specific agents vibekit analytics --agent cursor-agent ``` ### Cross-Agent Analytics Compare and analyze different agents: ```bash theme={"dark"} # View analytics across all agents vibekit analytics # Multi-agent breakdown shows performance comparison # Output includes per-agent session counts, success rates, etc. ``` ## Configuration ### Global Settings VibeKit settings apply to all agents: ```json theme={"dark"} { "sandbox": { "enabled": false, "type": "docker" }, "proxy": { "enabled": true, "redactionEnabled": true }, "analytics": { "enabled": true } } ``` ### Environment Variables ```bash theme={"dark"} # Agent-specific API keys (set by underlying CLIs) export ANTHROPIC_API_KEY="your-claude-key" export GEMINI_API_KEY="your-gemini-key" export OPENAI_API_KEY="your-openai-key" export GROK_API_KEY="your-grok-key" # VibeKit global settings export VIBEKIT_SANDBOX=true export VIBEKIT_DEBUG=true ``` ### Settings Management ```bash theme={"dark"} # Open settings interface (works for all agents) vibekit # Settings affect all agents uniformly ``` ## How Agent Wrapping Works ### Command Forwarding VibeKit acts as a wrapper around existing agent CLIs: * Forwards all unknown options to the underlying agent * Adds VibeKit-specific options (`--sandbox`, `--sandbox-type`) * Applies consistent logging, proxy, and analytics features ### Example Flow ```bash theme={"dark"} vibekit claude "help me code" --some-claude-option # 1. VibeKit processes its own options (--sandbox, etc.) # 2. Starts proxy server if needed # 3. Forwards "help me code" and "--some-claude-option" to claude CLI # 4. Logs the session and captures analytics ``` ### Agent Requirements VibeKit assumes the underlying agent CLIs are installed: * `claude` command for Claude Code CLI * `gemini` command for Gemini CLI * `codex` command for Codex CLI * `grok` command for Grok CLI * `cursor-agent` command for Cursor Agent * `opencode` command for OpenCode ## Current Implementation ### What's Implemented * **Command Wrapping**: All agents get proxy, logging, analytics * **Consistent Options**: Same sandbox and proxy options for all * **Unified Analytics**: Cross-agent session tracking and comparison * **Settings Integration**: Global settings affect all agents ### Agent Status All supported agents use the same architecture: * Proxy server for redaction (when enabled) * Structured logging to `~/.vibekit/logs/` * Analytics tracking in `~/.vibekit/analytics/` * Optional sandbox execution ## Best Practices ### Agent Selection Choose agents based on their strengths: * **Claude**: Complex reasoning, detailed analysis * **Gemini**: Multimodal capabilities, diverse tasks * **Codex**: Code completion and generation * **Grok**: Real-time information and context * **Cursor Agent**: IDE-integrated workflows * **OpenCode**: Open-source flexibility ### Consistent Workflow * Use same VibeKit options across agents for consistency * Monitor analytics to compare agent effectiveness * Apply same security settings (sandbox, redaction) to all agents * Regular log review for all agent activities ### Security * Enable redaction for all agents handling sensitive code * Use sandbox mode when working with untrusted operations * Monitor proxy logs for unexpected data patterns * Keep all agent CLIs updated for security Universal agent support provides a consistent security and observability layer across different AI coding assistants, letting you choose the best tool for each task while maintaining unified monitoring and protection. # Configuration Files Source: https://docs.vibekit.sh/cli/configuration-files Understanding and managing VibeKit CLI configuration files ## Overview VibeKit CLI stores configuration and data in the `~/.vibekit/` directory. These files control sandbox behavior, redaction settings, analytics, and logging preferences. ## File Locations ### User Configuration Directory All VibeKit CLI files are stored in `~/.vibekit/`: | File | Location | Purpose | | --------------- | -------------------------- | ------------------------------------- | | `settings.json` | `~/.vibekit/settings.json` | User preferences and feature toggles | | `logs/` | `~/.vibekit/logs/` | Agent interaction logs by date | | `analytics/` | `~/.vibekit/analytics/` | Usage statistics and performance data | ### Project Files | File | Location | Purpose | | ------ | ------------ | -------------------------------- | | `.env` | Project root | Environment variables (API keys) | ## Settings Configuration ### \~/.vibekit/settings.json Controls VibeKit CLI behavior and features: ```json theme={"dark"} { "sandbox": { "enabled": false }, "redaction": { "enabled": true }, "analytics": { "enabled": true }, "aliases": { "enabled": false } } ``` ### Settings Options #### Sandbox Settings | Option | Type | Default | Description | | ----------------- | --------- | ------- | -------------------------------- | | `sandbox.enabled` | `boolean` | `false` | Enable Docker sandbox by default | When enabled, agents run in Docker containers instead of directly on your system. #### Redaction Settings | Option | Type | Default | Description | | ------------------- | --------- | ------- | ------------------------------------------- | | `redaction.enabled` | `boolean` | `true` | Enable automatic PII redaction from outputs | The redaction system automatically removes sensitive information from agent outputs. #### Analytics Settings | Option | Type | Default | Description | | ------------------- | --------- | ------- | -------------------------------------- | | `analytics.enabled` | `boolean` | `true` | Track usage statistics and performance | Analytics track session duration, success rates, and error patterns. #### Aliases Settings | Option | Type | Default | Description | | ----------------- | --------- | ------- | ----------------------------- | | `aliases.enabled` | `boolean` | `false` | Enable global command aliases | When enabled, you can use `claude` instead of `vibekit claude`. ## Managing Settings ### Interactive Settings Use the interactive settings interface: ```bash theme={"dark"} vibekit ``` This provides a TUI for toggling options: * Navigate with arrow keys * Toggle with space bar * Save with enter ### Manual Editing Edit settings directly: ```bash theme={"dark"} # Open in editor vi ~/.vibekit/settings.json # Validate JSON cat ~/.vibekit/settings.json | jq '.' ``` ## Environment Variables ### API Keys Set API keys for your agents: ```bash theme={"dark"} # Claude Code CLI export ANTHROPIC_API_KEY="sk-ant-..." # Gemini CLI (when available) export GOOGLE_API_KEY="..." # Add to shell profile for persistence echo 'export ANTHROPIC_API_KEY="sk-ant-..."' >> ~/.zshrc source ~/.zshrc ``` ### Network Configuration Configure network settings: ```bash theme={"dark"} # Use external proxy if needed export HTTP_PROXY="http://proxy.example.com:8080" export HTTPS_PROXY="http://proxy.example.com:8080" # Enable debug logging export VIBEKIT_DEBUG="1" ``` ### Project-Level Environment Create `.env` file in your project: ```bash theme={"dark"} # .env ANTHROPIC_API_KEY=sk-ant-... GOOGLE_API_KEY=... # Custom environment variables for your project DATABASE_URL=postgresql://... API_BASE_URL=https://api.example.com ``` ## Data Storage ### Log Files Logs are organized by date in `~/.vibekit/logs/`: ``` ~/.vibekit/logs/ ├── 2024-01-15/ │ ├── claude-10-30-00.log │ ├── claude-14-45-12.log │ └── gemini-16-20-35.log ├── 2024-01-16/ │ └── claude-09-15-42.log ``` Each log file contains: * Agent commands and arguments * Execution output and errors * Performance timings * File changes made ### Analytics Data Analytics are stored in `~/.vibekit/analytics/`: ``` ~/.vibekit/analytics/ ├── sessions/ │ ├── claude-2024-01-15.json │ └── gemini-2024-01-15.json └── summary.json ``` Data includes: * Session duration and outcome * Commands executed * Files modified * Error messages and warnings ## Global Aliases ### Setting Up Aliases Enable global aliases to use `claude` directly: ```bash theme={"dark"} # Enable in settings vibekit # Toggle aliases to enabled # Install aliases to shell vibekit setup-aliases # Restart terminal or reload shell source ~/.zshrc ``` ### Using Aliases After setup, use commands directly: ```bash theme={"dark"} # Instead of: vibekit claude "Generate code" claude "Generate code" # Instead of: vibekit gemini "Ask question" gemini "Ask question" ``` ### Diagnosing Alias Issues Check alias setup: ```bash theme={"dark"} vibekit diagnose-aliases ``` This shows: * Settings status * VibeKit command availability * Shell alias functionality * Current active aliases ## Configuration Precedence Settings are applied in this order (later overrides earlier): 1. Built-in defaults 2. Settings file (`~/.vibekit/settings.json`) 3. Environment variables 4. Command line options Example: ```bash theme={"dark"} # Settings: sandbox.enabled = false # Environment: (none) # Command line wins: vibekit claude --sandbox docker "Generate code" ``` ## Backup and Restore ### Manual Backup Create backup of all VibeKit data: ```bash theme={"dark"} # Create timestamped backup BACKUP_DIR="$HOME/vibekit-backup-$(date +%Y%m%d-%H%M%S)" cp -r ~/.vibekit "$BACKUP_DIR" tar -czf "$BACKUP_DIR.tar.gz" -C "$HOME" "$(basename "$BACKUP_DIR")" rm -rf "$BACKUP_DIR" echo "Backup created: $BACKUP_DIR.tar.gz" ``` ### Restore Configuration ```bash theme={"dark"} # Restore from backup tar -xzf ~/vibekit-backup-20240115-103000.tar.gz -C ~/ mv ~/vibekit-backup-20240115-103000 ~/.vibekit ``` ## Maintenance ### Clean Data Remove old logs and analytics: ```bash theme={"dark"} # Clean all data vibekit clean # Clean specific data types vibekit clean --logs # Remove log files vibekit clean --analytics # Remove analytics data vibekit clean --docker # Remove Docker resources ``` ### Reset Configuration Reset settings to defaults: ```bash theme={"dark"} # Remove settings file (will recreate with defaults) rm ~/.vibekit/settings.json # Or reset all data (careful!) rm -rf ~/.vibekit ``` ## Troubleshooting ### Corrupted Settings Check settings file validity: ```bash theme={"dark"} # Validate JSON jq '.' ~/.vibekit/settings.json # Fix corrupted file echo '{}' > ~/.vibekit/settings.json ``` ### Permission Issues Fix file permissions: ```bash theme={"dark"} # Ensure proper ownership and permissions chmod 700 ~/.vibekit find ~/.vibekit -type f -exec chmod 600 {} \; # Check current permissions ls -la ~/.vibekit/ ``` ### Missing Dependencies Check for required tools: ```bash theme={"dark"} # Check for Claude Code CLI claude --version # Check for Docker (if using sandbox) docker --version # Diagnose common issues vibekit diagnose-aliases ``` ## Best Practices ### 1. Secure API Keys Never commit API keys to version control: ```bash theme={"dark"} # .gitignore .env *.log ``` Use environment variables or secure storage. ### 2. Regular Cleanup Set up automatic cleanup: ```bash theme={"dark"} # Add to crontab for weekly cleanup 0 0 * * 0 vibekit clean --logs ``` ### 3. Monitor Usage Use analytics to understand your usage patterns: ```bash theme={"dark"} # Weekly usage review vibekit analytics --days 7 --summary # Export for analysis vibekit analytics --export weekly-report.json --days 7 ``` ### 4. Safe Experimentation Enable Docker sandbox for unknown or experimental prompts: ```bash theme={"dark"} # Enable sandbox in settings for safety vibekit # Or use per-command vibekit claude --sandbox docker "Experimental code generation" ``` ## Related Topics * [Environment Variables](/cli/environment-variables) - Runtime configuration * [Installation](/cli/installation) - Initial setup * [Quick Reference](/cli/quick-reference) - Common commands # Environment Variables Source: https://docs.vibekit.sh/cli/environment-variables Complete reference for environment variables used by the VibeKit CLI ## Overview The VibeKit CLI uses environment variables for configuration, API keys, and integration settings. These can be set in your shell, `.env` files, or passed directly to commands. ## API Keys ### AI Agent Keys Configure API keys for different AI providers: | Variable | Description | Required For | | ------------------- | ---------------------------- | ------------------ | | `ANTHROPIC_API_KEY` | Anthropic API key for Claude | `--agent claude` | | `OPENAI_API_KEY` | OpenAI API key | `--agent codex` | | `GOOGLE_API_KEY` | Google API key | `--agent gemini` | | `GROQ_API_KEY` | Groq API key | `--agent opencode` | Example: ````bash theme={"dark"} export ANTHROPIC_API_KEY="sk-ant-api03-..." export OPENAI_API_KEY="sk-..." export GOOGLE_API_KEY="AIza..." export GROQ_API_KEY="gsk_..." ### Priority Order API keys are resolved in this order: 1. Command line `--api-key` option 2. Environment-specific API key variable 3. Environment variables passed via `--env` 4. `.env` file in current directory ## GitHub Integration ### Authentication | Variable | Description | Required For | |----------|-------------|--------------| | `GITHUB_TOKEN` | Personal access token | PR creation, Git operations | | `GITHUB_REPOSITORY` | Repository in `owner/repo` format | PR creation | Example: ```bash export GITHUB_TOKEN="ghp_xxxxxxxxxxxxxxxxxxxx" export GITHUB_REPOSITORY="myorg/myrepo" ### Token Permissions Required GitHub token scopes: - `repo` - Full repository access - `write:pull_requests` - Create PRs - `read:user` - Read user profile ## Provider Configuration ### Dagger (Local Provider) | Variable | Description | Default | |----------|-------------|---------| | `VIBEKIT_PREFER_REGISTRY_IMAGES` | Use Docker Hub images instead of local builds | `false` | | `DOCKER_USERNAME` | Docker Hub username for image uploads | None | Example: ```bash export VIBEKIT_PREFER_REGISTRY_IMAGES="true" export DOCKER_USERNAME="myusername" ### Northflank | Variable | Description | Default | |----------|-------------|---------| | `NORTHFLANK_PROJECT_ID` | Default project ID for Northflank | None | | `NORTHFLANK_API_TOKEN` | Northflank API token | None | ### Daytona | Variable | Description | Default | |----------|-------------|---------| | `DAYTONA_WORKSPACE_ID` | Default workspace ID | None | | `DAYTONA_API_TOKEN` | Daytona API token | None | ### E2B | Variable | Description | Default | |----------|-------------|---------| | `E2B_API_KEY` | E2B API key | None | | `E2B_TEAM_ID` | E2B team identifier | None | ## Default Settings ### Resource Allocation | Variable | Description | Default | |----------|-------------|---------| | `VIBEKIT_DEFAULT_CPU` | Default CPU cores for environments | 2 | | `VIBEKIT_DEFAULT_MEMORY` | Default memory in MB | 2048 | | `VIBEKIT_DEFAULT_DISK` | Default disk space in GB | 20 | Example: ```bash export VIBEKIT_DEFAULT_CPU="4" export VIBEKIT_DEFAULT_MEMORY="4096" export VIBEKIT_DEFAULT_DISK="50" ### Behavior Settings | Variable | Description | Default | |----------|-------------|---------| | `VIBEKIT_DEFAULT_AGENT` | Default AI agent type | None | | `VIBEKIT_DEFAULT_TIMEOUT` | Default command timeout in ms | 30000 | | `VIBEKIT_AUTO_CLEANUP` | Auto-delete stopped environments | `false` | ## Development Settings ### Debug Options | Variable | Description | Default | |----------|-------------|---------| | `VIBEKIT_DEBUG` | Enable debug logging | `false` | | `VIBEKIT_LOG_LEVEL` | Log level (error, warn, info, debug) | `info` | | `VIBEKIT_LOG_FILE` | Log output file | None (stdout) | Example: ```bash export VIBEKIT_DEBUG="true" export VIBEKIT_LOG_LEVEL="debug" export VIBEKIT_LOG_FILE="/tmp/vibekit.log" ## Using .env Files ### File Location The CLI automatically loads `.env` files from: 1. Current working directory 2. Project root (if in a git repository) 3. Home directory (`~/.env`) ### .env File Format ```bash # .env # AI API Keys ANTHROPIC_API_KEY=sk-ant-api03-... OPENAI_API_KEY=sk-... # GitHub Integration GITHUB_TOKEN=ghp_... GITHUB_REPOSITORY=owner/repo # Provider Settings DOCKER_USERNAME=myusername NORTHFLANK_PROJECT_ID=proj_123 # Defaults VIBEKIT_DEFAULT_AGENT=claude VIBEKIT_DEFAULT_MEMORY=4096 # Debug VIBEKIT_DEBUG=true ### Security Best Practices 1. **Never commit `.env` files** - Add to `.gitignore` 2. **Use `.env.example`** - Template without secrets 3. **Restrict permissions** - `chmod 600 .env` 4. **Rotate keys regularly** - Update API keys periodically ## Command-Specific Variables ### vibekit init Additional variables during initialization: ```bash # Skip interactive prompts export VIBEKIT_INIT_PROVIDERS="Dagger,E2B" export VIBEKIT_INIT_AGENTS="claude,codex" export VIBEKIT_INIT_CPU="4" export VIBEKIT_INIT_MEMORY="4096" ### vibekit local create Override defaults for environment creation: ```bash # Set working directory export VIBEKIT_WORKING_DIR="/app" # Set default environment variables export VIBEKIT_ENV_VARS="NODE_ENV=development,PORT=3000" ## Precedence Rules Environment variables are loaded in this order (later overrides earlier): 1. System environment variables 2. `~/.env` file 3. Project `.env` file 4. Current directory `.env` file 5. Command line options Example: ```bash # System env export ANTHROPIC_API_KEY="old-key" # .env file ANTHROPIC_API_KEY=new-key # Command line (highest priority) vibekit local create --api-key "newest-key" ## Validation ### Checking Variables View current settings: ```bash # All environment variables env | grep VIBEKIT # Specific variable echo $ANTHROPIC_API_KEY # In environment vibekit local exec -e my-env -c "env | grep API" ### Required Variables Commands will fail with clear messages if required variables are missing: ❌ No API key found for claude agent. Set ANTHROPIC_API_KEY environment variable or use --api-key ## Troubleshooting ### Variables Not Loading ```bash # Check if .env exists ls -la .env # Verify format cat .env # Test loading source .env echo $ANTHROPIC_API_KEY ### Permission Issues ```bash # Fix .env permissions chmod 600 .env # Check ownership ls -l .env ### Debugging Variable Loading ```bash # Enable debug mode export VIBEKIT_DEBUG=true # Run command to see variable loading vibekit local create --name test ## Best Practices ### 1. Use .env.example Create a template for team members: ```bash # .env.example ANTHROPIC_API_KEY=your-anthropic-key-here OPENAI_API_KEY=your-openai-key-here GITHUB_TOKEN=your-github-token-here GITHUB_REPOSITORY=owner/repo ### 2. Separate Environments Use different files for different environments: ```bash # .env.development VIBEKIT_DEFAULT_AGENT=codex VIBEKIT_DEBUG=true # .env.production VIBEKIT_DEFAULT_AGENT=claude VIBEKIT_DEBUG=false ### 3. Security Script Check for exposed secrets: ```bash #!/bin/bash # check-secrets.sh files=".env .env.* *.env" for file in $files; do if [ -f "$file" ]; then if grep -q "sk-\|ghp_\|gsk_" "$file"; then echo "WARNING: $file might contain secrets" ls -la "$file" fi fi done ## Related Topics - [Configuration Files](/cli/configuration-files) - Other configuration options - [Installation](/cli/installation) - Initial setup and configuration - [Quick Reference](/cli/quick-reference) - Common variable usage ```` # Introduction Source: https://docs.vibekit.sh/cli/index VibeKit is a safety layer for your coding agent. Run Claude Code, Gemini, Codex — or any coding agent — in a clean, isolated sandbox with sensitive data redaction and observability baked in. Dashboard ## Key Features Runs agent output in isolated Docker containers — zero risk to your local setup Auto-removes secrets, API keys, and other sensitive data from completions Complete visibility into agent operations with real-time logs, traces, and metrics Works with Claude Code, Gemini CLI, Grok CLI, Codex CLI, OpenCode, and more ## Getting Started Install the VibeKit CLI and get started in minutes Common commands and workflows for daily use ## Try It Out Get started with VibeKit CLI in seconds: ```bash theme={"dark"} # Install globally npm install -g vibekit # Run Claude Code with enhanced security vibekit claude ``` ## Why Use VibeKit CLI? Instead of running coding agents directly on your machine, VibeKit provides crucial safety and visibility: * **Zero Risk**: Isolated Docker containers prevent any damage to your local environment * **Security First**: Built-in redaction removes sensitive data from agent completions automatically * **Full Visibility**: Complete observability into what your coding agents are actually doing * **Works Offline**: No cloud dependencies or internet required — works entirely on your machine Whether you're using Claude Code for development, integrating AI agents into your workflow, or building applications that need secure code execution, VibeKit CLI provides the safety foundation you need to use coding agents with confidence. # Installation Source: https://docs.vibekit.sh/cli/installation How to install and set up the VibeKit CLI on your system ## Prerequisites Before installing the VibeKit CLI, ensure you have: * **Node.js** version 18.0.0 or higher * **npm** or **yarn** package manager * **Docker** installed and running (optional, for maximum security) * **Claude Code CLI** or **Gemini CLI** for the agents you want to use ## Installation Methods ### Global Installation (Recommended) Installing globally makes the `vibekit` command available system-wide: ```bash npm theme={"dark"} npm install -g vibekit ``` ```bash yarn theme={"dark"} yarn global add vibekit ``` ```bash pnpm theme={"dark"} pnpm add -g vibekit ``` ### Project Installation For project-specific installations: ```bash npm theme={"dark"} npm install --save-dev vibekit ``` ```bash yarn theme={"dark"} yarn add --dev vibekit ``` ```bash pnpm theme={"dark"} pnpm add -D vibekit ``` ### Using npx (No Installation) Run commands without installing: ```bash theme={"dark"} npx vibekit claude "Generate a REST API" npx vibekit dashboard ``` ## Verify Installation After installation, verify that the CLI is working: ```bash theme={"dark"} # Check version vibekit --version # View help vibekit --help ``` ## Post-Installation Setup ### 1. Install Required Agents Install the coding agents you want to use: ```bash theme={"dark"} # Install Claude Code CLI npm install -g @anthropic/claude-code # Install Gemini CLI (if available) # Follow Gemini CLI installation instructions ``` ### 2. Configure Environment Variables Set up your API keys: ```bash theme={"dark"} # For Claude export ANTHROPIC_API_KEY="sk-ant-..." # For Gemini export GOOGLE_API_KEY="..." # For proxy configuration (optional) export HTTP_PROXY="http://proxy.example.com:8080" ``` Or add them to your shell profile (`~/.bashrc`, `~/.zshrc`): ```bash theme={"dark"} echo 'export ANTHROPIC_API_KEY="sk-ant-..."' >> ~/.zshrc source ~/.zshrc ``` ### 3. Configure Settings (Optional) Run the settings interface to configure VibeKit: ```bash theme={"dark"} vibekit ``` This allows you to: * Enable/disable Docker sandbox * Configure proxy server settings * Enable/disable analytics * Set up global aliases ### 4. Docker Setup (Optional) For maximum security, ensure Docker is running: ```bash theme={"dark"} # Check Docker status docker info # Start Docker daemon if needed # On macOS: Open Docker Desktop # On Linux: sudo systemctl start docker ``` ## Troubleshooting Installation ### Command Not Found If `vibekit` command is not found after global installation: ```bash theme={"dark"} # Check npm global bin directory npm config get prefix # Add to PATH (example for macOS/Linux) export PATH="$(npm config get prefix)/bin:$PATH" # Make permanent by adding to ~/.bashrc or ~/.zshrc echo 'export PATH="$(npm config get prefix)/bin:$PATH"' >> ~/.bashrc ``` ```bash theme={"dark"} # Check yarn global bin directory yarn global bin # Add to PATH export PATH="$(yarn global bin):$PATH" ``` ### Permission Errors If you encounter permission errors during global installation: ```bash theme={"dark"} # Option 1: Use a Node version manager (recommended) # Install nvm: https://github.com/nvm-sh/nvm nvm install node npm install -g vibekit # Option 2: Change npm's default directory mkdir ~/.npm-global npm config set prefix '~/.npm-global' export PATH=~/.npm-global/bin:$PATH npm install -g vibekit ``` ### Docker Not Running (Optional) If you want to use Docker sandbox and see Docker-related errors: ```bash theme={"dark"} # Check if Docker is installed docker --version # Check if Docker daemon is running docker ps # Start Docker # macOS: Open Docker Desktop application # Linux: sudo systemctl start docker # Windows: Start Docker Desktop ``` ### Agent Not Found If you see "command not found" errors for Claude or Gemini: ```bash theme={"dark"} # For Claude Code CLI npm install -g @anthropic/claude-code # Verify installation claude --version # Set up global aliases (optional) vibekit setup-aliases ``` ## Platform-Specific Notes ### macOS * Docker Desktop is recommended * May need to grant terminal permissions for Docker * Homebrew users can install Node.js with `brew install node` ### Linux * Add your user to the docker group: `sudo usermod -aG docker $USER` * Log out and back in for group changes to take effect * Some distributions may require `sudo` for global npm installs ### Windows * Use WSL2 for best compatibility * Docker Desktop with WSL2 backend is recommended * Run commands in WSL2 terminal, not Command Prompt ## Updating the CLI To update to the latest version: ```bash npm theme={"dark"} npm update -g vibekit ``` ```bash yarn theme={"dark"} yarn global upgrade vibekit ``` ```bash npx theme={"dark"} # npx always uses the latest version npx vibekit@latest ``` ## Uninstalling To remove the CLI: ```bash npm theme={"dark"} npm uninstall -g vibekit ``` ```bash yarn theme={"dark"} yarn global remove vibekit ``` ## Next Steps After installation, you're ready to: 1. [Configure settings](/cli/configuration-files) with `vibekit` 2. [Run your first agent](/cli/quick-reference) with `vibekit claude "Hello world"` 3. [Set up monitoring](/cli/quick-reference) with `vibekit dashboard` For a quick overview of all commands, see the [Quick Reference](/cli/quick-reference). # Local Sandbox Source: https://docs.vibekit.sh/cli/local-sandbox Optional Docker container isolation for running AI coding agents with filesystem protection. VibeKit's local sandbox feature optionally runs coding agents inside Docker containers, providing isolation from your host system. The sandbox functionality is available but not enabled by default. ## How It Works When sandbox mode is enabled, VibeKit creates isolated Docker containers to run coding agents: * **Container Isolation**: Agent processes run inside Docker containers * **Filesystem Control**: Limited access to host filesystem through controlled mounts * **Runtime Support**: Works with Docker or Podman * **Optional Feature**: Sandbox can be enabled per-command or via settings ## Configuration ### Enable Sandbox Mode ```bash theme={"dark"} # Enable sandbox for a single command vibekit claude --sandbox "Help me debug this issue" # Specify sandbox type (docker or podman) vibekit claude --sandbox-type docker "Generate some code" # Use podman instead of docker vibekit claude --sandbox-type podman "Review this function" ``` ### Environment Variables ```bash theme={"dark"} # Enable sandbox globally export VIBEKIT_SANDBOX=true # Set default sandbox type export VIBEKIT_SANDBOX_TYPE=docker ``` ### Settings Configuration Configure sandbox in `~/.vibekit/settings.json`: ```json theme={"dark"} { "sandbox": { "enabled": false, "type": "docker" } } ``` ## Sandbox Management ### Check Sandbox Status ```bash theme={"dark"} # View current sandbox configuration vibekit sandbox status # Check with specific options vibekit sandbox status --sandbox --sandbox-type docker ``` ### Build Sandbox Image ```bash theme={"dark"} # Build the sandbox container image vibekit sandbox build ``` ### Clean Up Sandbox Resources ```bash theme={"dark"} # Remove sandbox images and containers vibekit sandbox clean ``` ## Current Implementation ### What's Available * **Docker/Podman Support**: Configurable container runtime * **Sandbox Detection**: Automatic detection of available runtimes * **Image Building**: Build custom sandbox images * **Status Reporting**: Check sandbox readiness and configuration * **Optional Operation**: Works with or without sandboxing ### Sandbox Engine Features The sandbox engine provides: * Runtime detection (Docker/Podman availability) * Container image management * Configuration resolution from CLI options and settings * Execution orchestration between sandboxed and direct execution ### Example Status Output ``` 📦 Sandbox Status ────────────────────────────────────────────────── Status: ENABLED Type: docker Source: CLI option Runtime: docker Available: YES Image: vibekit-sandbox:latest Image Exists: YES Ready: YES ``` ## Benefits ### Isolation * **Process Isolation**: Agent processes run in separate containers * **Filesystem Protection**: Host filesystem access is controlled * **Resource Containment**: Container resource limits prevent system impact ### Flexibility * **Optional Use**: Enable only when needed for sensitive operations * **Runtime Choice**: Support for both Docker and Podman * **Configuration Options**: CLI flags, environment variables, or settings file ### Development Safety * **Safe Experimentation**: Test potentially risky operations in isolation * **Clean Environment**: Fresh container state for reproducible results * **Host Protection**: Prevent accidental system modifications ## Best Practices ### When to Use Sandbox * Working with untrusted or experimental code * Testing potentially destructive operations * Ensuring reproducible development environments * Protecting sensitive host system configurations ### Setup Recommendations 1. **Install Docker/Podman**: Ensure container runtime is available 2. **Build Image**: Pre-build sandbox image for faster startup 3. **Test Configuration**: Verify sandbox status before important work 4. **Monitor Resources**: Check container resource usage during long sessions ### Security Considerations * Sandbox provides process isolation, not complete security * Container breakout vulnerabilities may still exist * Host filesystem mounts reduce isolation benefits * Keep container runtime updated for security patches The local sandbox feature provides an additional layer of protection when running AI coding agents, offering configurable isolation without requiring it for basic operations. # Observability Source: https://docs.vibekit.sh/cli/observability Complete visibility into agent operations with logs, analytics, and dashboard to understand what your coding agents are doing. Dashboard ## Dashboard ### Web Dashboard VibeKit includes a web dashboard for monitoring agent activity: ```bash theme={"dark"} # Start the dashboard (opens browser automatically) vibekit dashboard # Start on custom port vibekit dashboard --port 3001 # Start without opening browser vibekit dashboard --no-open # Stop dashboard vibekit dashboard stop ``` ### Dashboard Features The dashboard provides: * Agent session monitoring * Analytics visualization * Settings management * Real-time activity tracking ## Logging System ### View Logs Monitor agent activity through comprehensive logging: ```bash theme={"dark"} # View recent logs (default: 50 lines) vibekit logs # View logs for specific agent vibekit logs --agent claude # View more lines vibekit logs --lines 100 # Filter by specific agent vibekit logs --agent gemini ``` ### Log Storage Logs are stored in JSON format at `~/.vibekit/logs/`: * Daily log files per agent (e.g., `claude-2024-01-15.log`) * Structured JSON entries with timestamps, levels, and metadata * Session IDs for tracking individual agent runs ### Log Format Each log entry contains: ```json theme={"dark"} { "timestamp": "2024-01-15T10:30:00.000Z", "level": "INFO", "agent": "claude", "sessionId": "1705312200000", "message": "Agent session started", "metadata": {} } ``` ## Analytics ### Usage Statistics View detailed analytics about your agent usage: ```bash theme={"dark"} # View analytics summary (default: 7 days) vibekit analytics # View analytics for specific agent vibekit analytics --agent claude # View analytics for custom time period vibekit analytics --days 30 # Export analytics to JSON vibekit analytics --export analytics.json ``` ### Analytics Metrics The analytics system tracks: * **Total Sessions**: Number of agent sessions * **Session Duration**: Average and total session time * **Success Rate**: Percentage of successful completions * **Files Changed**: Number of files modified during sessions * **Error Count**: Total errors and warnings encountered * **Agent Breakdown**: Performance comparison across agents ### Example Analytics Output ``` 📊 Agent Analytics Summary ────────────────────────────────────────────────── Total Sessions: 45 Total Duration: 1,200s Average Duration: 27s Success Rate: 89.3% Files Changed: 127 Total Errors: 5 Total Warnings: 12 🤖 Agent Breakdown ────────────────────────────────────────────────── claude: Sessions: 32 Avg Duration: 31s Success Rate: 91.2% gemini: Sessions: 13 Avg Duration: 18s Success Rate: 84.6% ``` ## Data Management ### Clean Up Data Remove old logs and analytics: ```bash theme={"dark"} # Clean both logs and analytics vibekit clean # Clean only logs vibekit clean --logs # Clean only analytics data vibekit clean --analytics ``` ### Log Location * **Logs**: `~/.vibekit/logs/` * **Analytics**: `~/.vibekit/analytics/` * **Settings**: `~/.vibekit/settings.json` ## Current Capabilities ### What's Available * **Structured Logging**: JSON-formatted logs with timestamps and metadata * **Analytics Dashboard**: Web interface for viewing usage statistics * **CLI Analytics**: Command-line access to usage metrics * **Agent Tracking**: Per-agent performance monitoring * **Session Management**: Track individual agent sessions * **Data Export**: Export analytics to JSON format ### Dashboard Features * Real-time session monitoring * Settings management interface * Analytics visualization * Agent comparison views ## Proxy Server Observability ### Traffic Monitoring The proxy server provides additional observability: * HTTP/HTTPS request logging * Response time tracking * Redaction statistics * SSE (Server-Sent Events) stream monitoring ### Proxy Logs Proxy activity is captured but processed silently for privacy: * Request/response analysis * Traffic patterns * Redaction effectiveness * Performance metrics ## Best Practices ### Regular Monitoring 1. **Check Analytics Weekly**: Review agent usage patterns 2. **Monitor Success Rates**: Identify problematic sessions 3. **Clean Up Data**: Regularly remove old logs and analytics 4. **Use Dashboard**: Keep dashboard running for real-time monitoring ### Troubleshooting 1. **Check Recent Logs**: Look for error patterns in recent sessions 2. **Review Analytics**: Identify trends in failure rates 3. **Monitor Dashboard**: Watch for real-time issues 4. **Export Data**: Save important metrics before cleanup The observability features help you understand agent performance, track usage patterns, and identify issues through comprehensive logging and analytics. # Quick Reference Source: https://docs.vibekit.sh/cli/quick-reference Quick reference card for common VibeKit CLI commands ## Essential Commands ### Setup & Installation ```bash theme={"dark"} # Install VibeKit CLI globally npm install -g vibekit # Configure settings vibekit # Set up global aliases (optional) vibekit setup-aliases ``` ### Running Agents ```bash theme={"dark"} # Run Claude with default settings vibekit claude "Create a REST API" # Run Claude with Docker sandbox (maximum security) vibekit claude --sandbox docker "Add authentication" # Run Gemini with network access vibekit gemini --network "Create a web scraper" # Pass additional arguments to the underlying agent vibekit claude --help vibekit claude --model claude-3-5-sonnet-20241022 "Generate code" ``` ### Sandbox Options ```bash theme={"dark"} # No sandbox (default, fast startup) vibekit claude --sandbox none "Fix the bug" # Docker sandbox (complete isolation) vibekit claude --sandbox docker "Run untrusted code" # Docker with no network access (maximum security) vibekit claude --sandbox docker --no-network "Secure development" # Use fresh container instead of persistent one vibekit claude --sandbox docker --fresh-container "Clean environment" ``` ### Monitoring & Analytics ```bash theme={"dark"} # View recent logs vibekit logs # View logs for specific agent vibekit logs --agent claude --lines 100 # View analytics and statistics vibekit analytics --days 7 # View analytics for specific agent vibekit analytics --agent claude --summary # Export analytics to file vibekit analytics --export analytics.json ``` ### Dashboard & Web Interface ```bash theme={"dark"} # Start analytics dashboard and open in browser vibekit dashboard # Start dashboard on specific port vibekit dashboard start --port 3001 --open # Stop dashboard vibekit dashboard stop ``` ## Common Workflows ### Secure Development ```bash theme={"dark"} # 1. Enable Docker sandbox in settings vibekit # 2. Run agents in isolated containers vibekit claude --sandbox docker "Implement user authentication" # 3. Sync changes back to your project when ready vibekit sync # 4. Monitor activity in dashboard vibekit dashboard ``` ### Debugging & Analysis ```bash theme={"dark"} # 1. Run agent and capture all interactions vibekit claude --sandbox docker "Debug the payment system" # 2. Check logs for errors vibekit logs --agent claude --lines 50 # 3. View analytics to understand patterns vibekit analytics --agent claude --days 1 # 4. Check container status if needed vibekit docker --status ``` ### Team Collaboration ```bash theme={"dark"} # 1. Enable proxy for request logging vibekit proxy start # 2. Run agents through proxy vibekit claude --proxy http://localhost:8080 "Add new feature" # 3. Share analytics and logs with team vibekit analytics --export team-report.json # 4. Clean up when done vibekit clean ``` ### Proxy & Security ```bash theme={"dark"} # Start proxy server for request logging vibekit proxy start --port 8080 # Kill proxy server on specific port vibekit proxy kill --port 8080 # Run agent through custom proxy vibekit claude --proxy http://proxy.example.com:8080 "Generate code" ``` ### Docker Management ```bash theme={"dark"} # Check Docker container status vibekit docker --status # Stop persistent container vibekit docker --stop # Restart persistent container vibekit docker --restart # Sync changes from sandbox to project vibekit sync ``` ### Maintenance ```bash theme={"dark"} # Clean all data vibekit clean # Clean only logs vibekit clean --logs # Clean only Docker resources vibekit clean --docker # Clean only analytics vibekit clean --analytics ``` ## Environment Variables Quick Reference ```bash theme={"dark"} # In .env file or shell export ANTHROPIC_API_KEY="sk-ant-..." # For Claude export GOOGLE_API_KEY="..." # For Gemini export HTTP_PROXY="http://..." # Proxy for all requests export HTTPS_PROXY="http://..." # HTTPS proxy export VIBEKIT_DEBUG="1" # Enable debug logging ``` ## Keyboard Shortcuts When using interactive commands: * `↑/↓` - Navigate options * `Space` - Select/deselect option * `Enter` - Confirm selection * `Ctrl+C` - Cancel operation ## Common Flags | Flag | Description | Example | | ---------------------------- | --------------------------- | ------------------------------- | | `--sandbox ` | Sandbox type (none, docker) | `--sandbox docker` | | `--proxy ` | HTTP proxy URL | `--proxy http://localhost:8080` | | `--network` / `--no-network` | Network access control | `--no-network` | | `--fresh-container` | Use new Docker container | `--fresh-container` | | `-a, --agent ` | Filter by agent | `--agent claude` | | `-n, --lines ` | Number of lines | `--lines 100` | | `--json` | JSON output | `--json` | | `--export ` | Export to file | `--export report.json` | | `-p, --port ` | Port number | `--port 3001` | ## Exit Codes * `0` - Success * `1` - General error * `127` - Command not found * `130` - Interrupted (Ctrl+C) ## Getting Help ```bash theme={"dark"} # General help vibekit --help # Command-specific help vibekit claude --help vibekit analytics --help vibekit dashboard --help # Show version vibekit --version # Diagnose setup issues vibekit diagnose-aliases ``` # Built-in Redaction Source: https://docs.vibekit.sh/cli/redaction Automatically detect and remove sensitive data like API keys, secrets, and PII from AI agent completions through the proxy server. VibeKit's built-in redaction system automatically identifies and removes sensitive information from coding agent outputs by intercepting HTTP traffic through a proxy server that applies pattern-based filtering. ## How It Works VibeKit runs a proxy server that sits between coding agents and their API endpoints. All HTTP/HTTPS traffic flows through this proxy, where responses are processed in real-time to detect and redact sensitive data before it reaches you. ### Proxy-based Redaction ```bash theme={"dark"} # VibeKit automatically starts proxy server vibekit claude "Show me API integration code" # Traffic flows: Claude API → Proxy (redaction) → Your terminal # Sensitive data is replaced before you see it ``` ### Pattern Detection The redaction system uses comprehensive pattern matching from `rules-stable.yml` that includes hundreds of patterns for: * **AWS**: Access keys (AKIA...), ARNs, API Gateway URLs, RDS endpoints * **OpenAI**: API keys (sk-...), organization keys, project keys * **GitHub**: Personal access tokens, app tokens * **Google**: API keys, service account keys, OAuth tokens * **Database**: Connection strings, credentials * **Generic**: Email addresses, credit card numbers, phone numbers ## Configuration ### Settings Management Control redaction through the VibeKit settings: ```bash theme={"dark"} # Open settings interface vibekit # Toggle redaction on/off in the proxy section ``` ### Settings File Located at `~/.vibekit/settings.json`: ```json theme={"dark"} { "proxy": { "enabled": true, "redactionEnabled": true } } ``` ### How Patterns Work Patterns are loaded from `packages/cli/src/utils/rules-stable.yml`: ```yaml theme={"dark"} patterns: - pattern: name: OpenAI API Key regex: sk-[a-zA-Z0-9]{48} confidence: high - pattern: name: AWS Access Key ID Value regex: (A3T[A-Z0-9]|AKIA|AGPA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16} confidence: high ``` ## Real-time Processing ### Stream Processing Redaction happens as data flows through Transform streams: * HTTP responses are processed in chunks * Pattern matching occurs on buffered content * Sensitive data is replaced with `[PATTERN_NAME_REDACTED]` tokens * Modified responses are sent to your terminal ### Example Output ```bash theme={"dark"} # Original API response: # "Configure with API key sk-1234567890abcdef..." # What you see: # "Configure with API key [OPENAI_API_KEY_REDACTED]..." ``` ## Current Capabilities ### What's Implemented * **Proxy Server**: Intercepts HTTP/HTTPS traffic * **Pattern Matching**: 200+ predefined patterns for common secrets * **Real-time Processing**: Redacts responses as they stream * **Settings Integration**: Toggle redaction on/off * **Multiple Agents**: Works with Claude, Gemini, Codex, etc. ### Default Patterns Include * AWS access keys, secret keys, ARNs * OpenAI API keys and organization keys * GitHub personal access tokens * Google API keys and service accounts * Database connection strings * Email addresses and phone numbers * Credit card patterns ## Proxy Server Management ### Automatic Operation The proxy server starts automatically when needed: ```bash theme={"dark"} # Proxy starts automatically with redaction enabled vibekit claude "Generate secure API client" ``` ### Manual Control ```bash theme={"dark"} # Start proxy server manually vibekit proxy start --port 8080 # Stop proxy server vibekit proxy kill --port 8080 ``` ## Limitations & Current State ### What's Not Yet Implemented * Custom pattern definition through CLI * Redaction reporting and analytics * Retroactive log processing * Sensitivity level controls * Whitelist management ### Fallback Behavior If pattern loading fails, the system falls back to basic patterns: * Email addresses: `[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}` * Credit cards: `[0-9]{13,19}` ## Best Practices ### Security * Keep redaction enabled in settings * Regularly review proxy logs for sensitive data * Monitor pattern matching effectiveness * Update VibeKit for new pattern definitions ### Development * Test with dummy secrets to verify redaction works * Check settings periodically to ensure redaction is enabled * Be aware that redaction only works through the proxy server Built-in redaction provides an essential security layer by intercepting and filtering sensitive data from AI coding agent responses, helping prevent accidental exposure of secrets and credentials. # Ask Mode Source: https://docs.vibekit.sh/sdk/ask-mode Ask mode allows you to run RAG over codebase and disables changes to the file system. VibeKit ships with an `ask` mode that allows you to ask questions to the agent without changing any files in the file system. This is useful for quick questions and answers or building powerful RAG applications. ```typescript theme={"dark"} const result = await vibeKit.generateCode({ prompt: "Describe the codebase in detail", mode: "ask", }) console.log(result); ``` # GitHub Integration Source: https://docs.vibekit.sh/sdk/github-integration Clone repositories, create branches, open pull requests, and more. VibeKit integrates with GitHub to allow you to clone repositories, create branches, open pull requests, and more. This is particularly powerful for conversational UIs where users can iteratively request changes and see them reflected in real-time through GitHub. ## Setup First, configure your VibeKit instance with GitHub credentials using secrets: ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY!, templateId: "vibekit-claude", }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(e2bProvider) .withSecrets({ GH_TOKEN: process.env.GITHUB_TOKEN!, // GitHub Personal Access Token }); ``` Your GitHub token needs the following permissions: * `repo` (Full control of private repositories) * `workflow` (Update GitHub Action workflows) For public repositories, no token is required for cloning. ## Cloning Repositories The new `cloneRepository` method allows you to explicitly clone any GitHub repository: ```typescript theme={"dark"} // Clone a public repository (no token needed) await vibeKit.cloneRepository("octocat/Hello-World"); // Clone a private repository (requires GH_TOKEN in secrets) await vibeKit.cloneRepository("your-org/private-repo"); // Clone to a specific directory await vibeKit.cloneRepository("your-org/your-repo", "/custom/path"); // Clone to default working directory (if not specified, uses workingDirectory option) await vibeKit.cloneRepository("your-org/your-repo"); ``` ## Creating a PR ### The basic way After cloning a repository and generating code changes, you can create a pull request: ```typescript theme={"dark"} // Add event listeners vibeKit.on("update", (update) => { console.log("Update:", update); }); vibeKit.on("error", (error) => { console.error("Error:", error); }); // Clone the repository first await vibeKit.cloneRepository("your-org/your-repo"); // Generate initial code const response = await vibeKit.generateCode({ prompt: "Create a React component for user authentication with email and password fields", mode: "code", }); // Create pull request with the generated changes (requires repository parameter) const pullRequest = await vibeKit.createPullRequest("your-org/your-repo"); console.log("Pull Request created!"); console.log(`URL: ${pullRequest.html_url}`); console.log(`PR Number: ${pullRequest.number}`); console.log(`Branch: ${pullRequest.branchName}`); console.log(`Commit SHA: ${pullRequest.commitSha}`); ``` ## Iterative changes with pushToBranch For conversational UIs, users often want to make multiple iterations on the same feature. Use `pushToBranch` to continuously update the same branch without creating multiple pull requests: ```typescript theme={"dark"} const result = await vibeKit.generateCode({ prompt: "Add validation to the login form", mode: "code", branch: pullRequest.branchName, // or an existing branch }); await vibeKit.pushToBranch(); ``` ## Merging Pull Requests Once a pull request has been reviewed and approved, you can programmatically merge it using the `mergePullRequest` method: ```typescript theme={"dark"} // Create a VibeKit instance with GitHub token in secrets const vibekit = new VibeKit() .withSecrets({ GH_TOKEN: process.env.GITHUB_TOKEN, }); // Merge a pull request with default settings (regular merge) const mergeResult = await vibekit.mergePullRequest({ repository: "myorg/myrepo", // Repository is now a required parameter pullNumber: 42 }); console.log(`PR merged! Commit SHA: ${mergeResult.sha}`); // Or use squash merge with custom commit message const squashResult = await vibekit.mergePullRequest({ repository: "myorg/myrepo", pullNumber: 42, mergeMethod: "squash", commitTitle: "feat: Add user authentication", commitMessage: "Implemented complete authentication flow with validation" }); ``` ### Merge Methods * **`merge`** (default): Creates a merge commit with all commits from the feature branch * **`squash`**: Squashes all commits into a single commit before merging * **`rebase`**: Rebases the commits onto the base branch ## Migration from withGithub If you're migrating from the old `withGithub` API, here are the key changes: ### Before (deprecated) ```typescript theme={"dark"} const vibeKit = new VibeKit() .withAgent(agentConfig) .withSandbox(sandbox) .withGithub({ token: process.env.GITHUB_TOKEN, repository: "owner/repo" }); // Repository was cloned automatically when generateCode was called await vibeKit.generateCode({ prompt: "Fix bug" }); await vibeKit.createPullRequest(); ``` ### After (new API) ```typescript theme={"dark"} const vibeKit = new VibeKit() .withAgent(agentConfig) .withSandbox(sandbox) .withSecrets({ GH_TOKEN: process.env.GITHUB_TOKEN }); // Explicitly clone repository await vibeKit.cloneRepository("owner/repo"); // Generate code (no longer triggers cloning) await vibeKit.generateCode({ prompt: "Fix bug" }); // Create PR (now requires repository parameter) await vibeKit.createPullRequest("owner/repo"); ``` ## Benefits of the New API * **Explicit Control**: Repository cloning is now an explicit operation * **Public Repository Support**: Clone public repositories without authentication * **Flexible Repository Management**: Work with multiple repositories in the same session * **Cleaner Separation**: GitHub operations are clearly separated from code generation * **Better Error Handling**: More specific error messages for authentication issues This comprehensive GitHub integration allows you to build powerful conversational UIs where users can iteratively request code changes, see them applied in real-time, create pull requests, and merge them programmatically when they're satisfied with the results. # Introduction Source: https://docs.vibekit.sh/sdk/index The VibeKit SDK makes it easy to embed powerful AI coding agents into your web applications. With support for multiple AI providers and secure sandboxed execution, you can add intelligent code generation, editing, and execution capabilities to any application. ## Key Features Integrate Claude Code, Codex, Gemini, Grok, and OpenCode agents into your applications Secure, isolated environments for safe code execution and development SDK for embedding in apps, CLI for development, and API for custom workflows Deploy with E2B, Dagger, Daytona, Northflank, Cloudflare, Modal, or Fly.io ## Getting Started Install and configure the VibeKit SDK Example integrations and code samples ## Why Use the VibeKit SDK? Modern applications increasingly need AI-powered coding capabilities. The VibeKit SDK makes it simple to add these features without the complexity of managing sandboxed environments, AI model integrations, or security considerations. Whether you're building a code editor, documentation platform, educational tool, or any application that could benefit from intelligent code generation and execution, the VibeKit SDK provides a secure, scalable foundation that grows with your needs. # Quickstart Source: https://docs.vibekit.sh/sdk/quickstart Below is an example on how to get started with VibeKit Follow these steps to install and run Vibekit: ## Basic setup **Step 1**: Install VibeKit Typescript SDK: ```bash npm theme={"dark"} npm i @vibe-kit/sdk ``` ```bash yarn theme={"dark"} yarn add @vibe-kit/sdk ``` **Step 2**: Configure your VibeKit client: ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY!, templateId: "vibekit-claude", }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(e2bProvider); ``` **Step 3**: Add event listeners and execute commands: ```typescript theme={"dark"} // Add event listeners for command output vibeKit.on("stdout", (output) => { console.log("Output:", output); }); vibeKit.on("stderr", (error) => { console.error("Error:", error); }); // Execute a command (recommended approach) const claudeCommand = `echo "Create a simple web app that displays a list of users" | claude -p --output-format stream-json --verbose --allowedTools "Edit,Write,MultiEdit,Read,Bash" --model claude-sonnet-4-20250514`; const result = await vibeKit.executeCommand(claudeCommand); // Get host URL (optional) const host = await vibeKit.getHost(3000); // Clean up when done await vibeKit.kill(); console.log("Result:", result); console.log("Host:", host); ``` **💡 Tip**: You can also use the deprecated `generateCode` method, but we recommend migrating to `executeCommand` for better control and flexibility. See the [migration guide](/api-reference/generate-code#migration-to-executecommand) for details. # Secrets Management Source: https://docs.vibekit.sh/sdk/secrets Learn how to configure secrets and environment variables in VibeKit VibeKit allows you to securely pass environment variables to your sandbox environment through the `secrets` configuration. This guide explains how to configure and manage these secrets. ## Configuration Overview Secrets in VibeKit are environment variables that get passed to the sandbox where your code executes. They are configured through the optional `secrets` object when initializing the VibeKit class. ```typescript theme={"dark"} export type SecretsConfig = { /** Environment variables to be passed to the sandbox */ [key: string]: string; }; ``` ## Basic Usage ### Using withSecrets ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(e2bProvider) .withSecrets({ DATABASE_URL: process.env.DATABASE_URL!, REDIS_URL: process.env.REDIS_URL!, STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY!, API_BASE_URL: process.env.API_BASE_URL!, }); ``` ### Adding Secrets to Your Configuration ```typescript theme={"dark"} import { VibeKit, VibeKitConfig } from "@vibe-kit/sdk"; const config: VibeKitConfig = { agent: { type: "codex", model: { apiKey: process.env.OPENAI_API_KEY!, }, }, environment: { e2b: { apiKey: process.env.E2B_API_KEY!, }, }, secrets: { // These environment variables will be available in your sandbox DATABASE_URL: process.env.DATABASE_URL!, REDIS_URL: process.env.REDIS_URL!, STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY!, API_BASE_URL: process.env.API_BASE_URL!, }, }; const vibeKit = new VibeKit(config); ``` ### Accessing Secrets in Generated Code Once configured, these secrets are available as environment variables in your sandbox: ```typescript theme={"dark"} // In your generated code running in the sandbox const databaseUrl = process.env.DATABASE_URL; const stripeKey = process.env.STRIPE_SECRET_KEY; // Use them in your application const db = new Database(databaseUrl); const stripe = new Stripe(stripeKey); ``` ## Common Use Cases ### Database Connections ```typescript theme={"dark"} const config: VibeKitConfig = { // ... other configuration secrets: { DATABASE_URL: process.env.DATABASE_URL!, DB_USER: process.env.DB_USER!, DB_PASSWORD: process.env.DB_PASSWORD!, DB_HOST: process.env.DB_HOST!, DB_PORT: process.env.DB_PORT!, }, }; ``` ### API Keys and External Services ```typescript theme={"dark"} const config: VibeKitConfig = { // ... other configuration secrets: { STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY!, SENDGRID_API_KEY: process.env.SENDGRID_API_KEY!, AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID!, AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY!, TWILIO_ACCOUNT_SID: process.env.TWILIO_ACCOUNT_SID!, TWILIO_AUTH_TOKEN: process.env.TWILIO_AUTH_TOKEN!, }, }; ``` ### Application Configuration ```typescript theme={"dark"} const config: VibeKitConfig = { // ... other configuration secrets: { NODE_ENV: process.env.NODE_ENV || "development", PORT: process.env.PORT || "3000", JWT_SECRET: process.env.JWT_SECRET!, CORS_ORIGIN: process.env.CORS_ORIGIN!, APP_URL: process.env.APP_URL!, }, }; ``` ## Environment Variables Setup Create a `.env` file in your project root to store your secrets: ```bash theme={"dark"} # .env # VibeKit Configuration OPENAI_API_KEY=sk-proj-your-openai-key E2B_API_KEY=e2b_your-e2b-key # Application Secrets (passed to sandbox) DATABASE_URL=postgresql://user:password@localhost:5432/mydb REDIS_URL=redis://localhost:6379 STRIPE_SECRET_KEY=sk_test_your-stripe-key SENDGRID_API_KEY=SG.your-sendgrid-key JWT_SECRET=your-jwt-secret-key APP_URL=http://localhost:3000 ``` ## Security Best Practices Never commit secrets or API keys to version control. Always use environment variables and ensure your `.env` file is in your `.gitignore`. ### 1. Use Environment Variables Always use `process.env` to access secrets: ```typescript theme={"dark"} // ✅ Good secrets: { API_KEY: process.env.API_KEY!, } // ❌ Bad - Never hardcode secrets secrets: { API_KEY: "secret-123-abc", } ``` ### 2. Add .env to .gitignore Ensure your `.env` file is not committed to version control: ```bash theme={"dark"} # .gitignore .env .env.local .env.*.local ``` ### 3. Validate Required Secrets Validate that all required secrets are present before initializing VibeKit: ```typescript theme={"dark"} const requiredSecrets = [ 'DATABASE_URL', 'STRIPE_SECRET_KEY', 'JWT_SECRET' ]; requiredSecrets.forEach((secret) => { if (!process.env[secret]) { throw new Error(`Missing required environment variable: ${secret}`); } }); const config: VibeKitConfig = { // ... other configuration secrets: { DATABASE_URL: process.env.DATABASE_URL!, STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY!, JWT_SECRET: process.env.JWT_SECRET!, }, }; ``` ### 4. Use Different Environments Use different environment files for different stages: ```.env.development Development theme={"dark"} DATABASE_URL=postgresql://localhost:5432/myapp_dev STRIPE_SECRET_KEY=sk_test_dev_key APP_URL=http://localhost:3000 ``` ```.env.staging Staging theme={"dark"} DATABASE_URL=postgresql://staging-db:5432/myapp_staging STRIPE_SECRET_KEY=sk_test_staging_key APP_URL=https://staging.myapp.com ``` ```.env.production Production theme={"dark"} DATABASE_URL=postgresql://prod-db:5432/myapp_prod STRIPE_SECRET_KEY=sk_live_prod_key APP_URL=https://myapp.com ``` ## Complete Example Here's a complete example showing how to set up secrets for a full-stack application: ```typescript theme={"dark"} import { VibeKit, VibeKitConfig } from "@vibe-kit/sdk"; // Validate required environment variables const requiredEnvVars = [ 'OPENAI_API_KEY', 'E2B_API_KEY', 'DATABASE_URL', 'JWT_SECRET' ]; requiredEnvVars.forEach((envVar) => { if (!process.env[envVar]) { throw new Error(`Missing required environment variable: ${envVar}`); } }); const config: VibeKitConfig = { agent: { type: "codex", model: { apiKey: process.env.OPENAI_API_KEY!, }, }, environment: { e2b: { apiKey: process.env.E2B_API_KEY!, }, }, github: { token: process.env.GITHUB_TOKEN!, repository: "your-org/your-repo", }, secrets: { // Database DATABASE_URL: process.env.DATABASE_URL!, // Authentication JWT_SECRET: process.env.JWT_SECRET!, // External APIs STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY!, SENDGRID_API_KEY: process.env.SENDGRID_API_KEY!, // Application Config NODE_ENV: process.env.NODE_ENV || "development", PORT: process.env.PORT || "3000", CORS_ORIGIN: process.env.CORS_ORIGIN || "http://localhost:3000", // Custom secrets CUSTOM_API_ENDPOINT: process.env.CUSTOM_API_ENDPOINT!, WEBHOOK_SECRET: process.env.WEBHOOK_SECRET!, }, }; const vibeKit = new VibeKit(config); ``` ## Troubleshooting ### Common Issues 1. **Missing Environment Variable**: Make sure all required secrets are set in your environment 2. **Secrets Not Available in Sandbox**: Ensure secrets are properly configured in the `secrets` object 3. **Type Errors**: Use the non-null assertion operator `!` or provide default values for optional secrets ### Testing Your Configuration You can test your configuration by initializing VibeKit: ```typescript theme={"dark"} try { const vibeKit = new VibeKit(config); console.log("✅ VibeKit initialized successfully"); console.log("🔐 Secrets configured:", Object.keys(config.secrets || {})); } catch (error) { console.error("❌ Configuration error:", error.message); } ``` # Session Management Source: https://docs.vibekit.sh/sdk/session-management Learn how to manage sessions in VibeKit for multi-turn conversations ## Sessions Sessions are a way to group together multiple requests to the agent. This is useful for multi-turn conversations and changes. **Using withSession** ```typescript theme={"dark"} const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(e2bProvider) .withSession("session-id-123"); ``` **Set session id** ```typescript theme={"dark"} const session = await vibeKit.setSession("abcd***") ``` **Get session id** ```typescript theme={"dark"} const session = await vibeKit.getSession() ``` # Streaming Source: https://docs.vibekit.sh/sdk/streaming VibeKit supports streaming responses, allowing you to receive data from the API in real-time as it is generated. VibeKit supports streaming responses, allowing you to receive data from the API in real-time as it is generated. This is particularly useful for applications that require immediate feedback or want to display results incrementally. ## Overview Streaming enables your application to process and display data as soon as it is available, rather than waiting for the entire response. This can improve user experience and reduce perceived latency. ## How to Use Streaming To enable streaming with commands, use the event-driven approach with `.on()` listeners for `stdout` and `stderr` events. The API will emit events as data is generated. **💡 Recommended**: Use `executeCommand` with `stdout`/`stderr` events for the best streaming experience. The deprecated `generateCode` method also supports streaming but will be removed in a future version. ### Example Usage with executeCommand (Recommended) ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY!, templateId: "vibekit-claude", }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(e2bProvider); // Set up event listeners for streaming vibeKit.on("stdout", (output) => { // Handle streaming output from commands console.log('Streaming output:', output); // Update your UI with the new content updateUI(output); }); vibeKit.on("stderr", (error) => { // Handle streaming errors console.error('Streaming error:', error); }); // Execute a command const claudeCommand = `echo "Create a React component for a todo list" | claude -p --output-format stream-json --verbose --allowedTools "Edit,Write,MultiEdit,Read,Bash" --model claude-sonnet-4-20250514`; const response = await vibeKit.executeCommand(claudeCommand); // The final response is still available console.log('Final response:', response); ``` ### Legacy Streaming with generateCode (Deprecated) ```typescript theme={"dark"} // Set up event listeners for streaming (deprecated approach) vibeKit.on("update", (message) => { // Handle streaming updates console.log('Streaming update:', message); // Update your UI with the new content updateUI(message); }); vibeKit.on("error", (error) => { // Handle streaming errors console.error('Streaming error:', error); }); // Generate code (deprecated) const response = await vibeKit.generateCode({ prompt: "Create a React component for a todo list", mode: "code", }); // The final response is still available console.log('Final response:', response); ``` ### With Branch Support ```typescript theme={"dark"} // Event listeners are already set up from previous example vibeKit.on("stdout", (output) => { // Display incremental updates to the user appendToOutput(output); }); // Execute command on a specific branch const claudeCommand = `echo "Add error handling to the React component" | claude -p --output-format stream-json --verbose --allowedTools "Edit,Write,MultiEdit,Read,Bash" --model claude-sonnet-4-20250514`; const response = await vibeKit.executeCommand(claudeCommand, { branch: "feature-error-handling" }); ``` ### Legacy: With Conversation History (Deprecated) ```typescript theme={"dark"} // Event listeners are already set up from previous example vibeKit.on("update", (message) => { // Display incremental updates to the user appendToOutput(message); }); const response = await vibeKit.generateCode({ prompt: "Now add error handling to the component", mode: "code", history: previousConversation, }); ``` ## When to Use Streaming * When you want to display results to users as soon as they are available * For long-running code generation tasks where incremental updates improve UX * For interactive coding sessions where immediate feedback is valuable * For chatbots or Q\&A mode where responses can be shown progressively ## Streaming Events VibeKit uses an event-driven approach for streaming with the following events: | Event | Type | Description | | -------- | --------------------------- | ------------------------------------------------------------ | | `update` | `(message: string) => void` | Emitted with streaming content updates as they are generated | | `error` | `(error: string) => void` | Emitted when errors occur during streaming | ## Notes * Streaming is available for both "ask" and "code" modes * The final response is still returned as a Promise, even when using streaming events * Event listeners are optional - you can use the method without them for non-streaming behavior * Handle errors appropriately in your `error` event listener to provide good user experience For more details, refer to the [Generate Code API Reference](/api-reference/generate-code) or contact support. # Git Worktrees Source: https://docs.vibekit.sh/sdk/worktrees Use isolated workspace environments for different branches with automatic worktree management Git worktrees provide isolated workspace environments for different branches, allowing you to work on multiple features simultaneously without switching between branches. When enabled, VibeKit automatically creates separate worktrees for each branch operation. ## Configuration Enable worktrees in your VibeKit setup: ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY!, templateId: "vibekit-claude", }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(e2bProvider) .withWorktrees({ root: "/tmp/my-worktrees", // optional: custom root directory for worktrees cleanup: true // optional: auto-cleanup after operations (default: true) }); ``` ## How It Works When worktrees are enabled: 1. **Branch Creation**: Each new branch gets its own isolated directory 2. **Automatic Setup**: VibeKit automatically creates worktrees based on branch names 3. **Isolation**: Changes in one worktree don't affect others 4. **Cleanup**: Worktrees are automatically removed after operations (unless `cleanup: false`) ## Usage Examples ### Generate Code in Feature Branch ```typescript theme={"dark"} // Generate code in a feature branch (creates worktree automatically) const result = await vibeKit.generateCode({ prompt: "Add user authentication", mode: "code", branch: "feature/auth" // Creates worktree at {root}/feature-auth }); ``` ### Execute Commands in Worktree ```typescript theme={"dark"} // Execute commands in branch-specific worktree const testResult = await vibeKit.executeCommand("npm test", { branch: "feature/auth" // Runs tests in the worktree for this branch }); ``` ### Create Pull Request from Worktree ```typescript theme={"dark"} // Create pull request from worktree const pr = await vibeKit.createPullRequest(); ``` ## Benefits Work on multiple features without branch switching Each branch has its own workspace and dependencies No manual worktree commands needed Changes are isolated until merged ## Configuration Options | Option | Type | Default | Description | | --------- | --------- | ----------------- | -------------------------------------- | | `root` | `string` | `{workingDir}-wt` | Base directory for worktrees | | `cleanup` | `boolean` | `true` | Auto-remove worktrees after operations | ## Advanced Usage ### Custom Worktree Root ```typescript theme={"dark"} .withWorktrees({ root: "/custom/path/worktrees", // All worktrees created under this path cleanup: true }) ``` ### Disable Cleanup ```typescript theme={"dark"} .withWorktrees({ cleanup: false // Keep worktrees after operations for debugging }) ``` ### Multiple Branches Example ```typescript theme={"dark"} // Work on multiple features simultaneously const authResult = await vibeKit.generateCode({ prompt: "Implement OAuth login", mode: "code", branch: "feature/oauth" }); const dashboardResult = await vibeKit.generateCode({ prompt: "Create admin dashboard", mode: "code", branch: "feature/dashboard" }); // Each feature gets its own isolated worktree ``` Worktrees are particularly useful in CI/CD environments and when working with large codebases where branch switching is expensive. Ensure your git repository has a clean state before enabling worktrees. Uncommitted changes may cause issues during worktree creation. # Beam Source: https://docs.vibekit.sh/supported-sandboxes/beam Configure VibeKit with Beam sandboxes for scalable cloud execution Beam is a serverless platform for deploying and running containerized applications in secure cloud sandboxes. Built for AI agents and compute-intensive workloads, Beam provides on-demand scalability with automatic resource management. Learn more at [beam.cloud](https://beam.cloud). ## Installation First, install the Beam provider package: ```bash theme={"dark"} npm install @vibe-kit/beam ``` ## Prerequisites Before using the Beam provider, you need to: 1. Sign up for a Beam account at [https://beam.cloud](https://beam.cloud) 2. Get your Beam Token and Workspace ID from the [dashboard](https://platform.beam.cloud/settings/api-keys) 3. Set them as environment variables: ```bash theme={"dark"} export BEAM_TOKEN=YOUR_BEAM_TOKEN export BEAM_WORKSPACE_ID=YOUR_WORKSPACE_ID ``` ## Configuration VibeKit uses a builder pattern with method chaining for type safety and flexibility. Configure your Beam provider and VibeKit instance: ### Using the provider directly ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createBeamProvider } from "@vibe-kit/beam"; // Create the Beam provider with configuration const beamProvider = createBeamProvider({ token: process.env.BEAM_TOKEN!, workspaceId: process.env.BEAM_WORKSPACE_ID!, cpu: 2, // optional, defaults to 2 memory: "1Gi", // optional, defaults to "1Gi" keepWarmSeconds: 300, // optional, defaults to 300 (5 minutes) }); // Create the VibeKit instance with the provider const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(beamProvider) .withWorkingDirectory("/workspace") // Optional: specify working directory .withSecrets({ // Any environment variables for the sandbox NODE_ENV: "production", }); // Generate code const result = await vibeKit.generateCode({ prompt: "Create a REST API with Express.js", mode: "ask" }); // Execute commands in the sandbox const response = await vibeKit.executeCommand("npm install && npm test"); console.log(response); // Start a development server await vibeKit.executeCommand("npm run dev", { background: true }); // Get the public URL for the service const url = await vibeKit.getHost(3000); console.log(`Service available at: ${url}`); // Clean up await vibeKit.kill(); ``` ### Using configuration object ```typescript theme={"dark"} import { VibeKit, VibeConfig } from "@vibe-kit/sdk"; const config: VibeConfig = { ..., environment: { beam: { // Required Beam authentication token: process.env.BEAM_TOKEN!, workspaceId: process.env.BEAM_WORKSPACE_ID!, // Optional resource configuration cpu: 4, memory: "2Gi", keepWarmSeconds: 600, // Optional custom Docker image image: "my-custom-image:latest" }, }, }; ``` ## Configuration Options The `createBeamProvider` function accepts these configuration options: ### Required Options * **`token`** (string): Your Beam authentication token from the dashboard * **`workspaceId`** (string): Your Beam workspace ID ### Optional Options * **`image`** (string): Custom Docker image. If not provided, it will be auto-selected based on the agent type: * `claude` → `superagentai/vibekit-claude:1.0` * `codex` → `superagentai/vibekit-codex:1.0` * `opencode` → `superagentai/vibekit-opencode:1.0` * `gemini` → `superagentai/vibekit-gemini:1.1` * `grok` → `superagentai/vibekit-grok-cli:1.0` * Default: `ubuntu:22.04` * **`cpu`** (number): Number of CPU cores to allocate (default: 2) * **`memory`** (number | string): Memory allocation, e.g., 1024 or "1Gi" (default: "1Gi") * **`keepWarmSeconds`** (number): How long to keep the sandbox warm after inactivity (default: 300 seconds / 5 minutes) ## ENV variables and secrets Configure your Beam provider using environment variables: ```bash theme={"dark"} # Required Beam credentials BEAM_TOKEN=your_beam_token_here BEAM_WORKSPACE_ID=your_workspace_id_here # Agent API keys ANTHROPIC_API_KEY=your_anthropic_key OPENAI_API_KEY=your_openai_key GOOGLE_API_KEY=your_google_key GEMINI_API_KEY=your_gemini_key GROK_API_KEY=your_grok_key # Optional GitHub integration GITHUB_TOKEN=your_github_token_here ``` Reference them in your code: ```typescript theme={"dark"} const beamProvider = createBeamProvider({ token: process.env.BEAM_TOKEN!, workspaceId: process.env.BEAM_WORKSPACE_ID!, // All other config is optional }); // GitHub configuration at SDK level const vibeKit = new VibeKit() .withSandbox(beamProvider) .withGithub({ token: process.env.GITHUB_TOKEN, repository: "owner/repo-name", }); ``` ## Unique Features ### Automatic Image Selection Beam automatically selects the appropriate pre-built Docker image based on your agent type, ensuring optimal compatibility and performance without manual configuration. ### Serverless Scalability * **On-demand resources** - Sandboxes spin up automatically when needed * **Automatic scaling** - Resources scale based on workload * **Pay-per-use** - Only pay for actual compute time used * **No infrastructure management** - Beam handles all server provisioning and maintenance ### Performance Optimization * **Fast cold starts** - Optimized container initialization * **Keep-warm configuration** - Keep sandboxes warm between requests for faster response times * **Configurable resources** - Adjust CPU and memory per workload * **Port exposure** - Dynamically expose ports for web services ## Advanced Usage ### Custom Docker Image Use your own Docker image with pre-installed dependencies: ```typescript theme={"dark"} const beamProvider = createBeamProvider({ token: process.env.BEAM_TOKEN!, workspaceId: process.env.BEAM_WORKSPACE_ID!, image: "my-registry/my-custom-image:latest", }); ``` ### High-Performance Configuration For compute-intensive workloads: ```typescript theme={"dark"} const beamProvider = createBeamProvider({ token: process.env.BEAM_TOKEN!, workspaceId: process.env.BEAM_WORKSPACE_ID!, cpu: 8, memory: "16Gi", keepWarmSeconds: 600, // 10 minutes }); ``` ### Background Command Execution Run long-running processes in the background: ```typescript theme={"dark"} // Start a background process await vibeKit.executeCommand("npm run dev", { background: true }); // The command runs independently // You can continue with other operations // Get the host URL to access the running service const url = await vibeKit.getHost(3000); console.log(`Dev server running at: ${url}`); ``` ### Exposing Multiple Ports Expose multiple services running on different ports: ```typescript theme={"dark"} // Start services on different ports await vibeKit.executeCommand("npm run api", { background: true }); await vibeKit.executeCommand("npm run frontend", { background: true }); // Get URLs for each service const apiUrl = await vibeKit.getHost(8000); const frontendUrl = await vibeKit.getHost(3000); console.log(`API: ${apiUrl}`); console.log(`Frontend: ${frontendUrl}`); ``` ## System Requirements * **Node.js 18+** - Runtime environment * **Beam account** - Active account with API credentials * **Internet connection** - Required for cloud sandbox execution ## Limitations * **Pause/Resume**: Beam doesn't directly support pause/resume operations. The sandbox remains active until terminated. Use `keepWarmSeconds` to manage idle timeouts and optimize costs. * **Beta SDK**: The Beam TypeScript SDK is currently in beta. Some features may change in future releases. * **Cold start time**: Initial sandbox creation may take a few seconds. Use `keepWarmSeconds` to maintain warm sandboxes for faster subsequent executions. ## Troubleshooting **Authentication errors:** ```bash theme={"dark"} # Verify your credentials are set correctly echo $BEAM_TOKEN echo $BEAM_WORKSPACE_ID # Re-export if needed export BEAM_TOKEN=your_token_here export BEAM_WORKSPACE_ID=your_workspace_id_here ``` **Sandbox creation timeout:** ```typescript theme={"dark"} // Increase CPU/memory for faster initialization const beamProvider = createBeamProvider({ token: process.env.BEAM_TOKEN!, workspaceId: process.env.BEAM_WORKSPACE_ID!, cpu: 4, memory: "2Gi", }); ``` **Port exposure issues:** ```typescript theme={"dark"} // Ensure the service is running before calling getHost await vibeKit.executeCommand("npm start", { background: true }); // Wait a moment for the service to start await new Promise(resolve => setTimeout(resolve, 2000)); // Then get the host URL const url = await vibeKit.getHost(3000); ``` **Image pull errors:** ```typescript theme={"dark"} // Specify a custom image if default images aren't accessible const beamProvider = createBeamProvider({ token: process.env.BEAM_TOKEN!, workspaceId: process.env.BEAM_WORKSPACE_ID!, image: "ubuntu:22.04", // Use a reliable base image }); ``` ## Cost Optimization Tips 1. **Use keep-warm wisely**: Set `keepWarmSeconds` based on your usage pattern * High frequency: 600+ seconds (10+ minutes) * Low frequency: 300 seconds (5 minutes) or less 2. **Right-size resources**: Start with minimal resources and scale up as needed ```typescript theme={"dark"} // Start small cpu: 2, memory: "1Gi", ``` 3. **Clean up promptly**: Always call `kill()` when done to avoid unnecessary charges ```typescript theme={"dark"} try { // Your code here } finally { await vibeKit.kill(); } ``` ## Support For issues related to: * **Beam SDK**: Visit [Beam Documentation](https://docs.beam.cloud) * **VibeKit Integration**: Open an issue on [GitHub](https://github.com/superagent-ai/vibekit/issues) * **Community Support**: Join our [Discord](https://discord.gg/spZ7MnqFT4) ## Next Steps * Explore [GitHub integration](../sdk/github-integration) for automated PR workflows * Learn about [streaming](../sdk/streaming) for real-time command output * Check out [session management](../sdk/session-management) for persistent workflows # Blaxel Source: https://docs.vibekit.sh/supported-sandboxes/blaxel Configure VibeKit with Blaxel sandboxes for lightning-fast cloud execution Blaxel is a cloud-based container platform optimized for AI agents and development workflows. With sub-25ms cold starts from standby mode and automatic scale-to-zero, Blaxel provides cost-effective, high-performance sandboxes for running AI-generated code. Learn more at [blaxel.com](https://blaxel.com). ## Installation First, install the Blaxel provider package: ```bash theme={"dark"} npm install @vibe-kit/blaxel ``` ## Prerequisites Before using the Blaxel provider, you need to: 1. Sign up for a Blaxel account at [https://blaxel.com](https://blaxel.com) 2. Get your Workspace ID and API Key from the [Blaxel dashboard](https://app.blaxel.com/settings) 3. Set them as environment variables: ```bash theme={"dark"} export BL_WORKSPACE=YOUR_WORKSPACE_ID export BL_API_KEY=YOUR_API_KEY ``` Alternatively, you can authenticate using the Blaxel CLI: ```bash theme={"dark"} npm install -g @blaxel/cli bl login ``` ## Configuration VibeKit uses a builder pattern with method chaining for type safety and flexibility. Configure your Blaxel provider and VibeKit instance: ### Using the provider directly ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createBlaxelProvider } from "@vibe-kit/blaxel"; // Create the Blaxel provider with configuration const blaxelProvider = createBlaxelProvider({ workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, memory: 4096, // optional, defaults to 4096 MB region: "us-pdx-1", // optional, Blaxel will choose default ttl: "24h", // optional, auto-delete after 24 hours }); // Create the VibeKit instance with the provider const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(blaxelProvider) .withWorkingDirectory("/workspace") // Optional: specify working directory .withSecrets({ // Any environment variables for the sandbox NODE_ENV: "production", }); // Generate code const result = await vibeKit.generateCode({ prompt: "Create a REST API with Express.js", mode: "ask" }); // Execute commands in the sandbox const response = await vibeKit.executeCommand("npm install && npm test"); console.log(response); // Start a development server await vibeKit.executeCommand("npm run dev", { background: true }); // Get the public URL for the service const url = await vibeKit.getHost(3000); console.log(`Service available at: ${url}`); // Clean up await vibeKit.kill(); ``` ### Using configuration object ```typescript theme={"dark"} import { VibeKit, VibeConfig } from "@vibe-kit/sdk"; const config: VibeConfig = { ..., environment: { blaxel: { // Required Blaxel authentication workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, // Optional resource configuration memory: 8192, region: "us-pdx-1", ttl: "48h", // Optional custom Docker image image: "my-custom-image:latest", // Optional port configuration ports: [ { target: 3000, name: "web-server" }, { target: 8080, name: "api-server" } ] }, }, }; ``` ## Configuration Options The `createBlaxelProvider` function accepts these configuration options: ### Required Options * **`workspace`** (string): Your Blaxel workspace ID from the dashboard (can be omitted if using CLI authentication) * **`apiKey`** (string): Your Blaxel API key (can be omitted if using CLI authentication) ### Optional Options * **`image`** (string): Custom Docker image. If not provided, it will be auto-selected based on the agent type: * `claude` → `blaxel/vibekit-claude` * `codex` → `blaxel/vibekit-codex` * `opencode` → `blaxel/vibekit-opencode` * `gemini` → `blaxel/vibekit-gemini` * `grok` → `blaxel/vibekit-grok` * Default: `blaxel/vibekit-codex` * **`memory`** (number): Memory allocation in MB (default: 4096) * **`region`** (string): Deployment region (e.g., "us-pdx-1", "eu-west-1"). If not specified, Blaxel chooses the optimal region automatically * **`ttl`** (string): Time-to-live for automatic sandbox cleanup (e.g., "24h", "30m", "7d"). Supported units: s (seconds), m (minutes), h (hours), d (days), w (weeks) * **`ports`** (array): Port configuration for exposing services. Default: `[{ target: 3000, name: "web-server" }]` ## ENV variables and secrets Configure your Blaxel provider using environment variables: ```bash theme={"dark"} # Required Blaxel credentials BL_WORKSPACE=your_workspace_id_here BL_API_KEY=your_api_key_here # Agent API keys ANTHROPIC_API_KEY=your_anthropic_key OPENAI_API_KEY=your_openai_key GOOGLE_API_KEY=your_google_key GEMINI_API_KEY=your_gemini_key GROK_API_KEY=your_grok_key # Optional GitHub integration GITHUB_TOKEN=your_github_token_here ``` Reference them in your code: ```typescript theme={"dark"} const blaxelProvider = createBlaxelProvider({ workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, // All other config is optional }); // GitHub configuration at SDK level const vibeKit = new VibeKit() .withSandbox(blaxelProvider) .withGithub({ token: process.env.GITHUB_TOKEN, repository: "owner/repo-name", }); ``` ## Unique Features ### Lightning-Fast Cold Starts Blaxel's innovative architecture enables sub-25ms cold starts from standby mode, making it one of the fastest sandbox providers available. This means near-instant resumption of sandboxes after periods of inactivity. ### Automatic Scale-to-Zero * **Cost optimization** - Sandboxes automatically enter standby mode when inactive * **Instant resume** - Sub-25ms wake-up time from standby * **No manual management** - Blaxel handles lifecycle automatically * **TTL-based cleanup** - Set automatic deletion timers to prevent resource waste ### Automatic Image Selection Blaxel automatically selects the appropriate pre-built Docker image based on your agent type, ensuring optimal compatibility and performance without manual configuration. ### Performance Features * **Fast execution** - Optimized container runtime for AI workloads * **Flexible resources** - Configure memory allocation per sandbox * **Port exposure** - Dynamically expose ports for web services * **Background processes** - Run long-running commands in the background ## Advanced Usage ### Custom Docker Image Use your own Docker image with pre-installed dependencies: ```typescript theme={"dark"} const blaxelProvider = createBlaxelProvider({ workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, image: "my-registry/my-custom-image:latest", }); ``` ### High-Memory Configuration For memory-intensive workloads: ```typescript theme={"dark"} const blaxelProvider = createBlaxelProvider({ workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, memory: 16384, // 16GB ttl: "48h", // Keep for 2 days }); ``` ### Background Command Execution Run long-running processes in the background: ```typescript theme={"dark"} // Start a background process await vibeKit.executeCommand("npm run dev", { background: true }); // The command runs independently // You can continue with other operations // Get the host URL to access the running service const url = await vibeKit.getHost(3000); console.log(`Dev server running at: ${url}`); ``` ### Exposing Multiple Ports Expose multiple services running on different ports: ```typescript theme={"dark"} const blaxelProvider = createBlaxelProvider({ workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, ports: [ { target: 3000, name: "frontend" }, { target: 8000, name: "api" }, { target: 5432, name: "database" }, ], }); // Start services on different ports await vibeKit.executeCommand("npm run api", { background: true }); await vibeKit.executeCommand("npm run frontend", { background: true }); // Get URLs for each service const apiUrl = await vibeKit.getHost(8000); const frontendUrl = await vibeKit.getHost(3000); console.log(`API: ${apiUrl}`); console.log(`Frontend: ${frontendUrl}`); ``` ### Regional Deployment Deploy to specific regions for lower latency: ```typescript theme={"dark"} const blaxelProvider = createBlaxelProvider({ workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, region: "eu-west-1", // Deploy to Europe }); ``` ### Time-to-Live Management Set automatic cleanup timers to manage costs: ```typescript theme={"dark"} const blaxelProvider = createBlaxelProvider({ workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, ttl: "2h", // Auto-delete after 2 hours }); // For development/testing - short TTL const devProvider = createBlaxelProvider({ workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, ttl: "30m", // Auto-delete after 30 minutes }); // For production - longer TTL const prodProvider = createBlaxelProvider({ workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, ttl: "7d", // Auto-delete after 7 days }); ``` ## System Requirements * **Node.js 18+** - Runtime environment * **Blaxel account** - Active account with workspace and API key * **Internet connection** - Required for cloud sandbox execution ## Limitations * **Pause/Resume**: Blaxel automatically handles standby mode, so manual pause operations are not required. Sandboxes automatically enter standby when inactive and resume in sub-25ms when needed. * **Resource limits**: Memory and CPU resources are based on your Blaxel plan tier. Check your dashboard for current limits. ## Troubleshooting **Authentication errors:** ```bash theme={"dark"} # Verify your credentials are set correctly echo $BL_WORKSPACE echo $BL_API_KEY # Re-export if needed export BL_WORKSPACE=your_workspace_id_here export BL_API_KEY=your_api_key_here # Or login via CLI bl login ``` **Sandbox creation timeout:** ```typescript theme={"dark"} // Increase memory for faster initialization const blaxelProvider = createBlaxelProvider({ workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, memory: 8192, // Increase from default 4096 }); ``` **Port exposure issues:** ```typescript theme={"dark"} // Ensure the service is running before calling getHost await vibeKit.executeCommand("npm start", { background: true }); // Wait a moment for the service to start await new Promise(resolve => setTimeout(resolve, 2000)); // Then get the host URL const url = await vibeKit.getHost(3000); ``` **Image pull errors:** ```typescript theme={"dark"} // Specify a custom image if default images aren't accessible const blaxelProvider = createBlaxelProvider({ workspace: process.env.BL_WORKSPACE!, apiKey: process.env.BL_API_KEY!, image: "ubuntu:22.04", // Use a reliable base image }); ``` **Region availability:** ```bash theme={"dark"} # List available regions using Blaxel CLI bl regions list # Or let Blaxel choose automatically by omitting the region parameter ``` ## Cost Optimization Tips 1. **Use TTL wisely**: Set appropriate TTL values based on your usage pattern ```typescript theme={"dark"} // Development/testing - short TTL ttl: "30m" // 30 minutes // Production workflows - longer TTL ttl: "24h" // 24 hours ``` 2. **Leverage automatic scale-to-zero**: Blaxel automatically puts sandboxes in standby mode when idle, reducing costs without manual intervention 3. **Right-size memory**: Start with minimal memory and scale up as needed ```typescript theme={"dark"} // Start small memory: 4096, // 4GB // Scale up if needed memory: 8192, // 8GB ``` 4. **Clean up promptly**: Always call `kill()` when done to avoid unnecessary charges ```typescript theme={"dark"} try { // Your code here } finally { await vibeKit.kill(); } ``` 5. **Use CLI authentication**: For local development, use `bl login` to avoid storing credentials in code ## Support For issues related to: * **Blaxel Platform**: Visit [Blaxel Documentation](https://docs.blaxel.com) * **VibeKit Integration**: Open an issue on [GitHub](https://github.com/superagent-ai/vibekit/issues) * **Community Support**: Join our [Discord](https://discord.gg/spZ7MnqFT4) ## Next Steps * Explore [GitHub integration](../sdk/github-integration) for automated PR workflows * Learn about [streaming](../sdk/streaming) for real-time command output * Check out [session management](../sdk/session-management) for persistent workflows # Cloudflare Source: https://docs.vibekit.sh/supported-sandboxes/cloudflare Configure VibeKit with Cloudflare Sandboxes Cloudflare Sandboxes provide edge-native sandboxed code environments built on Cloudflare's container platform and Durable Objects. Unlike other VibeKit providers, Cloudflare sandboxes run exclusively within Cloudflare Workers for agentic & AI use cases. Learn more about Cloudflare Workers [here](https://workers.cloudflare.com/). ## Installation ```bash theme={"dark"} npm install @vibe-kit/cloudflare ``` ## Configuration ### Using the provider directly ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createCloudflareProvider } from "@vibe-kit/cloudflare"; // This must be called within a Cloudflare Worker const provider = createCloudflareProvider({ env: env, // Your Worker's env object containing the Sandbox binding hostname: "your-worker.domain.workers.dev", // Your Worker's hostname }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(provider); // Generate and run code const result = await vibeKit.generateCode({ prompt: "Create a simple web server using Node.js on port 3000", mode: "code", }); // Get the preview URL for the running server const previewUrl = await vibeKit.getHost(3000); console.log(`Server running at: ${previewUrl}`); // Clean up await vibeKit.kill(); ``` ## Worker Setup Cloudflare sandboxes require specific Worker configuration: ### 1. Configure wrangler.json ```jsonc theme={"dark"} { "name": "my-vibekit-worker", "main": "src/index.ts", "compatibility_date": "2024-01-01", "containers": [ { "class_name": "Sandbox", "image": "./node_modules/@cloudflare/sandbox/Dockerfile", "max_instances": 1 } ], "durable_objects": { "bindings": [ { "class_name": "Sandbox", "name": "Sandbox" } ] }, "migrations": [ { "new_sqlite_classes": ["Sandbox"], "tag": "v1" } ] } ``` ### 2. Create your Worker ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createCloudflareProvider } from "@vibe-kit/cloudflare"; // Export the Sandbox class for Durable Objects export { Sandbox } from "@cloudflare/sandbox"; export default { async fetch(request: Request, env: Env): Promise { // Handle VibeKit requests const provider = createCloudflareProvider({ env, hostname: request.headers.get("host") || "localhost", }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(provider); const result = await vibeKit.generateCode({ prompt: "Create a Node.js web server", mode: "code", }); return new Response(JSON.stringify(result), { headers: { "Content-Type": "application/json" }, }); }, }; ``` ## ENV variables and secrets ```bash theme={"dark"} ANTHROPIC_API_KEY=your_anthropic_api_key_here OPENAI_API_KEY=your_openai_api_key_here # If using OpenAI models GOOGLE_API_KEY=your_google_api_key_here # If using Gemini models ``` In your Worker code: ```typescript theme={"dark"} const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(provider); ``` ## Configuration Options The `createCloudflareProvider` function accepts these configuration options: * **`env`** (required): Your Cloudflare Worker's environment object containing the `Sandbox` Durable Object binding * **`hostname`** (required): Your Worker's hostname used for generating preview URLs when exposing ports ## Unique Features ### Preview URLs Cloudflare sandboxes can generate public preview URLs when services are exposed on specific ports, making them accessible from anywhere on the internet. ### Edge-Native Execution Sandboxes run on Cloudflare's global edge network, providing low-latency execution closest to your users. ### Durable Objects Integration Built on Cloudflare's Durable Objects platform for strong consistency, automatic geographic distribution, and seamless Workers platform integration. ## Local Development For local development with `wrangler dev`, only ports explicitly exposed in the Dockerfile are available for port forwarding. This is not an issue in production. To test multiple ports locally, create a custom Dockerfile: ```dockerfile theme={"dark"} FROM docker.io/cloudflare/sandbox:0.1.3 EXPOSE 3000 EXPOSE 8080 EXPOSE 3001 # Always end with the same command as the base image CMD ["bun", "index.ts"] ``` Then update your wrangler.json to use the custom Dockerfile: ```jsonc theme={"dark"} { "containers": [ { "class_name": "Sandbox", "image": "./Dockerfile", // Point to your custom Dockerfile "max_instances": 1 } ] } ``` ## Requirements * **Cloudflare Workers**: Must run within a Cloudflare Worker environment * **Wrangler**: For local development and deployment * **Docker**: For building sandboxes locally and deploying to Cloudflare * **Node.js 18+**: For development tooling # Dagger (Local) Source: https://docs.vibekit.sh/supported-sandboxes/dagger Configure VibeKit with local Dagger sandboxes for fast, offline development Dagger provides containerized sandboxes that run locally on your machine using Docker and the Dagger engine. This enables fast, offline development with complete isolation and control. Perfect for local development, testing, and when you need the speed of local execution with the isolation of containers. Learn more about Dagger [here](https://dagger.io). ## Installation First, install the Dagger CLI on your system: **macOS:** ```bash theme={"dark"} brew install dagger/tap/dagger ``` **Linux:** ```bash theme={"dark"} curl -fsSL https://dl.dagger.io/dagger/install.sh | BIN_DIR=$HOME/.local/bin sh ``` **Windows:** ```bash theme={"dark"} winget install Dagger.Cli ``` Then install the Dagger provider package: ```bash theme={"dark"} npm install @vibe-kit/dagger ``` **Verify installation:** ```bash theme={"dark"} dagger version docker --version ``` ## Configuration VibeKit uses a builder pattern with method chaining for type safety and flexibility. Configure your Dagger provider and VibeKit instance: Dagger supports multiple container registries for storing and sharing pre-built agent images. Choose the registry that best fits your infrastructure and security requirements. ### Default Configuration (Docker Hub) ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createLocalProvider } from "@vibe-kit/dagger"; const provider = createLocalProvider({ preferRegistryImages: true, // Use optimized images when available registryName: "dockerhub", // Defaults to DockerHub registryUser: "your-dockerhub-username" // Optional: for pushing/pulling images }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(provider); // Generate code const result = await vibeKit.generateCode({ prompt: "Create a REST API with Express.js", mode: "ask" }); // Run development server in background await vibeKit.executeCommand("npm run dev", { background: true }); // Get local host URL const host = await vibeKit.getHost(3000); console.log(`Server running at: ${host}`); // Clean up await vibeKit.kill(); ``` ### Using GitHub Container Registry GitHub Container Registry provides seamless integration with GitHub workflows: ```typescript theme={"dark"} const provider = createLocalProvider({ registryName: "ghcr", registryUser: "github-username", githubToken: process.env.GITHUB_TOKEN, // Required for GHCR }); ``` **Setting up GHCR:** ```bash theme={"dark"} # Set GitHub token (requires packages:write permission) export GITHUB_TOKEN=ghp_xxxxxxxxxxxx # Login to GHCR echo $GITHUB_TOKEN | docker login ghcr.io -u USERNAME --password-stdin # Initialize with GHCR vibekit init --providers dagger --agents claude,codex \ --registry ghcr --registry-user github-username ``` ### Using AWS ECR AWS Elastic Container Registry for enterprise AWS deployments: ```typescript theme={"dark"} const provider = createLocalProvider({ registryName: "ecr", registryUser: process.env.AWS_ACCOUNT_ID, // AWS CLI must be configured with credentials }); ``` **Setting up AWS ECR:** ```bash theme={"dark"} # Configure AWS credentials aws configure # Set environment variables export AWS_ACCOUNT_ID=123456789012 export AWS_REGION=us-east-1 # Login to ECR aws ecr get-login-password --region $AWS_REGION | \ docker login --username AWS --password-stdin \ $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com # Initialize with ECR vibekit init --providers dagger --agents claude,codex \ --registry ecr --registry-user $AWS_ACCOUNT_ID ``` ## Quick Setup Initialize with automatic dependency installation: ```bash theme={"dark"} # Interactive setup with agent selection vibekit init --providers dagger --agents claude,codex # With Docker Hub image optimization (default) docker login vibekit init --providers dagger --agents claude,codex --upload-images # With GitHub Container Registry vibekit init --providers dagger --agents claude,codex \ --registry ghcr --registry-user github-username --upload-images # With AWS ECR vibekit init --providers dagger --agents claude,codex \ --registry ecr --registry-user $AWS_ACCOUNT_ID --upload-images ``` The setup will: * Install Docker and Dagger CLI if needed * Pre-build agent images for faster startup * Optionally upload optimized images to your chosen registry * Configure registry authentication ## ENV variables and secrets Configure your Dagger provider using environment variables: ```bash theme={"dark"} # GitHub integration (optional) GITHUB_TOKEN=your_github_token_here # Agent API keys ANTHROPIC_API_KEY=your_anthropic_key OPENAI_API_KEY=your_openai_key GOOGLE_API_KEY=your_google_key GEMINI_API_KEY=your_gemini_key GROK_API_KEY=your_grok_key # Registry configuration VIBEKIT_REGISTRY_NAME=ghcr # Registry type (dockerhub, ghcr, ecr) VIBEKIT_REGISTRY_USER=myusername # Registry username VIBEKIT_PREFER_REGISTRY=true # Use registry images when available VIBEKIT_PUSH_IMAGES=true # Auto-push built images # Registry-specific authentication GITHUB_TOKEN=ghp_xxxx # For GitHub Container Registry AWS_ACCOUNT_ID=123456789012 # For AWS ECR AWS_REGION=us-east-1 # For AWS ECR # Advanced configuration VIBEKIT_RETRY_ATTEMPTS=3 # Registry operation retries VIBEKIT_RETRY_DELAY=1000 # Retry delay in ms VIBEKIT_CONNECTION_TIMEOUT=30000 # Connection timeout in ms VIBEKIT_CONFIG_PATH=~/.vibekit # Config directory path VIBEKIT_LOG_LEVEL=debug # Enable debug logging ``` Reference them in your code: ```typescript theme={"dark"} // Dagger provider configuration const provider = createLocalProvider({ preferRegistryImages: true, dockerHubUser: "your-username", // All other config is auto-loaded from env vars }); // GitHub configuration at SDK level const vibeKit = new VibeKit() .withSandbox(provider) .withGithub({ token: process.env.GITHUB_TOKEN, repository: "owner/repo-name", }); ``` ## Configuration Options The `createLocalProvider` function accepts these configuration options: * **`preferRegistryImages`** (optional): Use pre-built registry images for faster startup (default: `true`) * **`registryUser`** (optional): Registry username for pulling/pushing custom images (works with any registry) * **`registryName`** (optional): Which registry to use - supported values: * `"dockerhub"` - Docker Hub (default) * `"ghcr"` - GitHub Container Registry * `"ecr"` - AWS Elastic Container Registry * **`dockerHubUser`** (optional, deprecated): Legacy Docker Hub username - use `registryUser` instead * **`privateRegistry`** (optional): Alternative registry URL for enterprise setups * **`pushImages`** (optional): Automatically push built images to registry (default: `true`) * **`autoInstall`** (optional): Automatically install missing dependencies (default: `false`) * **`retryAttempts`** (optional): Number of retry attempts for registry operations (default: `3`) * **`retryDelayMs`** (optional): Delay between retry attempts in milliseconds (default: `1000`) ## Unique Features ### Local Execution * **No internet required** - Everything runs on your machine * **Zero usage fees** - No per-minute or per-execution costs * **Offline development** - Work without network connectivity ### Performance Optimization * **Local execution** - No network latency for container operations * **Multi-registry support** - Choose the best registry for your infrastructure: * **Docker Hub** - Public registry, easy sharing * **GitHub Container Registry** - Integrated with GitHub workflows * **AWS ECR** - Enterprise AWS deployments * **Automatic image caching** - Reuse images across sessions * **Registry fallback** - Automatically falls back to local builds if registry is unavailable ## Registry Architecture VibeKit's Dagger provider supports multiple container registries through a flexible factory pattern: ### Registry Selection The registry is selected based on the `registryName` configuration: * **`dockerhub`** (default) - Public Docker Hub registry * **`ghcr`** - GitHub Container Registry (requires GitHub token) * **`ecr`** - AWS Elastic Container Registry (requires AWS credentials) ### Image Resolution Strategy 1. **Check local cache** - Look for existing Docker images locally 2. **Pull from registry** - Attempt to pull pre-built images from configured registry 3. **Build from Dockerfile** - Fall back to building from source if needed ### Migration Guide If you're upgrading from an older version that only supported Docker Hub: ```typescript theme={"dark"} // Old configuration (still supported) const provider = createLocalProvider({ dockerHubUser: "myusername" }); // New configuration (recommended) const provider = createLocalProvider({ registryUser: "myusername", // Universal field registryName: "dockerhub" // Explicit registry selection }); ``` The `dockerHubUser` field is maintained for backward compatibility but `registryUser` is now the recommended universal field that works with all registries. ## System Requirements * **Docker** - Container runtime (automatically installed during setup) * **Dagger CLI** - Container orchestration engine (automatically installed during setup) * **Node.js 18+** - Runtime environment * **8GB RAM recommended** - For running multiple containers * **Registry-specific requirements:** * **GitHub Container Registry**: GitHub account with packages:write permission * **AWS ECR**: AWS account with ECR permissions and configured AWS CLI ## Troubleshooting **Docker not running:** ```bash theme={"dark"} # Check Docker status docker ps # Start Docker (macOS) open -a Docker # Start Docker (Linux) sudo systemctl start docker ``` **Dagger CLI not found:** ```bash theme={"dark"} # Reinstall Dagger curl -fsSL https://dl.dagger.io/install.sh | bash dagger version ``` **Registry authentication issues:** ```bash theme={"dark"} # Docker Hub docker logout docker login # GitHub Container Registry echo $GITHUB_TOKEN | docker login ghcr.io -u USERNAME --password-stdin # AWS ECR aws ecr get-login-password --region $AWS_REGION | \ docker login --username AWS --password-stdin \ $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com ``` **Permission errors (Linux):** ```bash theme={"dark"} # Add user to docker group sudo usermod -aG docker $USER # Then log out and back in ``` **Registry image not found:** ```bash theme={"dark"} # Rebuild and push images vibekit prebuild --agents claude,codex --push ``` # Daytona Source: https://docs.vibekit.sh/supported-sandboxes/daytona Configure VibeKit with a Daytona Sandbox Daytona is an open-source runtime for executing AI-generated code in secure cloud sandboxes. Made for agentic & AI use cases. You can read more about it [here](https://daytona.io). ## Installation First, install the Daytona provider package: ```bash theme={"dark"} npm install @vibe-kit/daytona ``` ## How to use To use Daytona with VibeKit, you need to create an image in the Daytona dashboard using the following DockerFile: **Claude Codex Dockerfile** ```dockerfile theme={"dark"} # Use Ubuntu 22.04 as the base image FROM ubuntu:22.04 # Install curl and git, update package list RUN apt-get update && apt-get install -y curl git ripgrep # Install Node.js 24.x RUN curl -sL https://deb.nodesource.com/setup_24.x | bash - && apt-get install -y nodejs # Confirm installations RUN node -v && npm -v && git --version # Install Claude Code globalliy RUN npm install -g @anthropic-ai/claude-code ``` **OpenAI Codex Dockerfile** ```dockerfile theme={"dark"} # Use Ubuntu 22.04 as the base image FROM ubuntu:22.04 # Install curl and git, update package list RUN apt-get update && apt-get install -y curl git # Install Node.js 24.x RUN curl -sL https://deb.nodesource.com/setup_24.x | bash - && apt-get install -y nodejs # Confirm installations RUN node -v && npm -v && git --version # Install OpenAI Codex globally RUN npm install -g @openai/codex@latest ``` **Opencode Dockerfile** ```dockerfile theme={"dark"} # Use Ubuntu 22.04 as the base image FROM ubuntu:22.04 # Install curl and git, update package list RUN apt-get update && apt-get install -y curl git # Install Node.js 24.x RUN curl -sL https://deb.nodesource.com/setup_24.x | bash - && apt-get install -y nodejs # Confirm installations RUN node -v && npm -v && git --version # Install OpenAI Codex globally RUN npm i -g opencode-ai@latest ``` ## Configuration ### Using the provider directly ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createDaytonaProvider } from "@vibe-kit/daytona"; const daytonaProvider = createDaytonaProvider({ apiKey: process.env.DAYTONA_API_KEY!, image: "codex-image", serverUrl: "https://app.daytona.io/api", }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(daytonaProvider); // Generate code const result = await vibeKit.generateCode({ prompt: "Build a Python FastAPI application", mode: "ask" }); // Get host URL (if applicable) const host = await vibeKit.getHost(8000); // Clean up await vibeKit.kill(); ``` ### Using configuration object ```typescript theme={"dark"} import { VibeKit, VibeConfig } from "@vibe-kit/sdk"; const config: VibeConfig = { ..., environment: { daytona: { // Required Daytona API key apiKey: "****", image: "codex-image", serverUrl: "https://app.daytona.io/api" }, }, }; ``` ## ENV variables and secrets You can use environment variables for your Daytona configuration: ```bash theme={"dark"} DAYTONA_API_KEY=your_daytona_api_key_here ``` Then reference them in your code: ```typescript theme={"dark"} const daytonaProvider = createDaytonaProvider({ apiKey: process.env.DAYTONA_API_KEY!, image: "codex-image", serverUrl: "https://app.daytona.io/api", }); ``` # E2B Source: https://docs.vibekit.sh/supported-sandboxes/e2b Configure VibeKit with an E2B sandbox E2B is an open-source runtime for executing AI-generated code in secure cloud sandboxes. Made for agentic & AI use cases. You can read more about it [here](https://e2b.dev). ## Installation First, install the E2B provider package: ```bash theme={"dark"} npm install @vibe-kit/e2b ``` ## How to use To use E2B with VibeKit, you need to configure E2B when creating a new VibeKit instance. You can get your API key from the E2B dashboard. ### Using the provider directly ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createE2BProvider } from "@vibe-kit/e2b"; const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY!, templateId: "vibekit-claude", // Optional custom template }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(e2bProvider); // Generate code const result = await vibeKit.generateCode({ prompt: "Create a simple web server", mode: "ask" }); // Get host URL (if applicable) const host = await vibeKit.getHost(3000); // Clean up await vibeKit.kill(); ``` ### Using configuration object ```typescript theme={"dark"} import { VibeKit, VibeConfig } from "@vibe-kit/sdk"; const config: VibeConfig = { ..., environment: { e2b: { // Required E2B API key apiKey: "e2b_****", // Optional custom E2B template you want to use // that has the codex CLI and Git installed. templateId: "super-codex" }, }, }; ``` ## ENV variables and secrets You can use environment variables for your E2B configuration: ```bash theme={"dark"} E2B_API_KEY=your_e2b_api_key_here ``` Then reference them in your code: ```typescript theme={"dark"} const e2bProvider = createE2BProvider({ apiKey: process.env.E2B_API_KEY!, templateId: "vibekit-claude", }); ``` # Fly.io Source: https://docs.vibekit.sh/supported-sandboxes/flyio Configure VibeKit with Fly.io Coming soon... # Modal Source: https://docs.vibekit.sh/supported-sandboxes/modal Configure VibeKit with Modal Modal is a serverless computing platform that provides a sandboxes product for secure code execution. ## Installation First, install the Modal provider package: ```bash theme={"dark"} npm install @vibe-kit/modal ``` ## How to use To use Modal with VibeKit, you must first setup your modal profile by following [https://modal.com/docs/reference/cli/setup](https://modal.com/docs/reference/cli/setup). You may need to run `pip install modal` for the Python SDK beforehand, whose setup with `modal setup` also enables the JS SDK. ### Using the provider directly ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createModalProvider } from "@vibe-kit/modal"; const modalProvider = createModalProvider({ image: "vibekit-claude", // Optional custom template }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(modalProvider); // Generate code const result = await vibeKit.generateCode({ prompt: "Create a simple web server", mode: "ask" }); // Get host URL (if applicable) const host = await vibeKit.getHost(3000); // Clean up await vibeKit.kill(); ``` ### Using configuration object ```typescript theme={"dark"} import { VibeKit, VibeConfig } from "@vibe-kit/sdk"; const config: VibeConfig = { ..., environment: { modal: { // Optional custom image you want to use image: "super-codex" }, }, }; ``` # Northflank Source: https://docs.vibekit.sh/supported-sandboxes/northflank Configure VibeKit with Northflank persistent sandboxes Northflank is a PaaS that allows you to run persistent sandboxes either on the Northflank infrastructure or your GCP/AWS. You can read more about it [here](https://northflank.com). ## Installation First, install the Northflank provider package: ```bash theme={"dark"} npm install @vibe-kit/northflank ``` ## How to use To use Northflank with VibeKit, you need to configure Northflank when creating a new VibeKit instance. Note that you must create a new project and API key in the Northflank dashboard. ### Using the provider directly ```typescript theme={"dark"} import { VibeKit } from "@vibe-kit/sdk"; import { createNorthflankProvider } from "@vibe-kit/northflank"; const northflankProvider = createNorthflankProvider({ apiKey: process.env.NORTHFLANK_API_KEY!, projectId: "your-project-id", billingPlan: "nf-compute-200", // Optional: 2 vCPU & 4096GB RAM persistentVolumeStorage: 10240, // Optional: 10GiB }); const vibeKit = new VibeKit() .withAgent({ type: "claude", provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-sonnet-4-20250514", }) .withSandbox(northflankProvider); // Generate code const result = await vibeKit.generateCode({ prompt: "Create a React application", mode: "ask" }); // Get host URL (if applicable) const host = await vibeKit.getHost(3000); // Clean up await vibeKit.kill(); ``` ### Using configuration object ```typescript theme={"dark"} import { VibeKit, VibeConfig } from "@vibe-kit/sdk"; const config: VibeConfig = { ..., environment: { northflank: { // Required Northflank API key apiKey: "nf_****", // Optional custom image to override the inferred agent sandbox image image: "your-custom-image", // Optional project ID corresponding to the project you created projectId: "your-project-id", // Optional billing plan determining CPU & RAM (default: nf-compute-200 - 2 vCPU & 4096GB RAM) billingPlan: "nf-compute-200", // Optional persistent volume size in MB (default: 10240 - 10GiB) persistentVolumeStorage: 10240 }, }, }; ``` ## Configuration Options * **`apiKey`** (required): The API token you generated in the Northflank dashboard for authentication * **`image`** (optional): Override the inferred agent sandbox image with a custom image * **`projectId`** (optional): The project name you created in the Northflank dashboard * **`billingPlan`** (optional): Determines the CPU & RAM of the sandboxes (default: `nf-compute-200` which has 2 vCPU & 4096GB RAM) * **`persistentVolumeStorage`** (optional): The persistent volume size in MB (default: `10240` for 10GiB) ## ENV variables and secrets You can use environment variables for your Northflank configuration: ```bash theme={"dark"} NORTHFLANK_API_KEY=your_northflank_api_key_here ``` Then reference them in your code: ```typescript theme={"dark"} const northflankProvider = createNorthflankProvider({ apiKey: process.env.NORTHFLANK_API_KEY!, projectId: "your-project-id", }); ```