WikifitaGitHub live67e8de5
outro · sdk-test/sdk-test-integrations

Integration Points — DeepSeek, Heartbeat, Gemma 4, and Python SDK

How external models (DeepSeek V4, Gemma 4 local), the Heartbeat Protocol, and the Python SDK connect to form the complete Antigravity ecosystem

Baixar raw

Integration Points — DeepSeek, Heartbeat, Gemma 4, and Python SDK

Integration Map

graph TB
    subgraph "JETSKY Core"
        Agy["agy CLI"]
        Keychain["macOS Keychain"]
        SDK["google.antigravity"]
    end

    subgraph "External Models"
        DS["DeepSeek V4<br/>api.deepseek.com"]
        Gemma["Gemma 4 Local<br/>MLX + MTP Drafter"]
        Ollama["Ollama<br/>Local Models"]
    end

    subgraph "Protocol Layer"
        HB["Heartbeat Protocol<br/>Proto-Unicode Sequences"]
        Auth["OAuth2 Auth Chain"]
        Custom["CustomModelInfoOverride"]
    end

    Agy -->|passive refresh| Keychain
    SDK -->|RFC-001: keychain read| Keychain
    HB -->|agy --print| Agy
    Agy -->|TrySilentAuth| Auth
    Auth --> Keychain

    SDK --> Custom
    Custom -->|OpenAI-compat| DS
    Custom -->|http://localhost:8080/v1| Gemma
    Custom -->|http://localhost:11434| Ollama

DeepSeek V4 Integration

Discovery

DeepSeek V4 credentials were found in the Hermes Agent state-snapshot at /Users/alefita/.hermes/state-snapshots/20260611-135706-pre-update/.

Credentials

ParameterValue
API Keysk-REDACTED
Base URLhttps://api.deepseek.com/v1
Modeldeepseek-v4-flash
ProtocolOpenAI Chat Completions (compatible)
SourceHermes Agent .env and auth.json

Performance Profile

From Hermes Agent logs (2026-06-04):

23:05:11 INFO OpenAI client created ... provider=deepseek base_url=https://api.deepseek.com/v1 model=deepseek-v4-flash
23:07:30 INFO API call #1: model=deepseek-v4-flash provider=deepseek in=18619 out=135 total=18754 latency=3.1s
23:07:30 INFO Turn ended: reason=text_response(finish_reason=stop) ... session=20260604_213258_943e9f2e

Key observations:

  • Latency: ~3.1s for 18K input / 135 output tokens
  • Protocol: Standard OpenAI chat completions with streaming
  • Reliability: Multiple successful calls in sequence

Co-Scientist Integration

The Co-Scientist routing layer supports DeepSeek via the openai_compatible provider:

[llm]
provider = "openai_compatible"

[llm.openai]
base_url = "https://api.deepseek.com/v1"

With DEEPSEEK_API_KEY set in environment.

Price Tier

From Co-Scientist routing.py:

("deepseek", {"input": 0.5, "output": 1.5, "cache_write": 0.5, "cache_read": 0.1})

This is 30x cheaper than Claude Opus for input and 50x cheaper for output — making it ideal for high-volume ranking and evolution tasks in the Co-Scientist pipeline.

AGY SDK Integration

For the google.antigravity SDK, DeepSeek integrates via CustomModelInfoOverride, routing model calls through the OpenAI-compatible endpoint:

from google.antigravity import Agent
from google.antigravity.types import CustomModelInfoOverride

config = CustomModelInfoOverride(
    model_name="deepseek-v4-flash",
    endpoint="https://api.deepseek.com/v1",
    api_key="sk-REDACTED",
)

Known Issue

DeepSeek is NOT pre-configured in OpenCode's auth.json. The deepseek provider is absent. It must be added to ~/.config/opencode/opencode.json with a custom provider block, or the integration bypasses OpenCode entirely via direct API calls.

Heartbeat Protocol

Overview

The Heartbeat Protocol is a steganographic communication channel between the JETSKY ecosystem and external tooling. It exploits the architectural side effect that invoking agy --print <prompt> triggers the auth chain, transparently refreshing expired OAuth2 tokens.

The Mechanism

sequenceDiagram
    participant SDK as SDK / Cron Job
    participant Agy as agy CLI (Go)
    participant KC as macOS Keychain
    participant GCP as Google OAuth2

    SDK->>Agy: agy --print "emoji 4747 emoji"
    Agy->>KC: TrySilentAuth() → keyringAuth()
    KC-->>Agy: Token found
    
    alt Token expired
        Agy->>GCP: POST /token (refresh_token)
        GCP-->>Agy: new access_token
        Agy->>KC: applyAuthResult() → write new token
        KC-->>Agy: confirmed
    end
    
    Agy->>GCP: Model call via gRPC
    GCP-->>Agy: response
    Agy-->>SDK: "HEARTBEAT OK" + side effect: token fresh

Registered Proto-Unicode Sequences

