Skip to content
Proyek

Tentang

Turn Gemini Web into a local Coding Agent or a 0-token-wait subagent for Claude Code, Cursor & Antigravity — Zero plugins, 100% official MCP, single Rust binary, any language, sandboxed patch & rollback | 把 Gemini 网页端变成你的本地 Coding Agent 与省额子代理

Alat pengembangan

Cara angka ini diukur

49 bintang5 Fork +8 dalam 24 jam

Yang dapat Anda lakukan

  • Stage 1 (Read-Only Recon): Host agent dispatches a pure read-only brief. Gemini Web fetches it via get_pending_task, explores via workspace_snapshot / code_outline / code_search / batch_read (all readOnlyHint: true — zero browser approval popups), and returns a condensed briefing via report_task_done.
  • Configurable via CLI flags or GEMLATCH_UI_MODE / GEMLATCH_WEB_MODEL (supports comma-separated fallback candidates like "Pro,Thinking", with no forced default); if the active Gemini Web UI mode or model does not match before sending, GemLatch cancels the task and exits with code 13 (gate_mismatch) so quota is never wasted on the wrong mode or model.
  • Supports --template recon|build|test|review, server-side --acceptance verification loops, delegate-batch --batch-file sequential queues, and second-session --cross-review (--fail-on-review-blocker exits 14). Standardized exit codes cover 0–7 and 10–14 (with 4 for needs_human — login, CAPTCHA, or Allow/Deny card; never bypassed).
  • For interactive Gemini Web chats across multiple repositories, explicitly opt into --unrestricted-fs (or allow_unrestricted_fs = true): cross-directory .mcp-trash/ snapshots and rollback_last continue to work while allowlist.toml and secret.key stay hard-blocked.

Pertumbuhan bintang terukur

dalam 24 jam
+8
dalam 7 hari
Mengumpulkan riwayat
dalam 15 hari
Mengumpulkan riwayat
dalam 1 bulan
Mengumpulkan riwayat

Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.

README.md

Asli

简体中文 | English

GemLatch

CI Latest Release License: MIT MCP Rust Edition

Turn Gemini Web into your local Coding Agent — or a 0-token-wait subagent for Claude Code, Cursor & Antigravity. Zero browser extensions · 100% official Streamable HTTP MCP · Single Rust binary · Works with any language (Python, TypeScript/JS, Go, Rust, etc.).

GemLatch: Main Agent Quota Savings & Dual-Mode Architecture

Mode 1: Gemini Web as Local Coding Agent (15s) Mode 2: Split-Screen Subagent Delegation — 0 Tokens While Waiting (25s)
Demo 1: @gemlatch local coding agent & official Allow/Deny card Demo 2: Antigravity/Claude Code dispatching to Gemini Web at 0 tokens
  • Slash Frontier Quota Burn (0 Tokens While Waiting): Antigravity, Claude Code, or Cursor dispatches heavy repo exploration and multi-file edits in one command, spending 0 host tokens while waiting and receiving only a compact <= 3 KiB JSON report (with full details persisted to report_path).
  • Zero Plugins · 100% Official Native MCP · Compliance-First: Connects directly to Google's official Developer Mode (Streamable HTTP MCP) with native function calling and official Allow / Deny confirmation cards—zero private API reverse-engineering, zero cookie/token extraction, zero account pooling, and zero CAPTCHA/approval bypasses (see Compliance & Account Safety →).
  • Any Codebase, Single Binary: Compiled as a zero-runtime-dependency Rust binary, yet not limited to Rust—works with any codebase (Python, TypeScript/JS, Go, Rust, C++, etc.) with ready-to-use multi-language allowlist templates.
  • Safe-by-Default & Zero-Restart Hot-Switch: Exposes 8 sandboxed tools by default, applies two-phase atomic patches with .mcp-trash/ one-click rollback, and hot-switches projects in milliseconds via gemlatch workspace set <dir> without restarting the gateway or tunnel.
Dimension Without GemLatch With GemLatch
Main Agent Quota Burn Frontier model burns context reading files, iterating patches, and fixing lint/build errors Host spends 0 tokens while waiting; receives a <= 3 KiB JSON summary (report_path on demand)
Cross-File Exploration Cost Dozens of round-trips or manual copy-paste between IDE and browser Gemini Web runs zero-popup read-only recon via workspace_snapshot / code_outline / code_search / batch_read
Plugin Dependency / Ban Risk Reverse-engineered API proxies, cookie replay, or fragile DOM extensions break on UI updates and risk bans 100% official Streamable HTTP MCP + native Allow / Deny cards; zero credential scraping or bypasses (details)
Safety & Rollback Unbounded edits or external stdio servers with soft permission bypasses Canonical path sandbox, shell-free scoped_exec allowlist, and .mcp-trash/ atomic rollback_last

