AG
Gemini & Antigravity v2.6 Agentic Engineering Guide
Antigravity Architecture Swarm + SDK Verified: 2026-11

Antigravity 2.6 + Unified Google GenAI SDK: Enterprise Heterogeneous Swarm Orchestration in Production

Which model powers the Antigravity CLI swarm (answered: none — swarm is an orchestration and context-isolation mechanism), how to declare a Coordinator-Worker-Verifier topology with Gemini 4 Carbon / Neon / Hydrogen via swarm.yaml + Markdown briefs, and a production-grade Google GenAI SDK boilerplate: exponential-backoff retries, token budget alarms, strict structured output, OpenTelemetry tracing, and prompt-injection defense.

Author: AGY Agentic Architecture Group • Google GenAI & Antigravity 2.6 Engineering Spec

Unified GenAI Production Client (Python)

examples/genai_production_client.py

"""
Unified Google GenAI Production Client
Target runtime: Python 3.12+ / google-genai v1.x / Antigravity 2.6 runtime
Safety: exponential backoff, token budget guard, strict schema
validation, OpenTelemetry spans, prompt-injection sanitization.
"""
import os, re, json, time, random
from dataclasses import dataclass, field
from google import genai
from google.genai import types

try:
    from opentelemetry import trace
    TRACER = trace.get_tracer("agy.swarm")
except ImportError:                      # OTel is optional in dev
    class _Null:
        def start_as_current_span(self, *a, **k):
            class _S:
                def __enter__(self): return self
                def __exit__(self, *a): return False
                def set_attribute(self, *a): pass
            return _S()
    TRACER = _Null()

# Heuristics for instruction smuggling inside untrusted content
_INJECTION_PATTERNS = [
    r"ignore (all|any|previous|prior) (instructions|rules)",
    r"disregard (the )?(above|previous|system)",
    r"you are now (a|an|the)",
    r"reveal (your )?(system prompt|instructions|rules)",
    r"</?\s*(system|assistant)\s*>",
]

def sanitize_untrusted(text: str) -> str:
    """Neutralize prompt-injection payloads inside tool/file output."""
    fenced = re.sub("|".join(_INJECTION_PATTERNS), "[filtered]", text, flags=re.I)
    return (f"<<<UNTRUSTED\n{fenced}\nUNTRUSTED>>>")

@dataclass
class TokenBudget:
    limit: int
    warn_ratio: float = 0.8
    spent: int = 0
    alerts: list = field(default_factory=list)

    def charge(self, usage, role: str = "worker"):
        self.spent += (usage.total_tokens or 0)
        ratio = self.spent / self.limit
        if ratio >= 1.0:
            raise RuntimeError(f"[budget] HARD STOP {role}: {self.spent}/{self.limit}")
        if ratio >= self.warn_ratio:
            self.alerts.append(f"[budget] WARN {role}: {ratio:.0%} of {self.limit}")
            print(*self.alerts[-1:], sep="\n")

class ProductionGenAIClient:
    def __init__(self, model="gemini-4-neon", budget_limit=2_000_000):
        self.client = genai.Client()          # reads GEMINI_API_KEY
        self.model = model
        self.budget = TokenBudget(limit=budget_limit)

    def generate(self, prompt: str, schema: dict | None = None,
                 untrusted: str | None = None, timeout_s: float = 120.0):
        payload = prompt + ("\n" + sanitize_untrusted(untrusted) if untrusted else "")
        delays = [0.5, 1, 2, 4]               # exponential backoff ladder
        for attempt, delay in enumerate([0, *delays], start=1):
            time.sleep(delay + random.uniform(0, 0.25))  # full jitter
            with TRACER.start_as_current_span("genai.generate") as span:
                span.set_attribute("genai.model", self.model)
                span.set_attribute("genai.attempt", attempt)
                try:
                    resp = self.client.models.generate_content(
                        model=self.model,
                        contents=payload,
                        config=types.GenerateContentConfig(
                            request_timeout=min(timeout_s, 60),
                            response_mime_type="application/json" if schema else None,
                        ),
                    )
                except Exception as err:
                    span.record_exception(err)
                    if attempt > len(delays):
                        raise
                    continue
                self.budget.charge(resp.usage_metadata)
                if schema:
                    return self._validate(resp.text, schema)
                return resp.text

    @staticmethod
    def _validate(raw: str, schema: dict):
        data = json.loads(raw)                # strict parse — fail fast
        for key, kind in schema.items():      # strict shape check
            value = data.get(key)
            if value is None or not isinstance(value, eval(kind)):
                raise ValueError(f"[schema] field '{key}' expected {kind}")
        return data

