Skip to content

Latest commit

 

History

160 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Google Antigravity Custom Model Proxy — Add Claude, OpenAI, DeepSeek & Ollama to Antigravity IDE

Google Antigravity Custom Model Proxy Logo

Version License TypeScript Tests

One IDE, every custom LLM model. Enable Anthropic Claude 3.5 Sonnet, OpenAI GPT-4o, DeepSeek R1 / V3, OpenRouter, Ollama, Google AI Studio, Groq, Mistral, and custom local or cloud AI models directly inside Google Antigravity IDE. Features native UI dropdown integration, real-time bi-directional SSE streaming, tool calling, and enterprise-grade AES-256-GCM encryption.


Table of Contents


Overview

Google Antigravity Custom Model Enabler is an advanced proxy patch for Google Antigravity. It intercepts internal communication between the IDE's Language Server (Go binary) and Google's internal Cloud Code infrastructure. By injecting a local reverse proxy (127.0.0.1:50999), it translates Google Cloud Code API requests into compatible payloads for 19+ LLM providers, while maintaining native UI dropdowns, streaming tokens, and tool calls.


Architecture & Reverse Engineering

Cloud Code Internal API (v1internal)

Google Antigravity does not use public Gemini REST endpoints (v1beta). Instead, it communicates via internal v1internal endpoints:

  • POST /v1internal:fetchAvailableModels — Fetches active model definitions, quotas, and capabilities.
  • POST /v1internal:streamGenerateContent?alt=sse — Real-time Server-Sent Event (SSE) chat and code completion stream.
  • POST /v1internal:generateContent — Non-streaming fallback generation.

The Cloud Code protocol wraps request payloads inside a top-level request object:

{
  "project": "antigravity-internal-project",
  "requestId": "req-12345-abcde",
  "request": {
    "contents": [
      {
        "role": "user",
        "parts": [{ "text": "Refactor this function to be async." }]
      }
    ],
    "systemInstruction": {
      "parts": [{ "text": "You are an expert TypeScript developer." }]
    },
    "generationConfig": {
      "temperature": 0.2,
      "maxOutputTokens": 4096
    }
  },
  "model": "custom-claude-3-5-sonnet"
}

The local proxy intercepts these calls, extracts request, translates roles, system instructions, and tool definitions into the targeted provider format, and re-wraps the output in Google's expected envelope: {"response": {...}, "traceId": "...", "metadata": {}}.

Language Server Binary Patching

Recent Google Antigravity releases hardcode daily-cloudcode-pa.googleapis.com inside the Language Server Go binary. To prevent the IDE from bypassing the local proxy:

  1. Binary Patching: Build scripts patch the compiled binary string tables, replacing Google's hostname with 127.0.0.1:50999.
  2. Frontend Interception: src/main.ts intercepts and blocks SetCloudCodeURL IPC requests from overriding the endpoint dynamically.
  3. URL Padding Handler: src/proxy/urlBuilder.ts strips null/space binary padding from incoming URLs.

Protobuf Model Injection

To inject custom models into the native IDE model picker:

  1. When fetchAvailableModels is called, src/proxy/protoInjector.ts parses the Google response.
  2. src/proxy/idGenerator.ts generates DJB2-hash-based IDs (MODEL_PLACEHOLDER_<hash>) for each user model.
  3. Custom models are dynamically appended to agentModelSorts and model arrays so they render natively inside the IDE picker with full feature flags enabled.

Request Lifecycle & Data Flow

sequenceDiagram
    autonumber
    participant IDE as Antigravity IDE (UI)
    participant LS as Language Server (Go Binary)
    participant Proxy as Local Proxy (127.0.0.1:50999)
    participant Registry as Translator Registry
    participant Ext as External Provider API (OpenAI/Claude/Ollama)

    IDE->>LS: User sends prompt with custom model selected
    LS->>Proxy: POST /v1internal:streamGenerateContent?alt=sse
    Proxy->>Proxy: Intercept request & detect model ID (MODEL_PLACEHOLDER_*)
    Proxy->>Registry: Lookup provider translator (e.g. anthropic.ts)
    Registry->>Proxy: Transformed payload (Anthropic / OpenAI format)
    Proxy->>Ext: POST https://api.anthropic.com/v1/messages (SSE)
    loop SSE Token Streaming
        Ext-->>Proxy: data: {"type": "content_block_delta", ...}
        Proxy->>Proxy: mapChunkToGemini() via jsonRepair
        Proxy-->>LS: SSE data: {"response": {"candidates": [...]}}
        LS-->>IDE: Render text chunk in chat UI
    end