🔒 Safe-by-Default opt-in switches. Out of the box, GemLatch exposes 8 tools locked to a single --root sandbox; shell_exec and delegation tools are hidden and direct calls are rejected (-32601). Enable higher-privilege modes explicitly (/health reflects tools, shell_exec, delegate, fs_mode, and unrestricted_fs):

  • --enable-shell-exec (or allow_shell_exec = true): exposes the 9th tool shell_exec (unrestricted OS shell, no rollback; approve each call).
  • --enable-delegate (or enable_delegate = true): enables the local task bus and 2 delegation tools (get_pending_task, report_task_done) so Claude Code / Cursor / Antigravity can orchestrate Gemini Web as a closed-loop subagent via gemlatch delegate.
  • --unrestricted-fs (or allow_unrestricted_fs = true): enables unrestricted filesystem mode so all 8 native tools and shell_exec accept absolute/cross-directory paths (including cross-directory snapshots & rollback), while still hard-blocking reads, searches, or writes to allowlist.toml and secret.key.

🔓 Unlock Gemini Web's Hidden Official MCP Mode (Prerequisites)

GemLatch taps into Google's official Connected Apps Platform (Custom MCP Apps) and Gemini Apps Developer Mode (gemini.google.com/devmode). Per Google's documentation, all four of the following are required for the Developer Mode toggle to appear in the Gemini Web sidebar:

  1. The UI language must be set to English. The entry is hidden under Simplified Chinese and other non-English interfaces.
  2. Your account and network environment must be in the US region, and you must be 18 or older.
  3. Personal Google accounts only. Google Workspace business and education accounts are not supported yet.
  4. Gemini Apps Activity / History must be enabled.

In addition, Google only accepts a public HTTPS Streamable HTTP endpoint (MCP protocol versions 2025-03-26 through 2025-11-25). Direct localhost connections are not supported, and neither is the legacy SSE transport — which is why GemLatch pairs cleanly with a public HTTPS tunnel (such as ngrok or Cloudflare Tunnel).

💡 Quick Tips

  1. ngrok is recommended for tunneling: Cloudflare tunnels enforce request rate limits that can be triggered during frequent tool calls. ngrok includes a free static domain upon registration, offering more stable connectivity without needing to update the endpoint URL on every restart.
  2. Mention @ your MCP once in a new Gemini Web chat: When starting a new conversation on Gemini Web, type @<your-MCP-name> once to activate it before its tools can be used. You only need to @-mention it once per session — follow-up turns in the same chat do not need @ again (gemlatch delegate --new-chat --mention <name> handles initial activation automatically and --continue skips @).

🚀 Two Flagship Modes: Local Coding Agent & Subagent for Claude Code, Cursor & Antigravity

One gateway powers two first-class workflows — switch anytime without restarting:

Flagship Mode How you use it What it solves
① Turn Gemini Web into your Local Coding Agent Start in default safe mode (8 tools) + tunnel, then @<AppName> directly inside gemini.google.com; hot-switch repos with workspace set or opt into --unrestricted-fs Zero browser extensions, zero extra API bills — turns your existing Gemini Web quota directly into a local Coding Agent with code outlines, atomic patches, verify-on-write (cargo_check, ruff_check, tsc_check, go_vet, etc.), and instant rollback
② Turn Gemini Web into a Native Subagent Enable --enable-delegate, drop in the delegation rule template, and let Claude Code, Cursor, or Antigravity orchestrate Gemini Web via gemlatch delegate Host Agent focuses on architecture, exact briefs, targeted git diff review, and tough edge cases (0 tokens while waiting, <= 3 KiB JSON back); Gemini Web (Subagent) handles zero-popup read-only recon, multi-file edits, server-gated --acceptance fix loops, and --cross-review

End-to-End Dual-Mode Architecture (Standalone Coding Agent & Subagent Loop)

flowchart TD
    USR["<b>Mode ① · Direct Developer Chat</b><br/>@mention inside gemini.google.com<br/>Use Gemini Web directly as your local Coding Agent"]
    AG["<b>Mode ② · Host Agent (Claude Code / Cursor / Antigravity)</b><br/>Plans briefs · Single-command dispatch · 0 tokens while waiting · Lightweight review"]
    BUS["<b>Local Delegation &amp; Control Plane · gemlatch delegate</b><br/>Pure-Rust no-TLS loopback Chrome CDP (127.0.0.1:9222)<br/>Fail-closed --ui-mode / --web-model gates · Local task bus<br/>Workspace hot-switch (--workspace) · /app/&lt;id&gt; URL writeback"]
    WEB["<b>Gemini Web (Coding Agent / Worker Subagent)</b><br/>gemini.google.com · English UI / Developer Mode<br/>Official Custom MCP App · Multi-step native Tool Chaining<br/>Allow / Deny cards driven by readOnlyHint / destructiveHint"]
    TUN["<b>HTTPS Tunnel · ngrok / Cloudflare Tunnel</b><br/>Forwards public HTTPS to loopback 127.0.0.1:3006<br/>Proxy headers on /health, /abort, or /local/* return 403"]
    GW["<b>Local MCP Gateway · gemlatch (single Rust binary)</b><br/>rmcp + axum + tokio + syn + ignore<br/>Constant-time 256-bit path key + Origin validation<br/>SandboxPath + .mcp-trash/ snapshots + WorkspaceLedger"]

    USR -->|"Direct @ chat<br/>Read / Patch / Verify / Rollback"| WEB
    AG -->|"1. Single-command dispatch<br/>gemlatch delegate --task-file ..."| BUS
    BUS -->|"2. Loopback CDP dispatch<br/>+ UI mode / model verification"| WEB
    WEB -->|"HTTPS · Streamable HTTP (POST)<br/>https://&lt;domain&gt;/mcp/&lt;256-bit-key&gt;"| TUN
    TUN -->|"127.0.0.1:3006 (loopback only)"| GW
    GW -->|"3. report_task_done wakes bus<br/>&lt;= 3 KiB JSON report + exit code 0–7, 10–14"| AG

Key Capabilities Across Both Modes

  1. Two-Stage Quota-First Funnel (Zero-Popup Recon → Precision Execution):
    • Stage 1 (Read-Only Recon): Host agent dispatches a pure read-only brief. Gemini Web fetches it via get_pending_task, explores via workspace_snapshot / code_outline / code_search / batch_read (all readOnlyHint: true — zero browser approval popups), and returns a condensed briefing via report_task_done.
    • Stage 2 (Batched Patch & Follow-Up Rework): Host agent specifies the exact plan in one write brief; Gemini Web batches edits into minimal atomic safe_patch calls (with optional verify against any read_only = true preset) and reports back. For rework, the host passes --continue to reuse the same Gemini Web chat (skipping @ activation and avoiding re-reading files).
  2. Fail-Closed --ui-mode / --web-model Gating, Server Acceptance Gate & Cross-Review:
    • Configurable via CLI flags or GEMLATCH_UI_MODE / GEMLATCH_WEB_MODEL (supports comma-separated fallback candidates like "Pro,Thinking", with no forced default); if the active Gemini Web UI mode or model does not match before sending, GemLatch cancels the task and exits with code 13 (gate_mismatch) so quota is never wasted on the wrong mode or model.
    • Supports --template recon|build|test|review, server-side --acceptance verification loops, delegate-batch --batch-file sequential queues, and second-session --cross-review (--fail-on-review-blocker exits 14). Standardized exit codes cover 0–7 and 10–14 (with 4 for needs_human — login, CAPTCHA, or Allow/Deny card; never bypassed).
  3. Loopback Zero-Restart Workspace Hot-Switching (Default Safe Mode) & Opt-In --unrestricted-fs:
    • Keep your gateway and ngrok / Cloudflare tunnel running continuously while switching projects in milliseconds via the loopback-only control plane (GET/POST /local/workspace; any tunneled request returns 403, and switching while a task or tool call is active returns 409 Conflict):
      # Inspect current workspace root and filesystem mode
      gemlatch workspace get
      
      # Hot-switch to another project directory with zero restart
      gemlatch workspace set "/path/to/another-project"
      
      # Auto-switch workspace before dispatching a delegated task
      gemlatch delegate --workspace "/path/to/another-project" --new-chat --mention gemlatch --task-file task.md
      
    • For interactive Gemini Web chats across multiple repositories, explicitly opt into --unrestricted-fs (or allow_unrestricted_fs = true): cross-directory .mcp-trash/ snapshots and rollback_last continue to work while allowlist.toml and secret.key stay hard-blocked.
  4. Drop-In Delegation Rule & Single-Turn Dispatch Templates:

🛡️ Compliance & Account Safety: Why GemLatch Isn't a Reverse-Engineered Proxy

When developers hear "turn Gemini Web into a local Coding Agent or subagent," the first question is almost always: "Will this get my Google account banned?"

The short answer: GemLatch is NOT a reverse-engineered private API wrapper, NOT a cookie/token harvester, NOT a multi-account proxy pool, and NOT a DOM-injecting browser extension. It is built squarely on Google's official Custom MCP Apps (Connected Apps Platform / Developer Mode) and enforces strict compliance guardrails in code:

Dimension Gray-Market API Proxies / DOM Extensions GemLatch (Official Native MCP Architecture)
Protocol Layer Reverse-engineers undocumented Gemini private RPCs (e.g., batchexecute) or injects browser extensions to scrape/rewrite the DOM 100% Official Google Native Streamable HTTP MCP (implemented via the official rmcp SDK with standard readOnlyHint / destructiveHint annotations and native function calling)
Credentials & Cookies Extracts, caches, or replays Google cookies, SNlM0e, or OAuth tokens—frequently tripping anomaly detection Zero credential touch: the codebase never reads, extracts, stores, or forwards browser cookies, session tokens, or passwords
Account & Concurrency Model Multi-account rotation, shared token pools, or OpenAI-compatible resale proxies blasting concurrent requests Single user · serial human-paced tasks: uses your own signed-in Chrome profile; the local task bus strictly enforces one active task at a time (409 Conflict on overlap) to prevent request flooding
Human Verification & Approvals Attempts headless anti-detect spoofing, CAPTCHA bypasses, or silent permission auto-clicks Hard-coded human-in-the-loop red lines (exit code 4): no headless fingerprint spoofing; whenever Google shows a login wall, CAPTCHA/rate limit, or official Allow / Deny tool card, GemLatch never bypasses or auto-clicks it and hands control back to you in Chrome
Data Path Routes prompts/code through third-party proxy backends, risking both account bans and source leaks Pure local binary, zero third-party relay or telemetry: traffic goes directly between Google's official MCP client and your local machine over your own private HTTPS tunnel (ngrok / Cloudflare Tunnel)

