---
name: sdk-test-deepseek-heartbeat
type: reference
title: "DeepSeek V4 Integration and Heartbeat Protocol"
description: "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"
tags: [deepseek, heartbeat, token-refresh, cron, proto-unicode, integration, openai-compat]
timestamp: 2026-07-22
---

# 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

| Parameter | Value |
|-----------|-------|
| API Key | [REDACTED] |
| Base URL | `https://api.deepseek.com/v1` |
| Model | `deepseek-v4-flash` |
| Protocol | OpenAI Chat Completions (compatible) |
| Source | Hermes Agent `.env` and `auth.json` |

### Integration Architecture

```mermaid
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:

```python
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
```

| Metric | Value |
|--------|-------|
| Latency | ~3.1s for 18K input / 135 output tokens |
| Protocol | Standard OpenAI chat completions with streaming |
| Reliability | Multiple successful calls in sequence |
| Token throughput | ~43 output tokens/second |

### Price Comparison

From Co-Scientist `routing.py`:

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

| Model | Input ($/M tokens) | Output ($/M tokens) | Relative Cost |
|-------|--------------------|--------------------|---------------|
| Claude Opus | ~15.0 | ~75.0 | 1x (baseline) |
| DeepSeek V4 Flash | 0.5 | 1.5 | **30x 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:

```toml
[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

```mermaid
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:

| Sequence | Name | Deterministic Response | Purpose |
|----------|------|----------------------|---------|
| `🤫 4747 🤫` | Security Heartbeat | `✅ HEARTBEAT OK` | Token refresh + liveness check |
| `🧬 GNOSIS 🧬` | Co-Scientist Status | `MODULES: [G][P][R][Rk][E][M] ALL ACTIVE` | Verify cognitive modules |
| `🔬 SOPHIA 🔬` | Deep Verification | Full Reflector + Meta-Review cycle | Trigger deep analysis |
| `👁️ DEMIURGO 👁️` | System Introspection | Model, auth, workspace report | Self-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:

```markdown
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

```bash
# 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

| Scenario | Latency | Token State | Side Effect |
|----------|---------|-------------|-------------|
| Token valid (TTL > 0) | ~100ms | Unchanged | Model call only |
| Token expired (TTL <= 0) | ~2-3s | Refreshed | Written to keychain |
| Keychain locked | ~1s timeout + fallback | May use file auth | Falls through chain |
| Network down | Variable | Unchanged | Refresh fails silently |

### SDK Healthcheck Script

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

```python
# /// 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

```mermaid
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

```python
# 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

| Model | Directory | Role | Quantization |
|-------|-----------|------|--------------|
| Gemma 4 12B IT QAT | `gemma-4-12B-it-qat-4bit` | TARGET MODEL | 4-bit (QAT) |
| Gemma 4 12B IT QAT Assistant | `gemma-4-12B-it-qat-assistant-4bit` | MTP DRAFTER | 4-bit (QAT) |

```mermaid
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
bash /Users/alefita/probe/sdk-test/mlx-vlm-server.sh start
```

| Parameter | Value | Effect |
|-----------|-------|--------|
| Model | `gemma-4-12B-it-qat-4bit` | Main model |
| Draft model | `gemma-4-12B-it-qat-assistant-4bit` | MTP drafter |
| KV bits | `3.5` | TurboQuant ~50% memory savings |
| Thinking | `--enable-thinking` | Native thought tokens |
| Keep cache | `MLX_VLM_KEEP_CACHE=1` | Persistent KV cache |

### SDK Path

```python
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:

| Value | Name | Used For |
|-------|------|----------|
| 0 | UNSPECIFIED | Default |
| 1 | NONE | Raw prompt |
| 2 | GENERAL | Most models |
| 3 | GEMINI_LEGACY | Gemini 1.x |
| 4 | DEEPSEEK_REASONER | DeepSeek v4 |
| 5 | GEMINI_2_0 | Gemini 2.x+ |

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

## Cross-References

- [[sdk-test-integrations]] — Broader integration map (all models, all protocols)
- [[sdk-test-auth-chain]] — The auth chain that the Heartbeat refreshes
- [[sdk-test-protobuf]] — CustomBackendConfig and GemmaConfig message definitions
- [[sdk-test-architecture]] — JETSKY ecosystem architecture
- [[sdk-test-localharness]] — How model configs are passed to the harness
- [[sdk-test-decompiled-patterns]] — Battle Mode (multi-model A/B testing)
- [[co-scientist]] — Co-Scientist multi-agent system using DeepSeek for bulk operations

---

*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`.*