Loading

Screenshots & UI Integration

The injected UI seamlessly blends with Antigravity's dark VS Code-adjacent chrome:

Custom Models Dashboard Add Model Modal
Google Antigravity Custom Models Dashboard Settings Add Custom LLM Model Modal in Google Antigravity IDE
Provider Selection (Claude, OpenAI, DeepSeek, Ollama) Model Selector in Antigravity Chat UI
Supported LLM Providers Selection in Google Antigravity Google Antigravity Model Selector Dropdown Interface
Auto-fallback & Failover Stream Notification
Google Antigravity Custom Model Auto-fallback Failover Stream Notification

Key Technical Features

Automated Model Auto-Fallback & Stream Warning Cards

When a primary model encounters rate limits (rate_limit / 429), context length limits, or provider timeouts, the proxy automatically initiates an Auto-Fallback:

  • Seamless Failover: Automatically retries the prompt with a secondary model (e.g. falling back from MiniMax-M2.7 to MiniMax-M3 or Claude-3.5-Sonnet to GPT-4o).
  • Native Stream Warning Card: Emits an inline markdown warning block (> ⚠️ Auto-fallback: <model-1> failed (<reason>). Retrying with <model-2>…) directly into the IDE chat response stream without interrupting the agent's workflow.
  • Context Preservation: Retains the full conversational history and active tool definitions across the failover boundary.

Format Translators