# ── Swarm role routing (see swarm topology in the article) ──────────────
WORKER = ProductionGenAIClient(model="gemini-4-neon", budget_limit=1_500_000)
result = WORKER.generate(
    prompt="Summarize failing tests and propose minimal fixes.",
    schema={"fixes": "list", "confidence": "float"},
    untrusted=open("ci_output.log").read(),   # CI log = untrusted input
)
print(json.dumps(result, indent=2))

1. First, the Question Everyone Asks: Which Model Does the Antigravity CLI Swarm Use?

The single most-searched swarm query hitting this site — “antigravity cli 的swarm的模型是哪个” (which model does the Antigravity CLI’s swarm use?) — has a precise answer: the swarm is not one model, it is a multi-agent orchestration and context-isolation mechanism.

In the Antigravity model, “Swarm” denotes a set of conventions: one coordinator owns the overall goal, shards the work, and dispatches independent briefs to specialized workers; every worker runs inside its own workspace under code and command isolation; a verifier checks the resulting diffs. The model is not a global swarm switch — it is declared per role in orchestration config, which is exactly why “which model does the swarm use” has no single answer.

Two clarifications before the internet’s phantom commands mislead you:

  1. There is no agy swarm config get / agy swarm status --json. The authoritative command set is whatever agy --help and the agy CLI 2.6 reference document (sync / doctor / init / run / test).
  2. Model routing lives in the orchestration layer, not in a global default: the .agents/swarm.yaml manifest declares models and tool allowlists per role, and each worker gets a Markdown brief that locks its task boundary (§2.2).

The heterogeneous routing we recommend and use throughout this guide (our production recommendation, not a CLI built-in default):

RoleRecommended modelWhy
CoordinatorGemini 4 CarbonTerminal review authority: architecture verdicts, security sign-off (SEC-bench Pro 94.2% — see the Carbon & Argon handbook)
WorkersGemini 4 NeonParallel code generation at Flash-tier price and throughput for the high-frequency implementation turns (architecture and caching economics in the Neon deep-dive)
VerifiersGemini 4 HydrogenSyntax/type/invariant checks on every diff at 232 tok/s nominal and $0.40/1M output — cheap enough to run on every save
FallbackGemini 4 ArgonLong-horizon reasoning when a brief exceeds Neon’s planning depth or a worker deadlocks

Everything below is how to run this topology in production without setting money on fire.

💡 Production infrastructure: decouple persistent swarms from developer machines

For coordinators, workers, verifiers, or SDK services that must stay online 24/7, deploy them on dedicated cloud infrastructure so laptop sleep, network changes, and local resource contention cannot interrupt a run. Choose DigitalOcean Droplets for fixed hosts and network control, or App Platform for managed builds and releases. New DigitalOcean users can receive $200 in developer credit, valid for 60 days—enough to benchmark a single-node deployment before committing to a multi-node cluster.

Sponsored link; offer terms are controlled by the provider. Independently assess region, bandwidth, data residency, secret management, and disaster recovery before production rollout.


2. Heterogeneous Swarm Topology: Coordinator + Workers + Verifiers

2.1 Why heterogeneous beats monolithic swarms

A swarm of identical frontier models is the most expensive way to produce average code: every unit review pays flagship rates, and every syntax check queues behind deep-thinking tokens. Heterogeneous routing matches model capability to task altitude — the economics compound exactly like the caching math in the Neon guide: a worker that costs 14% of the coordinator should handle ~90% of the turns.

flowchart TB
    Dev["Developer<br/>submit coordinator brief"] --> Coord["COORDINATOR<br/>Gemini 4 Carbon<br/>plan review · final merge authority"]
    Coord -->|"task shards"| W1["WORKER 1<br/>Gemini 4 Neon"]
    Coord -->|"task shards"| W2["WORKER 2<br/>Gemini 4 Neon"]
    Coord -->|"task shards"| W3["WORKER N<br/>Gemini 4 Neon"]
    W1 & W2 & W3 -->|"diffs"| V1["VERIFIER POOL<br/>Gemini 4 Hydrogen<br/>syntax · types · invariants"]
    V1 -->|"green diffs"| Coord
    V1 -->|"rejects"| W2
    Coord -->|"merged result"| Dev
    style Coord fill:#0c2a4d,stroke:#38bdf8,stroke-width:2px
    style V1 fill:#0d3320,stroke:#34d399

2.2 Declaring the swarm: Architecture Blueprint, role briefs, and workspace isolation

In enterprise production deployments, we recommend defining swarm governance under .agents/: a conceptual architecture blueprint (.agents/swarm.yaml) explicitly specifies team preferences for roles, models, Thinking Levels, tool allowlists, and boundaries, alongside per-worker Markdown briefs (.agents/briefs/<agent-id>.md) that define immutable task boundaries and definitions of done:

# .agents/swarm.yaml — heterogeneous orchestration manifest (our recommended routing)
name: auth-migration
isolation: workspace        # every worker's file & command operations stay inside its workspace
agents:
  - id: coordinator
    role: coordinator
    model: gemini-4-carbon
    thinkingLevel: high
    authority: [plan-approve, merge, escalate]   # permission constraint: only the coordinator merges
    brief: briefs/coordinator.md

  - id: worker-frontend
    role: worker
    model: gemini-4-neon
    thinkingLevel: medium
    workspace: .swarm/w-frontend          # must be relative (absolute paths error out)
    allowedTools: [read_file, write_file, run_tests]   # tool allowlist
    brief: briefs/worker-frontend.md
    maxTurns: 24

  - id: worker-backend
    role: worker
    model: gemini-4-neon
    thinkingLevel: medium
    workspace: .swarm/w-backend
    allowedTools: [read_file, write_file, run_tests, git_diff]
    brief: briefs/worker-backend.md
    maxTurns: 24

  - id: verifier
    role: verifier
    model: gemini-4-hydrogen
    thinkingLevel: low
    allowedTools: [read_file, run_tests, typecheck]   # verifiers get no write access
    brief: briefs/verifier.md
    veto: true                             # one-vote veto on any diff that fails checks

Each brief is a plain Markdown file — boundary, constraints, and completion criteria written out item by item; the coordinator shards and dispatches against them:

<!-- .agents/briefs/worker-frontend.md -->
# Brief: worker-frontend

## Objective
The frontend half of migrating auth middleware from JWT to OAuth 2.1.

## Boundary (hard constraints)
- Operate only on files inside this workspace (.swarm/w-frontend)
- Do not touch backend routes or the database schema
- Refuse any command outside the allowedTools allowlist

## Definition of done
- `npm test` fully green
- Passes the verifier's type and invariant checks
- Report progress in the task-list after each sub-task

Handing the swarm a task = writing the overall goal into the coordinator’s brief and committing it; watch progress with two real tools: agy sync --surface ide --follow (cross-surface session roaming, see the command reference) and the task-list.md artifact inside each workspace.

workspace isolation is not cosmetic. Each worker’s file operations are jailed to .swarm/<agent-id>/ — a frontend worker physically cannot rewrite backend routes. Workers exchange results only through the coordinator, which eliminates the two classic swarm failure modes: merge-conflict stampedes and responsibility smearing.

2.3 Brief lifecycle: sequence of one task end-to-end

Developer          Coordinator(Carbon)      Worker(Neon)        Verifier(Hydrogen)
    │                      │                     │                     │
    ├── submit brief ─────>│                     │                     │
    │                      ├─ plan + shard ──────┼─────────────────────┤
    │                      │                     ├── implement ───────>│
    │                      │                     │   (workspace-jail) ├─ syntax+types
    │                      │                     │                     ├── reject ──> Worker (retry)
    │                      │                     │<── green diff ──────┤
    │                      ├<─ candidate diff ───┤                     │
    │                      ├─ final review ──────┼─────────────────────┤
    │<── merged result ────┤                     │                     │
    │    (audit trail: OTel spans for every hop, per-agent token ledger)│

The economic point of this sequence is the cost shape, not any specific number: the Carbon gate only runs on verifier-green diffs, so flagship pricing applies solely to terminal review; the overwhelming majority of implementation and verification turns settle at Neon and Hydrogen price points — swarm cost per PR tracks worker economics, not flagship economics. There is no universal per-PR figure; measure your own with the §3.4 OTel instrumentation (evaluation methodology in Neon guide §2.3).


3. Enterprise SDK Boilerplate: the Unified google-genai Client

Swarm roles are only as trustworthy as the client code beneath them. The artifact box at the top of this page contains the complete production module our teams deploy; the five concerns it encodes:

3.1 Timeout + exponential backoff with full jitter

delays = [0.5, 1, 2, 4]                       # ladder caps at 4 retries
time.sleep(delay + random.uniform(0, 0.25))   # jitter prevents sync stampedes

Retries wrap only the transport call, never side effects; the per-request timeout (request_timeout) is enforced separately from the total attempt budget so one hung socket can’t eat a worker’s turn allocation.

3.2 Token budget guard with alarm thresholds

Every role carries a TokenBudget — warn at 80%, hard-stop at 100% (RuntimeError). In swarm mode the coordinator charges all agents against one budget, so a runaway retry loop in worker-backend trips the alarm before it multiplies across siblings. Alerts fan out to the standard OTel genai.budget.* attributes — wire them to PagerDuty like any other resource alarm.

3.3 Strict structured-output validation

response_mime_type="application/json" gets you model-side schema discipline; the client then does its own shape check (_validate) so a malformed confidence: "high" string can’t leak downstream as a float. Fail-fast + retry beats lenient parsing in agent pipelines — one poisoned object poisons every downstream decision.

