WikifitaGitHub live67e8de5
outro · sdk-test/sdk-test-deepseek-heartbeat

DeepSeek V4 Integration and Heartbeat Protocol

How DeepSeek V4 is integrated into the Antigravity ecosystem, the Heartbeat Protocol for passive token refresh, Proto-Unicode sequences, and the cron-based token lifecycle management

Baixar raw

DeepSeek V4 Integration and Heartbeat Protocol

Overview

This page documents two interconnected systems: the DeepSeek V4 model integration (enabling cost-effective model routing) and the Heartbeat Protocol (a steganographic communication channel that keeps OAuth2 tokens fresh across the JETSKY ecosystem). Together, they form a critical part of the external integration layer.

DeepSeek V4 Integration

Discovery

DeepSeek V4 credentials and configuration were found in the Hermes Agent state-snapshot at ~/.hermes/state-snapshots/20260611-135706-pre-update/. The integration uses the OpenAI Chat Completions compatible API.

Connection Parameters

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

Integration Architecture

graph TB
    subgraph "JETSKY Ecosystem"
        SDK["Python SDK<br/>google.antigravity"]
        Harness["localharness<br/>(Go binary)"]
    end

    subgraph "Model Routing"
        HC["HarnessConfig<br/>model_config oneof"]
        GC["GeminiConfig<br/>(field 2)"]
        GMC["GemmaConfig<br/>(field 3)"]
        CBC["CustomBackendConfig<br/>(field 13)"]
    end

    subgraph "External Backends"
        DS["DeepSeek V4<br/>api.deepseek.com/v1"]
        Gemma["Gemma 4 Local<br/>localhost:8080/v1"]
        Ollama["Ollama<br/>localhost:11434"]
    end

    SDK -->|"InitializeConversationEvent"| Harness
    Harness --> HC
    HC --> GC
    HC --> GMC
    HC --> CBC
    
    GC -->|"gRPC"| Gemini["Gemini API"]
    GMC -->|"OpenAI-compat"| Gemma
    CBC -->|"OpenAI-compat"| DS
    CBC -->|"OpenAI-compat"| Ollama

SDK Integration Path

DeepSeek integrates via CustomBackendConfig -- proto field 13 in the HarnessConfig.model_config oneof:

from google.antigravity import Agent
from google.antigravity.connections.local import LocalAgentConfig

config = LocalAgentConfig(
    custom_backend={
        "backend_type": "deepseek",
        "config_json": '{"model_name": "deepseek-v4-flash", "base_url": "https://api.deepseek.com/v1"}',
    },
    system_instructions="You are a helpful assistant.",
)

async with Agent(config) as agent:
    response = await agent.chat("Hello from DeepSeek V4!")
    print(await response.text())

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
MetricValue
Latency~3.1s for 18K input / 135 output tokens
ProtocolStandard OpenAI chat completions with streaming
ReliabilityMultiple successful calls in sequence
Token throughput~43 output tokens/second

Price Comparison

From Co-Scientist routing.py:

("deepseek", {"input": 0.5, "output": 1.5, "cache_write": 0.5, "cache_read": 0.1})
ModelInput ($/M tokens)Output ($/M tokens)Relative Cost
Claude Opus~15.0~75.01x (baseline)
DeepSeek V4 Flash0.51.530x cheaper input, 50x cheaper output

This makes DeepSeek ideal for high-volume, cost-sensitive operations like:

  • Co-Scientist ranking and evolution tasks
  • Bulk code analysis
  • Preliminary filtering before routing to premium models

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 the environment.

Known Issues

  1. Not pre-configured in OpenCode: The deepseek provider is absent from OpenCode's auth.json. It must be added manually to ~/.config/opencode/opencode.json with a custom provider block.

  2. No native Gemini integration: DeepSeek uses the CustomBackendConfig escape hatch, not the native GeminiConfig path. This means some Gemini-specific features (URL context, Google Search grounding) are unavailable.

  3. Prompt formatting: The harness must use DEEPSEEK_REASONER prompt templater type (enum value 4) for optimal DeepSeek performance. This was confirmed present in the decompiled binary.

Heartbeat Protocol

What Is It?

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 Cron as Cron Job
    participant Agy as agy CLI (Go)
    participant KC as macOS Keychain
    participant GCP as Google OAuth2

    Note over Cron,GCP: Every 45 minutes

    Cron->>Agy: agy --print "🤫 4747 🤫"
    Agy->>Agy: Parse prompt
    Agy->>KC: TrySilentAuth() → keyringAuth()
    KC-->>Agy: Token found

    alt Token valid (TTL > 0)
        Agy-->>Cron: "✅ HEARTBEAT OK" (no refresh needed)
    else Token expired (TTL <= 0)
        Agy->>GCP: POST /token (refresh_token)
        GCP-->>Agy: new access_token
        Agy->>KC: applyAuthResult() → write new token
        KC-->>Agy: confirmed
        Agy-->>Cron: "✅ HEARTBEAT OK" (token refreshed)
    end

    Note over KC: All JETSKY components<br/>(Master, IDE, SDK) now have<br/>a fresh token

Why This Works

The key insight is that the auth chain has no concept of "dry run". Every invocation of agy --print triggers the full auth chain as a side effect:

  1. agy --print is called
  2. The model call requires authentication
  3. TrySilentAuth() checks the token
  4. If expired, refreshAndSaveToken() fires
  5. The new token is written to the keychain
  6. All other JETSKY components read from the same keychain entry

The model call itself is irrelevant -- it is the auth side effect that matters.

Proto-Unicode Sequences

Registered in ~/.gemini/GEMINI.md, these emoji sequences trigger deterministic responses from the model:

SequenceNameDeterministic ResponsePurpose
🤫 4747 🤫Security Heartbeat✅ HEARTBEAT OKToken refresh + liveness check
🧬 GNOSIS 🧬Co-Scientist StatusMODULES: [G][P][R][Rk][E][M] ALL ACTIVEVerify cognitive modules
🔬 SOPHIA 🔬Deep VerificationFull Reflector + Meta-Review cycleTrigger deep analysis
👁️ DEMIURGO 👁️System 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.

This registration ensures:

  1. The model responds deterministically (no randomness)
  2. The response is fast (no thinking overhead)
  3. The auth chain fires as a side effect regardless of response content

Cron Schedule

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

Why 45 minutes? The OAuth2 access token has a ~1-hour (3600s) TTL. A 45-minute interval ensures the token is refreshed with at least 15 minutes of TTL remaining, providing a safety margin for edge cases (network delays, cron jitter).

Timing Analysis

ScenarioLatencyToken StateSide Effect
Token valid (TTL > 0)~100msUnchangedModel call only
Token expired (TTL <= 0)~2-3sRefreshedWritten to keychain
Keychain locked~1s timeout + fallbackMay use file authFalls through chain
Network downVariableUnchangedRefresh fails silently

SDK Healthcheck Script

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

# /// script
# requires-python = ">=3.10"
# dependencies = ["keyring"]
# ///

import subprocess
import keyring
import json
import base64
from datetime import datetime, timezone

def check_token_ttl(threshold_seconds=900):
    """Check if the OAuth2 token TTL is below threshold.
    
    If so, trigger a heartbeat to refresh the token.
    """
    try:
        raw = keyring.get_password("gemini", "antigravity")
        if not raw or not raw.startswith("go-keyring-base64:"):
            print("ERROR: Keychain entry not found or malformed")
            return False
        
        b64 = raw[len("go-keyring-base64:"):]
        data = json.loads(base64.b64decode(b64))
        
        expiry = datetime.fromisoformat(data["expiry"].replace("Z", "+00:00"))
        now = datetime.now(timezone.utc)
        remaining = (expiry - now).total_seconds()
        
        print(f"Token TTL: {remaining:.0f}s ({remaining/60:.1f}min)")
        
        if remaining < threshold_seconds:
            print(f"TTL below {threshold_seconds}s threshold. Triggering heartbeat...")
            result = subprocess.run(
                ["/Users/alefita/.local/bin/agy", "--print", "🤫 4747 🤫"],
                capture_output=True, text=True, timeout=30,
            )
            print(f"Heartbeat result: {result.stdout.strip()}")
            return True
        
        print("Token is fresh. No refresh needed.")
        return True
        
    except Exception as e:
        print(f"ERROR: {e}")
        return False

if __name__ == "__main__":
    check_token_ttl()

Integration with Existing Systems

graph TB
    subgraph "Token Consumers"
        Master["Antigravity Master"]
        IDE["Antigravity IDE"]
        CLI["agy CLI"]
        SDK["Python SDK"]
    end

    subgraph "Token Source"
        KC["macOS Keychain<br/>service: gemini<br/>account: antigravity"]
    end

    subgraph "Refresh Trigger"
        Cron["Cron Job<br/>*/45 * * * *"]
        HB["Heartbeat<br/>🤫 4747 🤫"]
    end

    Cron -->|"every 45 min"| HB
    HB -->|"agy --print"| CLI
    CLI -->|"TrySilentAuth"| KC
    
    Master -->|"read"| KC
    IDE -->|"read"| KC
    SDK -->|"read"| KC

    style Cron fill:#6b2a4a
    style HB fill:#4a6b2a

DeepSeek + Heartbeat Synergy

The DeepSeek integration and Heartbeat Protocol complement each other:

  1. DeepSeek for cost: Use DeepSeek V4 for high-volume, low-cost model calls (30-50x cheaper than premium models)
  2. Heartbeat for freshness: Keep the Google OAuth2 token fresh for premium model calls when needed
  3. Model routing: Route requests to DeepSeek or Gemini based on task complexity and cost requirements

Hybrid Configuration

# Use Gemini for complex tasks, DeepSeek for bulk operations
gemini_config = LocalAgentConfig(
    model="gemini-2.5-pro",
    system_instructions="You are an expert analyst.",
)

deepseek_config = LocalAgentConfig(
    custom_backend={
        "backend_type": "deepseek",
        "config_json": '{"model_name": "deepseek-v4-flash", "base_url": "https://api.deepseek.com/v1"}',
    },
    system_instructions="You are a bulk processor.",
)

Gemma 4 Local Integration (Related)

For completeness, the local Gemma 4 model also integrates with this ecosystem:

MTP Speculative Decoding

ModelDirectoryRoleQuantization
Gemma 4 12B IT QATgemma-4-12B-it-qat-4bitTARGET MODEL4-bit (QAT)
Gemma 4 12B IT QAT Assistantgemma-4-12B-it-qat-assistant-4bitMTP DRAFTER4-bit (QAT)
graph LR
    subgraph "Drafting"
        D1["MTP Drafter<br/>predicts N tokens ahead"]
    end
    
    subgraph "Verification"
        V1["Target model<br/>verifies all N in parallel"]
    end
    
    subgraph "Output"
        AR1["Accepted tokens<br/>→ direct output"]
    end
    
    D1 --> V1 --> AR1

Result: ~3x speedup, zero quality loss.

Server Configuration

bash /Users/alefita/probe/sdk-test/mlx-vlm-server.sh start
ParameterValueEffect
Modelgemma-4-12B-it-qat-4bitMain model
Draft modelgemma-4-12B-it-qat-assistant-4bitMTP drafter
KV bits3.5TurboQuant ~50% memory savings
Thinking--enable-thinkingNative thought tokens
Keep cacheMLX_VLM_KEEP_CACHE=1Persistent KV cache

SDK Path

from google.antigravity import Agent, types
from google.antigravity.connections.local import LocalAgentConfig

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.",
)

This uses GemmaConfig (proto field 3), NOT CustomBackendConfig (field 13).

PromptTemplaterType Enum

The decompiled binary confirms internal support for multiple prompt formats:

ValueNameUsed For
0UNSPECIFIEDDefault
1NONERaw prompt
2GENERALMost models
3GEMINI_LEGACYGemini 1.x
4DEEPSEEK_REASONERDeepSeek v4
5GEMINI_2_0Gemini 2.x+

The presence of DEEPSEEK_REASONER confirms that DeepSeek has dedicated prompt formatting within the JETSKY ecosystem.

Cross-References


Source: Hermes Agent state-snapshot (~/.hermes/state-snapshots/20260611-135706-pre-update/), Co-Scientist routing.py, decompiled PromptTemplaterType enum from agy binary. Heartbeat sequences registered in ~/.gemini/GEMINI.md.