Clear Boundary Between Both Modes

  1. Mode ① (Local Coding Agent — Zero Browser Automation, 100% Native Official Usage):
    • Zero CDP and zero browser control.
    • You simply register your local standards-compliant MCP server following Google's official Custom Connected Apps documentation and chat with @<AppName> manually in gemini.google.com. Every tool call and Allow / Deny card is driven natively by Google Gemini Web.
  2. Mode ② (Subagent Delegation --enable-delegate — Tool Calls Still 100% Official MCP):
    • All codebase reads, patches, verifications, and reports still run 100% over Google's official Streamable HTTP MCP protocol—zero private RPC calls.
    • Loopback-only Chrome CDP (hard-restricted to 127.0.0.1 / localhost in code) performs minimal local UI input assistance in your own signed-in Chrome tab—typing your task brief, checking the target mode/model, and submitting—replacing manual copy-paste while immediately pausing with needs_human (exit 4) for any login, CAPTCHA, or Allow / Deny card.

💡 Transparent Note: Mode ① is pure standard usage of Google's official Developer Mode / Custom MCP Apps. Mode ② adds local real-browser input assistance on top of official MCP; while it is engineered from the ground up to avoid every high-risk behavior behind account bans (private API reverse-engineering, cookie theft, concurrent pooling, headless spoofing, or bypassing human checks), platform policies remain governed by Google's Terms of Service—please use it strictly with your own personal account for normal development workflows.


Why GemLatch?