3.4 OpenTelemetry observability injection

Each generate call opens a genai.generate span carrying genai.model, genai.attempt, token usage, and budget ratio. With agy sync --surface ide the same trace IDs light up the IDE execution tree — terminal, IDE, and dashboards tell one story. Per-PR cost, cache hit ratio, and verifier reject rate all aggregate straight out of these spans, which is precisely the measurement harness behind the §2.3 cost argument.

3.5 Prompt-injection defense

Workers ingest untrusted text constantly — CI logs, issue bodies, dependency READMEs. The sanitize_untrusted() helper does two things: fence untrusted blocks inside <<<UNTRUSTED ... UNTRUSTED>>> delimiters, and neutralize known override patterns (“ignore previous instructions”, fake </system> tags, persona rewrites). Combined with workspace jail + allowedTools allowlists, injection becomes a contained nuisance instead of a lateral-movement vector.


4. Cross-Platform Customizations & Rules: the Pitfall Library

Antigravity customization files (global ~/.gemini/config/rules/*.md or GEMINI.md, workspace .agents/rules/*.md, skills in .agents/skills/*/SKILL.md) behave identically across platforms only if you avoid these traps:

4.1 Path and permission differences

ConcernWindows (PowerShell)WSL (Ubuntu)macOS
Global config root%USERPROFILE%\.gemini\config\~/.gemini/config/~/.gemini/config/ (symlink from ~/.config ok)
Path separator in rulesUse / — agy normalizes//
workspace field in swarm.yamlAlways relative (/.swarm/w-api breaks)relativerelative
Symlinked skill pluginsRequires Developer Mode or mklinkNativeNative
Lock files%USERPROFILE%\.gemini\.locks~/.gemini/.lockssame; beware Dropbox/iCloud sync stalls .locks
PermissionsACLs: grant the user, never Everyonechmod 600 on auth.jsonchmod 600; Gatekeeper may quarantine downloaded plugins

The three most frequent support tickets, with fixes:

  1. Rules silently not loading on Windows. Cause: GEMINI.md saved as GEMINI.md.txt by Notepad, or saved with a UTF-8 BOM that breaks frontmatter parsing. Fix: Set-Content -Encoding utf8NoBOM, verify with agy doctor --verbose.
  2. WSL sees a different ~/.gemini than Windows. They are separate filesystems (§3 of the RU install guide). Keep one source of truth: either run everything inside WSL, or sync explicitly — never edit both.
  3. macOS cloud-sync corruption. iCloud Drive syncing ~/.gemini evicts files to cloud placeholders; auth.json reads as empty mid-session. Exclude the directory: brctl exclude ~/Library/Mobile Documents/... or move config out of synced paths.

4.2 MCP extension configuration standards

MCP servers are declared per-workspace under mcpDirectory (~/.gemini/antigravity/mcp by default):

{
  "mcpServers": {
    "repo-db": {
      "command": "npx",
      "args": ["-y", "@mcp/postgres", "--read-only"],
      "env": { "DATABASE_URL": "${MCP_DB_URL}" },
      "scope": "workspace",
      "capabilities": ["resources.read", "tools.query"]
    }
  }
}

Rules that keep MCP swarms healthy:

  • No circular dependencies. An MCP server must never launch agy (or another MCP server that does). Server A → CLI → Server A = recursive session spawn. Keep the MCP layer strictly leaf; orchestration belongs to the swarm coordinator only.
  • Least-privilege capabilities. Declare capabilities explicitly and match them to the consumer: verifiers need resources.read + tools.typecheck; only the coordinator gets tools.git.merge. A worker with database write access is a prompt-injection amplifier.
  • Pin versions, fail loudly. npx -y unpinned means your CI drifts nightly. Pin exact versions and let agy doctor --json gate the pipeline on MCP health.
  • Env vars over secrets in files. ${MCP_DB_URL} indirection keeps credentials out of the orchestration manifest (which lands in git) and in the platform secret store.

5. Production Rollout Checklist

  1. Pin the role routing (coordinator=carbon, worker=neon, verifier=hydrogen) in the .agents/swarm.yaml manifest — don’t rely on scaffold defaults surviving upgrades.
  2. Give every worker a workspace jail and an allowedTools allowlist before the first brief.
  3. Ship the artifact-box client (retry / budget / schema / OTel / injection defense) as your single import path to the GenAI SDK — no ad-hoc generate_content calls in feature code.
  4. Alarm on budget ratio ≥ 80% and verifier reject-rate > 30% (the latter means your briefs are underspecified).
  5. Exclude ~/.gemini from cloud sync, chmod 600 auth.json, and run agy doctor --json as a CI preflight on all three platforms.

Related: agy CLI 2.6 command reference · Customizations, Skills & Rules · Gemini 4 Neon deep-dive · Model Lab calculator