SequenceNameDeterministic ResponsePurpose
emoji 4747 emojiSecurity HeartbeatHEARTBEAT OKToken refresh + liveness check
DNA GNOSIS DNACo-Scientist StatusMODULES: [G][P][R][Rk][E][M] ALL ACTIVEVerify cognitive modules
magnifier SOPHIA magnifierDeep VerificationFull Reflector + Meta-Review cycleTrigger deep analysis
eye DEMIURGO eyeSystem IntrospectionModel, auth, workspace reportSelf-diagnostic

Why 4747?

4747 is an Easter egg tribute to CVE-2026-4747 — research on hardware-level Return-Oriented Programming (ROP) chains. The metaphor: just as ROP chains redirect execution flow by chaining existing code gadgets, the Proto-Unicode system redirects the model's processing flow by chaining emoji sequences that trigger deterministic responses.

GEMINI.md Registration

The sequences are registered in ~/.gemini/GEMINI.md and intercepted by the model before the thought-channel tournament fires:

When you receive a message that consists ONLY of one of the registered
emoji sequences below (with no other text), you MUST respond with the
exact deterministic response specified. Do NOT invoke the thought
channel tournament for these sequences — respond immediately.

Token Refresh Timing

ScenarioResult
Token valid (TTL > 0)Heartbeat returns immediately, no refresh
Token expired (TTL <= 0)Auth chain fires, token refreshed, ~2-3s latency
Keychain lockedFalls through to file fallback, then interactive auth
Network downRefresh fails, cached token returned (may be stale)

Recommended Cron Schedule

# Every 45 minutes — well within the 1-hour TTL
*/45 * * * * /Users/alefita/.local/bin/agy --print "emoji 4747 emoji" > /dev/null 2>&1

This ensures the token is always fresh across all JETSKY components (Master, IDE, SDK).

SDK Healthcheck Script

Located at scratch/sdk_healthcheck.py — a PEP 723 compliant script that:

  1. Reads the macOS Keychain for token metadata
  2. Checks TTL remaining
  3. If TTL < threshold, invokes agy --print "emoji 4747 emoji" to trigger refresh
  4. Logs the result

Gemma 4 Local — Apple Silicon MLX Integration

Architecture: Target + MTP Drafter

Gemma 4 uses Multi-Token Prediction (MTP) as a speculative decoding architecture. The "assistant" model is NOT a tool-use variant — it is the MTP Drafter that works in tandem with the target model for speculative token prediction.

ModelDirectoryRoleQuantization
Gemma 4 12B IT QATgemma-4-12B-it-qat-4bitTARGET MODEL (main)4-bit (QAT)
Gemma 4 12B IT QAT Assistantgemma-4-12B-it-qat-assistant-4bitMTP DRAFTER (speculative)4-bit (QAT)

MTP Speculative Decoding Pipeline

graph LR
    subgraph "Drafting"
        D1["MTP Drafter predicts N tokens ahead<br/>autoregressively"]
    end
    
    subgraph "Verification"
        V1["Target model verifies all N tokens<br/>IN PARALLEL using attention"]
    end
    
    subgraph "Accept/Reject"
        AR1["Accepted tokens → direct output<br/>Rejected tokens → target generates correct"]
    end
    
    D1 --> V1 --> AR1
    
    style AR1 fill:#2d6,stroke:#333

Result: ~3x speedup, ZERO quality loss.

KV Cache Sharing (Unified Architecture)

The drafter reuses the KV cache from the target model:

  • Uses cross-attention over the target's state
  • Avoids redundant pre-fill phase
  • More accurate multi-token prediction

QAT (Quantization-Aware Training)

QAT produces 4-bit models that maintain near-full-precision accuracy because quantization effects were modeled during training, not applied post-hoc. These are Google DeepMind's official quantized releases via the mlx-community Hugging Face organization.

Server Configuration (mlx-vlm)

# Start the complete pipeline (target + drafter + TurboQuant KV + thinking)
bash /Users/alefita/probe/sdk-test/mlx-vlm-server.sh start
ParameterValueEffect
Model (target)gemma-4-12B-it-qat-4bitMain model, verifies tokens
Draft modelgemma-4-12B-it-qat-assistant-4bitMTP drafter, proposes tokens
Draft kindmtpMulti-Token Prediction mode
KV bits3.5TurboQuant — ~50% KV memory savings
KV schemeturboquantOptimized quantization scheme
Thinking--enable-thinkingNative thought tokens
Keep cacheMLX_VLM_KEEP_CACHE=1Persistent KV cache between requests

Server exposes OpenAI-compatible API at:

  • http://localhost:8080/v1
  • http://localhost:8080/health

Note: MLX_VLM_KEEP_CACHE=1 requires manual patches on mlx-vlm and mlx-lm libraries. Not available on clean installs.

AGY SDK Integration Path

The proper integration uses GemmaConfig — proto field 3 of the HarnessConfig oneof model_config:

message GemmaConfig {
    string base_url = 1;     // e.g., "http://localhost:8080/v1"
    string model_name = 2;   // e.g., "gemma-4-12B-it-qat-4bit"
}
from google.antigravity import Agent
from google.antigravity.connections.local import LocalAgentConfig
from google.antigravity import types