Trying to leverage Gemini Web quota previously meant either copy-pasting files back and forth from your IDE/agent (burning host context and time) or relying on fragile browser-extension DOM injection (UI updates break selectors, JSONL parsing silently fails, every tool call costs extra turns, stuck tasks can't be aborted cleanly, and external stdio servers often suffer from soft permission bypasses).

How GemLatch is engineered:

  • Closed-Loop Subagent Delegation: Combines a local task bus (get_pending_task / report_task_done) with a pure-Rust loopback Chrome CDP client so Gemini Web operates as an async worker subagent callable in one command — 0 host tokens while waiting, <= 3 KiB JSON report back (full report at report_path), --template, --acceptance gates, delegate-batch, --cross-review, fail-closed --ui-mode / --web-model gates, and --workspace zero-restart hot-switching.
  • 100% Official Protocol: Implements MCP Streamable HTTP (2025-11-25 and 2025-03-26) via rmcp, enabling native structured function calling, multi-step Tool Chaining, and Gemini's native Allow / Deny confirmation cards for mutating tools.
  • 8–11 Agent-Grade Composite Tools: Compresses 40+ granular file operations into 8 safe-by-default (up to 11 opt-in) high-density tools, cutting round-trips while staying within bounded context budgets (read-only output defaults to configurable 96 KiB; batch reads preserve complete lines and structured continuation ranges).
  • Hard Filesystem Sandbox, Atomic Patch & Rollback: Mandatory single --root by default, fs::canonicalize path validation, parent-traversal rejection, symlink-escape detection, and hard exclusion of .git/, .mcp-trash/, target/, and node_modules/. safe_patch preflights exact match counts in memory before touching disk, saves pre-write snapshots to .mcp-trash/, performs atomic temp-file renames with compensation on failure, optionally runs a read_only verifier in the same call, and supports one-click restoration via rollback_last.
  • Shell-Free Command Allowlist & Private Tunnel Isolation: scoped_exec spawns approved binaries directly via Command::new (no cmd /c, powershell, or sh), enforces an 18-second process timeout (kill_on_drop), and caps output to first 4 KiB + last 12 KiB. Constant-time comparison against a 43-char URL-safe base64 256-bit key (/mcp/<key>), 404 on unknown routes/keys, and 403 on /health, /abort, or /local/* whenever proxy/forwarding headers or non-loopback Host headers are present.

The Built-in Tools (8 by default, up to 11 opt-in)

On initialize, the server automatically injects SERVER_INSTRUCTIONS into the model context so you don't have to paste manual rules into every chat. The default safe mode registers the first 8 tools below; shell_exec appears only with allow_shell_exec = true or --enable-shell-exec; get_pending_task and report_task_done appear only with enable_delegate = true or --enable-delegate.

Tool Annotation Purpose & Guardrails
workspace_snapshot readOnlyHint: true Respects .gitignore (via ignore), returns bounded directory tree (depth=3, max_entries=500), scoped git status --short / git diff --stat, and WorkspaceLedger summary (reserving tail budget so recent edits/checks aren't lost).
code_outline readOnlyHint: true .rs: syn AST with syntax fallback. .ts/.tsx: pure Rust lexical scanner for top-level interface/type/enum/class/function, exported functions/components and class methods, with exact 1-based lines and no bodies. Skips .d.ts, dist/, node_modules/.
code_search readOnlyHint: true Embedded ripgrep engine (grep-searcher + ignore), skips binaries & target/, supports regex, optional glob, subpath, and line context (context defaults to 2 lines, max_hits to 60).
batch_read readOnlyHint: true Reads up to 8 file fragments with 1-based inclusive [start_line, end_line] ranges (L{n}: prefixes and total line count), default cap 96 KiB; truncates at complete lines with JSON continuation ranges for every unfinished file.
git_diff readOnlyHint: true Unified diffs for literal workspace paths, optional staged, base_ref, context_lines, subpath, max_bytes (default 96 KiB). Disables external diff/textconv; reports truncated file/hunk location and an untracked-file notice.
safe_patch destructiveHint: true Two-phase atomic multi-file patch: verifies every old_str occurrence count strictly matches expect (default 1) before writing anything → creates .mcp-trash/ snapshot → atomic rename → returns similar unified diff. Optional verify runs any read_only = true preset (e.g., "cargo_check", "ruff_check", "tsc_check", "go_vet", "git_readonly") in the same turn.
scoped_exec destructiveHint: true Executes a preset from allowlist.toml directly without a shell; rejects disallowed subcommands/metacharacters; 18s timeout. Ships with cargo_check, cargo_test, git_readonly; multi-language and writable presets are opt-in — see Configuration.
rollback_last destructiveHint: true Atomically restores the latest or specified snapshot_id from .mcp-trash/, including deleting files newly created in that snapshot (supports cross-directory rollback in unrestricted mode with protected-path checks).
shell_exec destructiveHint: true Opt-in (--enable-shell-exec). Unrestricted PowerShell (default)/CMD with subpath (cross-directory in unrestricted mode), 60s default/300s maximum timeout, UTF-8, process-tree termination, head/tail capture per stream and JSON results. Command, duration and exit code are logged locally; no OS sandbox or rollback.
get_pending_task readOnlyHint: true Opt-in (--enable-delegate). Lets Gemini Web fetch the active pending delegated task payload and constraints from the local task bus (read-only, zero approval cards).
report_task_done idempotentHint: true Opt-in (--enable-delegate). Submits structured completion summary, changed files, verification status, or blockers, waking up the blocking gemlatch delegate process immediately for the host agent.

Prerequisites

  • Rust Toolchain: Rust 1.96+ (Edition 2024; required only when building from source — prebuilt releases do not need Rust).
  • Public HTTPS Tunnel CLI: ngrok (recommended for free static domain & stability) or cloudflared installed and available in PATH (or placed in the repo root on Windows).
  • Gemini Web Account Requirements (per Google's Custom Connected Apps guidelines): see Unlock Gemini Web's Hidden Official MCP Mode above for the full list — in short, English UI + US region + personal account + Gemini Apps Activity enabled, plus access to Connected Apps / Developer Mode (gemini.google.com/devmode).
  • For Subagent Delegation Mode (optional): Your regular Chrome launched with loopback-only --remote-debugging-port=9222 and a signed-in Gemini Web tab.

Quick Start

1. Download a prebuilt release (unzip and run)

No Rust toolchain required. Open the Releases page, download the archive for your platform, and run it after extracting (each archive keeps a single same-named top-level directory so files don't scatter onto your desktop):

Platform Archive How to start
Windows (x86_64) gemlatch-<version>-windows-x86_64.zip After extracting, double-click start.bat (or run .\scripts\start.ps1 -Workspace "D:\path\to\your\project")
Linux (x86_64) gemlatch-<version>-linux-x86_64.tar.gz Extract, then ./gemlatch --root <project> --allowlist ./allowlist.toml --key-file ./secret.key
macOS (Apple Silicon) gemlatch-<version>-macos-aarch64.tar.gz Extract, then ./gemlatch ...

Verify integrity with the SHA256SUMS.txt published on the same Release. The Windows archive also ships a start.bat launcher for newcomers: it offers to reuse the last workspace or paste/drag a new project path, then invokes scripts\start.ps1 with -ExecutionPolicy Bypass so unsigned .ps1 files run despite Windows' default policy.

Portable note: scripts/start.ps1 uses cloudflared by default. On Windows run winget install Cloudflare.cloudflared, or drop cloudflared.exe into the extraction root. If you prefer ngrok, launch gemlatch directly and expose port 3006 with ngrok http 127.0.0.1:3006.


2. Build from source (optional)

Prefer to build it yourself, or need another platform / architecture:

git clone https://github.com/DicSeek/gemlatch.git
cd gemlatch
cargo build --release --locked

This produces target/release/gemlatch.exe (or target/release/gemlatch on Linux/macOS).


3A. Windows (One-Command PowerShell Scripts)

All Windows helper scripts live under scripts/ and store runtime state (.runtime/secret.key, .runtime/current-mcp-url.txt, logs, and PIDs) inside .runtime/ (gitignored).

Start gateway + Cloudflare Quick Tunnel:

# Default safe mode (8 tools)
.\scripts\start.ps1 -Workspace "D:\path\to\your\project"

# Enable subagent delegation mode (10 tools; add -EnableShellExec for 11)
.\scripts\start.ps1 -Workspace "D:\path\to\your\project" -EnableDelegate

Tip for strict networks / proxies: If UDP port 7844 (QUIC) is blocked or your proxy uses fake-IP DNS, switch to HTTP/2 or ensure argotunnel.com bypasses TUN/fake-IP:

.\scripts\start.ps1 -Workspace "D:\path\to\your\project" -TunnelProtocol http2

When startup succeeds:

  1. A 256-bit key is generated (or reused from .runtime/secret.key).
  2. cloudflared registers an HTTPS Quick Tunnel (https://<random>.trycloudflare.com).
  3. The script performs an actual public POST /mcp/<key> initialize check (2025-11-25) before printing success.
  4. The full private endpoint URL (https://<subdomain>.trycloudflare.com/mcp/<43-char-key>) is saved to .runtime/current-mcp-url.txt and copied to your clipboard.

Treat the complete MCP URL as a password. Anyone with that URL can access the exposed workspace tools (subject to Gemini's Allow/Deny prompt in your own browser, or directly via HTTP if leaked).

Other daily commands:

# Stop gateway and tunnel (removes current-mcp-url.txt, preserves secret.key)
.\scripts\stop.ps1

# Rotate the 256-bit key (invalidates the old URL immediately) and restart tunnel
.\scripts\rotate-key.ps1

# Read-only check of the public endpoint (never prints secret.key)
.\scripts\verify-public.ps1 -FullSmoke

3B. Linux / macOS / Manual CLI

The Rust server is cross-platform. You can run it directly on any OS:

# 1. Start the local MCP gateway (loopback-only; add --enable-delegate for subagent mode)
./target/release/gemlatch \
  --root /path/to/your/project \
  --allowlist ./allowlist.toml \
  --key-file ./secret.key \
  --host 127.0.0.1 \
  --port 3006 \
  --enable-delegate

Keep --allowlist outside --root: startup refuses an allowlist that resolves inside the exposed workspace. The example above already does this.

In a second terminal, expose port 3006 over HTTPS using ngrok (recommended for a free static domain) or cloudflared:

# Option 1: ngrok (recommended)
ngrok http 127.0.0.1:3006

# Option 2: Cloudflare Quick Tunnel
cloudflared tunnel --url http://127.0.0.1:3006 --no-autoupdate

Combine the allocated https://<your-domain> origin with the 43-character key inside ./secret.key:

https://<your-domain>/mcp/<43-char-key>

4. Connect in Gemini Web

Prerequisite: confirm the four hard requirements in Unlock Gemini Web's Hidden Official MCP Mode above first. The steps below are how you actually make the Developer Mode entry appear.

Step 1 · Set your Google account language to English (United States)

Open Google account language settings and set Preferred Language to English / United States. The preference propagates to Gemini Web; if the page still shows another language, reload it once.

Step 2 · Open Developer Mode from the Gemini sidebar

Go back to gemini.google.com, open the sidebar from the top-left menu, and click </> Developer Mode under the Preferences group. If the entry is missing, either the language from step 1 or the region requirement in Prerequisites is not satisfied yet.

Step 3 · Create a Custom MCP App

Inside Developer Mode, create a new Custom MCP App and fill in:

  • URL: the complete https://.../mcp/<key> endpoint (the contents of .runtime/current-mcp-url.txt)
  • Protocol: Streamable HTTP

Step 4 · Confirm the tools are discovered

After saving, the panel should list 8 tools by default (safe mode), 9 with --enable-shell-exec, 10 with --enable-delegate, or 11 with both enabled. A different count usually means the tunnel is not reachable, the key does not match, or the mode differs — run .\scripts\verify-public.ps1 -FullSmoke to diagnose.

Step 5 · Start chatting (or wire up your host agent below)

In chat, mention @<Your App Name> and ask Gemini to inspect your project with workspace_snapshot or code_outline. Mutating tools (safe_patch, scoped_exec, shell_exec, rollback_last) will show Gemini's Allow / Deny confirmation card before execution.


5. Wire Up Claude Code / Cursor / Antigravity (Subagent Delegation)

Once connected in Gemini Web and running with --enable-delegate (or enable_delegate = true), connect your host agent in 3 quick steps:

  1. Launch your signed-in Chrome with loopback debugging and probe the connection:
    chrome.exe --remote-debugging-port=9222
    gemlatch task probe-cdp --cdp-port 9222
    
  2. Install the quota-first delegation rule: Copy examples/delegation-rule.en.md (简体中文) into ~/.gemini/config/rules/ (Antigravity), CLAUDE.md (Claude Code), or .cursor/rules/ (Cursor), pointing it at examples/dispatch-delegate.ps1 (Windows) or examples/dispatch-delegate.sh (Linux/macOS), your @mention name, and optional --ui-mode / --web-model gates.
  3. Verify a single-command closed-loop dispatch (invoked automatically by the host agent during real tasks):
    # New delegated task (add --workspace to hot-switch projects, --ui-mode / --web-model for fail-closed gating)
    gemlatch delegate --task-file .gemlatch/task.md --mention gemlatch --new-chat --format json
    
    # Follow-up rework in the same Gemini Web chat (skips @ activation and re-reading)
    gemlatch delegate --task-file .gemlatch/review.md --continue --format json
    

For interactive cross-repository browsing/editing without delegation, you can also explicitly enable unrestricted filesystem mode:

gemlatch --unrestricted-fs --root /path/to/projects --allowlist ./allowlist.toml

See docs/delegate-guide.md and docs/cdp-findings.md for exit codes 0–7, 10–14, selectors.toml overrides, automatic URL writeback, and troubleshooting.


Configuration (allowlist.toml)

By default, gemlatch loads allowlist.toml from --allowlist <path> (or next to the executable). Startup fails closed if the resolved allowlist lies inside --root, so an AI model editing files inside the workspace can never modify its own command allowlist.

Presets in the shipped allowlist.toml — none of them can modify tracked files:

  • cargo_check (read_only = true, runs cargo check --message-format=short, no extra args allowed; valid verify target)
  • cargo_test (runs cargo test only, extra args restricted to ^[a-zA-Z0-9_:\-]+$; not a verify target because tests can write files)
  • git_readonly (read_only = true, restricted to read-only status, diff, log, branch subcommands and safe flags; injects --no-ext-diff --no-textconv on diff/log; valid verify target)

Multi-Language Preset Examples

GemLatch is not limited to Rust — swap in or merge any of these ready-to-use examples/ allowlists via --allowlist (kept outside --root):

Language / Use Case Example File Included Presets (read_only / writable)
Python examples/allowlist.python.toml ruff_check (read_only), mypy_check (read_only), pytest_run, git_readonly (read_only)
Node.js / TS / JS examples/allowlist.node.toml tsc_check (read_only), eslint_check (read_only), vitest_run, npm_test, git_readonly (read_only)
Go examples/allowlist.go.toml go_vet (read_only), go_test, git_readonly (read_only)
Rust / Git Writable examples/allowlist.writable.toml cargo_any (build/check/clippy/fmt/run/test), git_any (19 local subcommands)

Writable presets are not shipped in the default allowlist.toml. Copy them into your own allowlist.toml if you want them: they cannot be used as a verify target, are never snapshotted or rolled back, and only run when a model explicitly calls scoped_exec with that preset and you approve the Allow card.

Shell executables (cmd, powershell, pwsh, sh, bash, .bat, .cmd, .ps1, .sh, etc.) and shell metacharacters remain rejected in scoped_exec allowlist presets only, at startup and runtime. This does not restrict the separate shell_exec tool.

The top-level allow_shell_exec switch (default false) controls whether shell_exec is exposed: the shipped allowlist.toml keeps allow_shell_exec = false, so only 8 tools appear by default; set it to true or start with --enable-shell-exec to expose the 9th tool. The scoped_exec allowlist and shell_exec are independent: enabling shell_exec never widens the allowlist, and the allowlist cannot constrain shell_exec.


Output Configuration & New Tool Examples

Top-level settings in the TOML selected by --allowlist:

max_timeout_ms = 18000        # scoped_exec only; existing 18s hard cap unchanged
max_response_bytes = 98304    # optional; read-only default 96 KiB, adjustable up/down
allow_shell_exec = false      # default off; set true or use --enable-shell-exec to expose shell_exec
enable_delegate = false       # default off; set true or use --enable-delegate to expose local task bus & delegate tools
allow_unrestricted_fs = false # default off; set true or use --unrestricted-fs for cross-directory filesystem access

The byte setting applies to final workspace_snapshot, code_outline, code_search and batch_read responses; independent entry/hit/8 MiB file limits still apply. batch_read preserves complete lines and ends truncated output with [BATCH_READ_TRUNCATION] and JSON:

{"truncated":true,"max_bytes":98304,"resume":[{"path":"src/main.rs","last_output_line":420,"remaining_start_line":421,"remaining_end_line":900,"total_lines":900},{"path":"README.md","last_output_line":null,"remaining_start_line":1,"remaining_end_line":100,"total_lines":100}]}

Resume with each remaining range as start_line/end_line. Not-started files use last_output_line=null. A single oversized line is not partially returned: increase the configured limit. A budget too small for complete metadata returns an explicit error, never broken continuation JSON.

shell_exec

{"command":"cargo test --workspace","subpath":"backend","shell":"powershell","timeout_ms":120000}

command is required; subpath defaults to . and must be a workspace-relative directory without traversal or symlink escape. shell is powershell (default) or cmd. timeout_ms defaults to 60000, is capped at 300000, and rejects zero. Windows uses system PowerShell/CMD with UTF-8; elsewhere PowerShell requires pwsh and CMD is unsupported. Ordinary tools keep the 20s request guard; shell calls use their own timeout plus 5s cleanup grace.

Returns JSON exit_code (possibly null on termination), stdout, stderr, duration_ms, timed_out, cancelled, and per-stream truncation/total/omitted byte counts. Each stream retains the first 8 KiB and last 56 KiB (64 KiB raw bytes plus a small omission marker), preserving diagnostic tails and valid UTF-8 boundaries. Windows Job Objects / Unix process groups terminate the whole tree on timeout, cancellation or dropped calls; pipe draining shares the same deadline. Windows preserves a console for CMD encoding; the OS may create a console window if no parent console exists.

The last 10 command records are stored in .mcp-trash/state.json under recent_commands, including command/directory/shell/duration/exit/timeout/cancellation, and invalidate earlier verification status. Do not put secrets in command strings. This unrestricted tool can access files outside the workspace, change configuration or use the network. It has neither snapshots nor an OS sandbox; keeping the allowlist outside the workspace does not restrict it.

git_diff

{"paths":["src/main.rs"],"staged":false,"base_ref":"HEAD","context_lines":3,"max_bytes":98304}

Omitted/empty paths means the entire current workspace. Paths are literal, workspace-relative and may name deleted tracked files. staged=true compares the index; base_ref is safely resolved to a commit first. context_lines defaults to 3 (maximum 1000). max_bytes inherits max_response_bytes (96 KiB), with a per-call range of 1024..16777216. External diff/textconv, color and rename detection are disabled; internal/generated directories are excluded. [GIT_DIFF_TRUNCATION] JSON records the file, last diff line/hunk and remaining bytes: retry that path with a larger budget. Untracked files are not in Git diffs; the output points to workspace_snapshot and batch_read.

TypeScript Outline

.ts/.tsx use a pure Rust lexical scanner with no tree-sitter/C build dependency. It skips comments, strings, template literals, regular expressions and JSX while retaining the compact file: Lline signature | ... format. It is a structural outline, not a TypeScript type checker: namespaces, interface members, destructured bindings and arbitrary HOC aliases are not expanded. Regex/division and JSX/generic ambiguity uses heuristics; exotic syntax may be omitted, and template/JSX nesting is capped at 64. Lines point to declaration keywords (method names for class methods). Existing Rust AST/fallback behavior is unchanged.


Security & Operational Notes

  1. Trust boundary for cargo check / cargo test / linters: read_only = true in allowlist.toml is an operator authorization flag for Verify-on-Write, not an OS container. Running cargo check, cargo test, or other build/lint tools can still execute build.rs or project code in the target repository. Only point --root at trusted repositories. If you opt into the writable presets from examples/, note that cargo run executes your program and git_any can rewrite history, and neither is snapshotted.
  2. Tunnel & Local Control Plane Isolation:
    • The server refuses non-loopback --host values.
    • /health, POST /abort, and /local/* (task bus & workspace hot-switch endpoints) check ConnectInfo loopback IP, local Host (127.0.0.1 / localhost), and reject requests containing CF-Connecting-IP, X-Forwarded-For, X-Real-IP, Forwarded, or Origin (even if empty).
    • If you run a reverse proxy in front of 127.0.0.1:3006 that strips forwarding headers, restrict the proxy route strictly to /mcp/* so local control endpoints are never exposed.
  3. Loopback CDP & Human-in-the-Loop Guardrails: gemlatch delegate's CDP client strictly rejects any non-127.0.0.1/localhost target and never bypasses Google login, CAPTCHA/human verification, or Allow/Deny confirmation cards — it exits with code 4 (needs_human) so you stay in full control in Chrome.
  4. Quick Tunnel Rate Limits & Fixed URLs:
    • Free Cloudflare Quick Tunnels assign a new *.trycloudflare.com domain on each restart and enforce creation rate limits (HTTP 429) if restarted repeatedly in a short window.
    • Prefer ngrok's free static domain, or a Cloudflare Named Tunnel on your own domain (https://mcp.yourdomain.com/mcp/<key>), for a permanent URL.
    • Note: cloudflared tunnel --url (Quick Tunnel) fails if ~/.cloudflared/config.yml or config.yaml exists on your machine; scripts/start.ps1 detects this and aborts safely without modifying your config.
  5. Control-File Hard Protection: Startup fails if --allowlist resolves inside --root, because safe_patch could otherwise rewrite the allowlist and grant itself new commands (scripts/start.ps1 automatically copies the allowlist to the system temp directory $env:TEMP\gemlatch-allowlist.toml whenever the workspace is the repository itself). Even in --unrestricted-fs mode, allowlist.toml and secret.key are always hard-blocked from reads, searches, and writes.
  6. Target Workspace .gitignore: Add .mcp-trash/ to your target repository's .gitignore so snapshots and state.json stay local.

Testing & Verification

Run all acceptance checks (96 KiB/configured budgets and continuation ranges; filtered/staged/base-ref Git diffs and path safety; TS/TSX symbol lines; shell UTF-8, head/tail capture, process-tree timeout/cancellation; existing patch/rollback/guard regressions):

cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace

The tests that exercise real child processes compile tests/support/process_fixture.rs with rustc at runtime, so rustc must be on PATH (it is, in a normal rustup install).

When the gateway + tunnel are running on Windows, run the 14-item end-to-end verification suite against a target workspace:

.\scripts\e2e-verify.ps1 -Workspace "D:\path\to\your\project"

There is also a standalone Python local HTTP smoke script in tests/http_smoke.py for testing a locally running instance without a tunnel.


License

MIT — see LICENSE.

Jelajahi proyek terkait

Memuat…