The proxy features isolated translator modules under src/proxy/translators/:

  • OpenAI Translator (openai.ts): Full mapping between Gemini contents/parts and OpenAI messages, including tool calls, system prompts, and usage token metrics.
  • Anthropic Translator (anthropic.ts): Handles Claude system parameter, tool_use blocks, SSE content_block_start/delta events, and thinking parameter extraction.
  • Google AI Studio Passthrough (google.ts): Direct passthrough to Google AI Studio keys (https://generativelanguage.googleapis.com) with automated model routing.
  • Ollama Translator (ollama.ts): Compatible with local Ollama, LM Studio, and vLLM servers without requiring API keys.

Bi-Directional SSE Streaming

  • No Buffering Timeouts: Streaming requests (streamGenerateContent) bypass response buffering and pipe SSE chunks directly to prevent Language Server execution timeouts.
  • Safe JSON Repair (jsonRepair.ts): Malformed or truncated SSE chunks are parsed and repaired using string-level state machines (repairPartialJson()). Zero use of eval() or new Function().

Tool Calling & Function Execution

  • Converts Gemini functionDeclarations to OpenAI tools / Anthropic tool_use.
  • Matches execution responses (functionResponse) back to upstream tool_call_id tokens across multi-turn sessions using src/proxy/shared.ts state storage.

DeepSeek & Claude Thinking Support

  • Detects reasoning parameters (reasoning_effort, thinking) in modelUtils.ts.
  • Automatically strips or surfaces reasoning blocks (<think>...</think>) depending on IDE capabilities.

Per-Model Circuit Breaker & Resiliency (circuitBreaker.ts)

  • Short-Circuiting Failures: Automatically trips when an upstream provider experiences persistent errors or timeouts. Prevents the proxy from hanging and keeps the IDE model selection dropdown responsive.
  • Adaptive Retry Budget (retryBudget.ts): Dynamically adjusts retries per provider based on observed historical reliability. Flaky models receive fewer retries to prevent request storms, while stable models are granted retries.

Automated Stream Fallback Routing

  • Seamless Provider Redirection: If a primary custom model returns 429 Rate Limit or 5xx Server Error, the proxy automatically reroutes the prompt to an alternate configured fallback model.
  • In-Stream Transparency: Emits a lightweight markdown notification chunk directly at the top of the chat stream (e.g. > ⚠️ Auto-fallback: Claude 3.5 Sonnet failed (rate_limit). Retrying with DeepSeek R1...).

Telemetry, Metrics & Configuration Exchange

  • Real-Time Latency Metrics (metrics.ts): Exposes latency distributions (proxy_upstream_ms) and error counters (proxy_errors_total) via /metrics.
  • Config Import / Export (configExchange.ts): Provides structured JSON export and bulk import for easy model preset sharing across developer teams.
  • Native System Tray Integration (tray.ts, menu.ts): Embedded tray menu providing quick server status, log shortcuts, and toggle controls.

Security Architecture

AES-256-GCM Encryption (safeStorage)

All custom model configurations are stored in %APPDATA%/antigravity/custom_models.json (or OS equivalent).

  • Encryption at Rest: API keys are encrypted using AES-256-GCM via Electron safeStorage (backed by Windows DPAPI, macOS Keychain, or Linux Secret Service).
  • Auto-Migration: Upgrades legacy plaintext keys to encrypted payloads (enc:gcm:...) seamlessly on first run (src/proxy/modelLoader.ts).

Request Hardening & DoS Protection

  • Request Body Size Cap: Strict 10 MB payload limit to prevent buffer exhaustion DoS attacks (HTTP 413 Payload Too Large).
  • Timeouts: 30s-120s configurable timeouts on all outbound requests to prevent hung connections.
  • Header Masking: CSRF tokens and authorization headers are scrubbed from diagnostic logging outputs.

Quick Start & Installation

Windows Setup

One-Click Script

Double-click or run in terminal:

repatch.bat

npm Manual Build

npm run build
npm run repatch

macOS & Linux Setup

# macOS (Extracts /Applications/Antigravity.app, patches, repacks app.asar)
npm run repack:mac

# Linux (Auto-detects installation directory)
npm run repack:linux

Enterprise MITM HTTPS Mode

If your network requires port 443 interception with custom SSL certificates:

"Start Antigravity MITM.bat"

(Requires Administrator privileges)


ag-doctor Diagnostic CLI

ag-doctor is the built-in diagnostic and maintenance tool provided with this repository.

Command Reference

# Run full diagnostic suite (Binary patch status, proxy port, config integrity)
npm run doctor

# Quick health check
npm run doctor:check

# Automated repair (Applies binary patch, fixes corrupt config, resets ports)
npm run doctor:repair

# List active custom models and test API endpoints
npm run doctor:models

# Stream real-time diagnostic logs
npm run doctor:logs

CLI Architecture & Worker Mode

ag-doctor runs in two execution modes (ag-doctor/bin/ag-doctor.js):

  1. CLI Mode: One-shot execution for terminal environment checks, model listing, and automated repairs.
  2. Worker Mode (--worker): Spawns an in-process JSON-RPC daemon via stdin/stdout, eliminating process spawn overhead for IDE UI queries.

Visual Diagnostic Dashboard (ag-doctor-ui)

In addition to the terminal CLI, this repository includes ag-doctor-ui, a dedicated Electron UI renderer application:

  • Visual Health Monitors: Real-time status indicators for port 50999 binding, Language Server binary patches, and SSL certificate validity.
  • One-Click Auto-Repair: Single button repair flow to un-stick ports, restore corrupt app.asar backups, and re-apply version patches.
  • Live Log Inspector: Integrated log tailing window with real-time severity filters (INFO, WARN, ERROR) and automatic API key masking.

Traffic Inspector View (traffic-inspector.ts)

  • Real-Time Network Logging: Intercepts and displays active Cloud Code API requests, HTTP status codes, target models, translated providers, and end-to-end latency benchmarks.
  • Payload Diff & Replay: Generates visual diff views (generateDiffView) for request/response payloads and enables single-click request replaying (replayEntry).
  • Multi-Field Filtering: Filter entries instantly by URL path, model name, provider, or HTTP status code.

Failure Scenarios Showcase (custom-error-scenarios.ts, failure-scenario-showcase.ts)

  • Visual Error Simulation: Interactive showcase previewing all provider error scenarios (Rate Limits 429, Billing/Quota Overage, Auth Errors 401/403, Network Timeouts, SSL Bypass failures).
  • Native Antigravity Banner Rendering: Renders full-replica native Antigravity error cards complete with category badges, status tags, decoded troubleshooting hints, and primary/secondary action buttons (ag-btn-primary, ag-btn-dismiss).
  • Interactive QA Filter Chips: Filter error cards by scenario category (Rate Limit, Authentication, Network, Quota) for visual debugging and QA verification.

Version-Aware Patching Engine

  • Multi-Version Binary Patching: ag-doctor automatically detects installed Antigravity releases (v2.0.x through v2.3.x) and performs binary string replacement without corrupting Go executable alignment.
  • Backup & Rollback Safety: Creates timestamped .bak copies of app.asar before modifying binary payloads, allowing instant 1-command rollbacks (npm run doctor:repair).

Antigravity Remote 2.0 (Mobile & Daemon Bridge)

Antigravity Remote 2.0 brings Google Antigravity IDE and your custom models directly to your smartphone (Android / iOS). Control background tasks, monitor streaming reasoning models, review unified diffs, and approve CLI tool actions from anywhere via local Wi-Fi or automated Cloudflare Quick Tunnels.

IDE Chat UI ↔ Language Server (Hub :55256) ◄── gRPC-Web ── Daemon Go (:8090 / Cloudflare Tunnel)
                                                                 ▲
                                                                 │ WebSocket (JSON RPC)
                                                                 ▼
                                                    Mobile Client (Flutter App)

Remote Architecture & Protocol

  • Go Daemon Bridge (remote/daemon): Scans running Antigravity language_server processes, extracts session CSRF tokens with a background watchdog, frames binary gRPC-Web Protobuf & Jetbox Connect JSON streams, and serves a hardened WebSocket server (/ws?token=...).
  • Zero-Config Discovery & Pairing: UDP LAN Beacon on port 41234 for automatic discovery, 60s rotating 6-digit PIN pairing (POST /pair), and live Cloudflare Quick Tunnels with terminal QR code pairing.
  • Interactive PTY Terminal & ADB Bridge: Interactive shell terminal emulator and Android Debug Bridge (adb.*) for remote device and file management.
  • StepRecovery Buffer: Retains the last 100 trajectory frames in memory to re-synchronize sessions immediately after transient network drops without losing chat state.

Mobile Companion Features (remote/mobile)

  • Exact Antigravity 2.0 Design Tokens: Built to match real computed IDE stylesheet tokens (htmlcss.log) — featuring Quiet Console welcome cards, #101010 canvas, #21252B sidebars, #528BFF focus accents, #D7BA7D syntax highlights, and native diff insertion/deletion tints.
  • Interactive Tool Approvals (submit_approval): Push alerts and cards to authorize shell commands and file writes with single-use (once) or full-session (session) approval scopes and auto-rejection timeouts.
  • Interactive Choice Prompts (AskQuestion): Single and multi-select cards for responding directly to agent decision forks.
  • Colosseum Battle Arena: Multi-model duel supervision (e.g. Claude vs Gemini) with live branch diffing and arbitration voting.
  • MCP Server & Tool Explorer: Inspect active Model Context Protocol (MCP) servers, trigger tools, and complete OAuth flows.
  • Workspace File Explorer & Code Viewer: Interactive tree navigation, search, find-in-page, syntax icons, and code inspection.
  • Scheduled Tasks Monitor & Code Review Comments: View cron jobs, trigger tasks on-demand, and attach comments to code diffs on the fly.

Running the Remote Daemon

# Start Daemon with Cloudflare Tunnel & Auth Token
cd remote/daemon
go run main.go --port 8090 --tunnel cloudflare --auth-token mysecret

# Run Flutter Mobile Companion
cd remote/mobile
flutter run -d <device-id>

Provider Configuration Matrix

Provider Preset Slug Target Base URL Key Required Streaming Tool Calling
OpenAI openai https://api.openai.com/v1 Yes Yes Yes
Anthropic anthropic https://api.anthropic.com/v1 Yes Yes Yes
OpenRouter openrouter https://openrouter.ai/api/v1 Yes Yes Yes
Google AI Studio google https://generativelanguage.googleapis.com Yes Yes Yes
Ollama ollama http://localhost:11434 No Yes Yes
DeepSeek openai https://api.deepseek.com/v1 Yes Yes Yes
Groq openai https://api.groq.com/openai/v1 Yes Yes Yes
Mistral AI openai https://api.mistral.ai/v1 Yes Yes Yes
Together API openai https://api.together.xyz/v1 Yes Yes Yes
LM Studio openai http://localhost:1234/v1 No Yes Yes
vLLM / LocalAI openai Custom Endpoint Optional Yes Yes

custom_models.json Schema Reference

Configurations are saved under %APPDATA%/antigravity/custom_models.json:

[
  {
    "id": "custom-claude-3-5-sonnet",
    "name": "Claude 3.5 Sonnet",
    "provider": "anthropic",
    "model": "claude-3-5-sonnet-20241022",
    "apiKey": "enc:gcm:...",
    "baseUrl": "https://api.anthropic.com/v1",
    "parameters": {
      "temperature": 0.7,
      "topP": 0.9,
      "maxTokens": 4096,
      "customSystemPrompt": "Focus on high-performance clean code."
    },
    "retry": {
      "maxRetries": 3,
      "timeoutMs": 60000
    }
  }
]

Developer Guide

Codebase Structure

├── ag-doctor/             # Diagnostic CLI suite & worker daemon
├── scripts/               # Repack, deploy, and MITM launcher scripts
├── src/
│   ├── constants.ts       # Central source of truth (Providers, default ports, timeouts)
│   ├── cryptoStore.ts     # AES-256-GCM encryption wrapper
│   ├── main.ts            # Electron main process interceptors
│   ├── preload.ts         # Injected Custom Models Settings UI
│   ├── ipcHandlers.ts     # IPC storage & connection test handlers
│   ├── proxy/
│   │   ├── proxy.ts       # Core HTTP proxy server orchestration
│   │   ├── registry.ts    # Translator auto-discovery registry
│   │   ├── protoInjector.ts # Protobuf payload injection
│   │   ├── jsonRepair.ts  # Safe non-eval SSE JSON repair
│   │   ├── retryStrategy.ts # Exponential backoff retry logic
│   │   └── translators/   # OpenAI, Anthropic, Google, Ollama translators
│   └── __tests__/         # 1455 unit tests (Vitest)

Building & Watch Mode

# Compile TypeScript files (src/ -> dist/)
npm run build

# Watch mode for iterative code changes
npm run watch

Running Tests

The test suite runs via Vitest:

# Run all 1455 unit tests
npm test

# Run tests in watch mode
npm run test:watch

Adding a New Translator Module

To add support for a new LLM provider format:

  1. Create src/proxy/translators/<provider>.ts.
  2. Implement and export:
    export function mapGeminiTo<Provider>(body: any, modelName: string): any;
    export function map<Provider>ToGemini(res: any, modelName: string): any;
    export function map<Provider>ChunkToGemini(chunk: any, modelName: string): any;
  3. Add the provider definition to PROVIDERS in src/constants.ts.

Troubleshooting & Diagnostics

Symptom Cause Solution
Models missing from chat dropdown IDE update overwrote app.asar Run npm run doctor:repair or repatch.bat
Connection test failed (401/403) Invalid or expired API Key Check key in Settings or npm run doctor:models
Port 50999 in use Another proxy instance active ag-doctor automatically picks fallback port
ERR_HTTP_HEADERS_SENT in logs Upstream response race condition Handled automatically by safeWriteHead helpers
SSL / Certificate error Corporate proxy SSL interception Enable MITM mode via "Start Antigravity MITM.bat"

Full troubleshooting guides are detailed in TROUBLESHOOTING.md.


Frequently Asked Questions (FAQ)

How do I add Anthropic Claude 3.5 Sonnet or DeepSeek R1 to Google Antigravity IDE?

You can add Claude 3.5 Sonnet, DeepSeek R1, OpenAI GPT-4o, or any custom LLM model by opening the custom model settings modal in Google Antigravity IDE, entering your API key and provider base URL, and running the automatic patcher (repatch.bat on Windows or npm run repack:mac on macOS).

Are my provider API keys secure?

Yes. All custom model configurations and API keys are stored locally and encrypted at rest using AES-256-GCM via Electron safeStorage (backed by Windows DPAPI, macOS Keychain, or Linux Secret Service). Keys are never sent to third-party tracking servers.

Can I run local LLMs with Ollama or LM Studio in Google Antigravity?

Yes. Set the provider to ollama or openai with endpoint http://localhost:11434 (Ollama) or http://localhost:1234/v1 (LM Studio). No API keys are required for offline local inference.

How does auto-fallback and failover work?

If a primary custom model returns a 429 Rate Limit, quota overage, or timeout, the proxy automatically retries the prompt with your configured secondary fallback model and renders a native warning banner in the chat stream without breaking conversation history.


GitHub Search & Topics Metadata

For maximum repository discoverability on GitHub Search and Google SERP, ensure the following repository topics are assigned under GitHub Repository Settings > About:

google-antigravityantigravity-idecustom-modelsclaude-3-5-sonnetdeepseek-r1openai-gpt4oollamaopenrouterllm-proxycloudcode-patch


License & Acknowledgments

  • License: Distributed under the Apache-2.0 License. See LICENSE for details.
  • Original Repository & Credits: Special thanks to Abdulvahap OGUT for the original project repository: vahapogut/antigravity-add-model.

About

One IDE, every model. Custom LLM proxy for Google Antigravity IDE (Claude 3.5 Sonnet, OpenAI GPT-4o, DeepSeek R1, Ollama, OpenRouter).

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

11 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages