DicSeek/gemlatch
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 pengembanganYang 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
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.).
| Mode 1: Gemini Web as Local Coding Agent (15s) | Mode 2: Split-Screen Subagent Delegation — 0 Tokens While Waiting (25s) |
|---|---|
![]() |
![]() |
- 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
0host tokens while waiting and receiving only a compact<= 3 KiBJSON report (with full details persisted toreport_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
allowlisttemplates. - 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 viagemlatch 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
--rootsandbox;shell_execand delegation tools are hidden and direct calls are rejected (-32601). Enable higher-privilege modes explicitly (/healthreflectstools,shell_exec,delegate,fs_mode, andunrestricted_fs):
--enable-shell-exec(orallow_shell_exec = true): exposes the 9th toolshell_exec(unrestricted OS shell, no rollback; approve each call).--enable-delegate(orenable_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 viagemlatch delegate.--unrestricted-fs(orallow_unrestricted_fs = true): enables unrestricted filesystem mode so all 8 native tools andshell_execaccept absolute/cross-directory paths (including cross-directory snapshots & rollback), while still hard-blocking reads, searches, or writes toallowlist.tomlandsecret.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:
- The UI language must be set to English. The entry is hidden under Simplified Chinese and other non-English interfaces.
- Your account and network environment must be in the US region, and you must be 18 or older.
- Personal Google accounts only. Google Workspace business and education accounts are not supported yet.
- 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
- 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.
- 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--continueskips@).
🚀 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 & 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/<id> 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://<domain>/mcp/<256-bit-key>"| TUN
TUN -->|"127.0.0.1:3006 (loopback only)"| GW
GW -->|"3. report_task_done wakes bus<br/><= 3 KiB JSON report + exit code 0–7, 10–14"| AG
Key Capabilities Across Both Modes
- 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 viaworkspace_snapshot/code_outline/code_search/batch_read(allreadOnlyHint: true— zero browser approval popups), and returns a condensed briefing viareport_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_patchcalls (with optionalverifyagainst anyread_only = truepreset) and reports back. For rework, the host passes--continueto reuse the same Gemini Web chat (skipping@activation and avoiding re-reading files).
- Stage 1 (Read-Only Recon): Host agent dispatches a pure read-only brief. Gemini Web fetches it via
- Fail-Closed
--ui-mode/--web-modelGating, 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 code13(gate_mismatch) so quota is never wasted on the wrong mode or model. - Supports
--template recon|build|test|review, server-side--acceptanceverification loops,delegate-batch --batch-filesequential queues, and second-session--cross-review(--fail-on-review-blockerexits14). Standardized exit codes cover0–7and10–14(with4forneeds_human— login, CAPTCHA, or Allow/Deny card; never bypassed).
- Configurable via CLI flags or
- 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 returns403, and switching while a task or tool call is active returns409 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(orallow_unrestricted_fs = true): cross-directory.mcp-trash/snapshots androllback_lastcontinue to work whileallowlist.tomlandsecret.keystay hard-blocked.
- Keep your gateway and ngrok / Cloudflare tunnel running continuously while switching projects in milliseconds via the loopback-only control plane (
- Drop-In Delegation Rule & Single-Turn Dispatch Templates:
- Copy
examples/delegation-rule.en.md(简体中文) into your host agent's rules (~/.gemini/config/rules/for Antigravity,CLAUDE.mdfor Claude Code, or.cursor/rules/for Cursor) and pair it withexamples/dispatch-delegate.ps1(Windows) orexamples/dispatch-delegate.sh(Linux/macOS, supporting-AutoSwitchWorkspace/--auto-switch-workspace). - See docs/delegate-guide.md and docs/cdp-findings.md for the complete reference and troubleshooting guide.
- Copy
🛡️ 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
- 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 ingemini.google.com. Every tool call and Allow / Deny card is driven natively by Google Gemini Web.
- 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/localhostin 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 withneeds_human(exit4) 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 —0host tokens while waiting,<= 3 KiBJSON report back (full report atreport_path),--template,--acceptancegates,delegate-batch,--cross-review, fail-closed--ui-mode/--web-modelgates, and--workspacezero-restart hot-switching. - 100% Official Protocol: Implements MCP Streamable HTTP (
2025-11-25and2025-03-26) viarmcp, 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
--rootby default,fs::canonicalizepath validation, parent-traversal rejection, symlink-escape detection, and hard exclusion of.git/,.mcp-trash/,target/, andnode_modules/.safe_patchpreflights 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 aread_onlyverifier in the same call, and supports one-click restoration viarollback_last. - Shell-Free Command Allowlist & Private Tunnel Isolation:
scoped_execspawns approved binaries directly viaCommand::new(nocmd /c,powershell, orsh), enforces an 18-second process timeout (kill_on_drop), and caps output to first4 KiB+ last12 KiB. Constant-time comparison against a 43-char URL-safe base64 256-bit key (/mcp/<key>),404on unknown routes/keys, and403on/health,/abort, or/local/*whenever proxy/forwarding headers or non-loopbackHostheaders 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
cloudflaredinstalled and available inPATH(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=9222and 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.ps1usescloudflaredby default. On Windows runwinget install Cloudflare.cloudflared, or dropcloudflared.exeinto the extraction root. If you prefer ngrok, launchgemlatchdirectly and expose port3006withngrok 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 ensureargotunnel.combypasses TUN/fake-IP:.\scripts\start.ps1 -Workspace "D:\path\to\your\project" -TunnelProtocol http2
When startup succeeds:
- A 256-bit key is generated (or reused from
.runtime/secret.key). cloudflaredregisters an HTTPS Quick Tunnel (https://<random>.trycloudflare.com).- The script performs an actual public
POST /mcp/<key>initializecheck (2025-11-25) before printing success. - The full private endpoint URL (
https://<subdomain>.trycloudflare.com/mcp/<43-char-key>) is saved to.runtime/current-mcp-url.txtand 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
--allowlistoutside--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:
- 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 - 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 atexamples/dispatch-delegate.ps1(Windows) orexamples/dispatch-delegate.sh(Linux/macOS), your@mentionname, and optional--ui-mode/--web-modelgates. - 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, runscargo check --message-format=short, no extra args allowed; validverifytarget)cargo_test(runscargo testonly, extra args restricted to^[a-zA-Z0-9_:\-]+$; not averifytarget because tests can write files)git_readonly(read_only = true, restricted to read-onlystatus,diff,log,branchsubcommands and safe flags; injects--no-ext-diff --no-textconvondiff/log; validverifytarget)
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
- Trust boundary for
cargo check/cargo test/ linters:read_only = trueinallowlist.tomlis an operator authorization flag for Verify-on-Write, not an OS container. Runningcargo check,cargo test, or other build/lint tools can still executebuild.rsor project code in the target repository. Only point--rootat trusted repositories. If you opt into the writable presets fromexamples/, note thatcargo runexecutes your program andgit_anycan rewrite history, and neither is snapshotted. - Tunnel & Local Control Plane Isolation:
- The server refuses non-loopback
--hostvalues. /health,POST /abort, and/local/*(task bus & workspace hot-switch endpoints) checkConnectInfoloopback IP, localHost(127.0.0.1/localhost), and reject requests containingCF-Connecting-IP,X-Forwarded-For,X-Real-IP,Forwarded, orOrigin(even if empty).- If you run a reverse proxy in front of
127.0.0.1:3006that strips forwarding headers, restrict the proxy route strictly to/mcp/*so local control endpoints are never exposed.
- The server refuses non-loopback
- Loopback CDP & Human-in-the-Loop Guardrails:
gemlatch delegate's CDP client strictly rejects any non-127.0.0.1/localhosttarget and never bypasses Google login, CAPTCHA/human verification, or Allow/Deny confirmation cards — it exits with code4(needs_human) so you stay in full control in Chrome. - Quick Tunnel Rate Limits & Fixed URLs:
- Free Cloudflare Quick Tunnels assign a new
*.trycloudflare.comdomain 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.ymlorconfig.yamlexists on your machine;scripts/start.ps1detects this and aborts safely without modifying your config.
- Free Cloudflare Quick Tunnels assign a new
- Control-File Hard Protection: Startup fails if
--allowlistresolves inside--root, becausesafe_patchcould otherwise rewrite the allowlist and grant itself new commands (scripts/start.ps1automatically copies the allowlist to the system temp directory$env:TEMP\gemlatch-allowlist.tomlwhenever the workspace is the repository itself). Even in--unrestricted-fsmode,allowlist.tomlandsecret.keyare always hard-blocked from reads, searches, and writes. - Target Workspace
.gitignore: Add.mcp-trash/to your target repository's.gitignoreso snapshots andstate.jsonstay 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.rswithrustcat runtime, sorustcmust be onPATH(it is, in a normalrustupinstall).
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…