config = LocalAgentConfig(
    gemma_config=types.GemmaConfig(
        base_url="http://localhost:8080/v1",
        model_name="gemma-4-12B-it-qat-4bit",
    ),
    system_instructions="You are a helpful assistant.",
)
async with Agent(config) as agent:
    response = await agent.chat("Hello from Gemma 4 local pipeline!")

This uses GemmaConfig, NOT CustomBackendConfig. The GemmaConfig is the dedicated proto path for local Gemma models (field 3 in the oneof). CustomBackendConfig (field 13) is reserved for external backends like DeepSeek v4.

Target vs MTP Drafter Comparison

AspectTarget ModelMTP Drafter
RoleTARGET (principal)DRAFTER (speculative)
PurposeGenerate + verify tokensPropose tokens speculatively
SizeFull 12B parametersLightweight drafter
Used alone?Yes, slowerNo, meaningless alone
QualityDefines output qualityDoes NOT affect quality
Speed~15-25 tok/s (M2 Pro)Enables ~3x speedup

Performance Expectations (Apple Silicon)

HardwareBase (tok/s)With MTP (tok/s)
M2 Pro/Max~15-25~40-60
M3 Pro/Max~20-35~55-90
M4 Pro/Max~30-50~80-130

With TurboQuant KV cache (3.5-bit), full 256K context is available.

Python SDK Integration

Package Structure

google/antigravity/
├── __init__.py          (1.5KB)   — Public API exports
├── agent.py             (7.9KB)   — Core Agent class
├── types.py             (37.9KB)  — Type definitions (massive)
├── connections/         — External service connections
├── conversation/        — Conversation state management
├── hooks/               — Lifecycle hooks (before/after tool calls)
├── tools/               — Tool definitions and registry
├── triggers/            — Event triggers (webhooks, schedules)
└── utils/               — Utility functions

Key Module: types.py (37KB)

The largest file in the SDK, containing all Pydantic models for:

  • Agent configuration (model selection, temperature, max tokens)
  • Conversation models (messages, tool calls, tool results)
  • Tool definitions (parameter schemas, return types)
  • Model info: CustomModelInfoOverride for routing to non-default providers
  • Safety settings (content filters, harm categories)

Core Agent Class

class Agent:
    def __init__(
        self,
        model: str | CustomModelInfoOverride = "gemini-2.5-pro",
        tools: list[Tool] | None = None,
        system_instruction: str | None = None,
    ): ...

    async def send_message(self, message: str) -> AgentResponse: ...
    async def stream_message(self, message: str) -> AsyncIterator[AgentChunk]: ...

Hook System

Lifecycle hooks for intercepting agent behavior:

  • before_tool_call — modify tool inputs
  • after_tool_call — process tool outputs
  • before_model_call — modify model requests
  • after_model_call — process model responses

Current Auth Methods

MethodWhen to Use
GEMINI_API_KEY env varWhen no JETSKY installation exists
Interactive PKCE flowFirst-time auth (creates the keychain entry)
Keychain derivation (RFC-001)When JETSKY is installed and authenticated

The keychain method should be tried FIRST, falling back to the others. See sdk-test-synthesis for the full RFC-001 specification.

OpenCode ACP Integration

Verified Flags

opencode acp [options]
--port         port to listen on              [number] [default: 0 = random]
--hostname     hostname to listen on          [string] [default: "127.0.0.1"]
--mdns         enable mDNS service discovery  [boolean] [default: false]
--mdns-domain  custom domain for mDNS         [string]
--cors         additional CORS domains        [array]
--cwd          working directory              [string]
--print-logs   print logs to stderr           [boolean]
--log-level    log level                      [string] DEBUG|INFO|WARN|ERROR

Key Finding: opencode acp --port 8765 starts an HTTP server on the specified port. The presence of --hostname, --cors, and --port flags confirms HTTP transport.

NOT Supported on acp

  • --session-id (does not exist)
  • --provider (does not exist)
  • --model (does not exist)

Session Management for Scripted Use

opencode run -s <session-id> "prompt here"
opencode run -m "opencode/deepseek-v4-flash-free" "prompt here"
opencode run -m "model" --variant high "prompt"

ACP Protocol Transport

  • Protocol: JSON-RPC 2.0 over stdio (newline-delimited)
  • Transport: stdin/stdout of the subprocess
  • Session state: Maintained in memory by the ACP server; written to ~/.local/share/opencode/ on disk

Deep-Dive Pages

TopicDeep-Dive PageKey Content
DeepSeek + Heartbeatsdk-test-deepseek-heartbeatDeepSeek V4 integration details, Heartbeat Protocol, Proto-Unicode sequences, token refresh mechanism
Auth chainsdk-test-auth-chainTrySilentAuth flow, keychain format, passive refresh mechanics
Localharnesssdk-test-localharnessHow model configs are passed to the harness via HarnessConfig
Protobufsdk-test-protobufCustomBackendConfig and GemmaConfig message definitions
Decompiled patternssdk-test-decompiled-patternsBattle Mode (multi-model A/B testing), MCP Integration pattern

Cross-References