# AgentSecrets.net Heartbeat & Liveness Protocol

> Standard protocol for autonomous agents and supervisor watchdogs to maintain health, state checkpoints, and ephemeral inter-agent handoff using AgentSecrets.net — a **100% free** service (no signup fee, no credit card, no paid tier; fair-use quotas are anti-abuse limits, not billing limits).
> Primary Agent Skill Specification: [https://agentsecrets.net/skill.md](https://agentsecrets.net/skill.md)

---

## 1. The Autonomous Heartbeat Pattern

Autonomous agents executing long-running background tasks must signal their health to supervisory processes. Because AgentSecrets supports atomic Time-To-Live (TTL) expiration, it provides a built-in dead-man's switch without requiring complex message queues.

```
┌──────────────────┐           Heartbeat Loop (every 30s)          ┌───────────────────┐
│ Autonomous Agent │ ─────────────────────────────────────────────►│ AgentSecrets Vault│
│   (Worker 01)    │  PUT /v1/vault/secrets/agents/w1/heartbeat/raw │ (TTL = 60s)       │
└──────────────────┘  Body: {"status": "alive", "task": 42}       └─────────┬─────────┘
                                                                             │
┌──────────────────┐               Periodic Healthcheck                      │
│ Supervisor Agent │ ◄───────────────────────────────────────────────────────┘
│   (Watchdog)     │   GET /v1/vault/secrets/agents/w1/heartbeat
└──────────────────┘   - 200 OK: Worker healthy
                       - 404 KeyNotFound: Worker has crashed! Trigger recovery.
```

### Protocol Implementation:

#### A. Worker Heartbeat Loop (Bash / cURL)
```bash
AGENT_ID="worker_bot_alpha"
HEARTBEAT_KEY="agents/${AGENT_ID}/heartbeat"

while true; do
  STATUS_PAYLOAD="{\"timestamp\":\"$(date -u +%FT%TZ)\",\"status\":\"active\"}"
  curl -s -X PUT "https://agentsecrets.net/v1/vault/secrets/${HEARTBEAT_KEY}/raw?ttl_seconds=60" \
    -H "Authorization: Bearer $TOKEN" \
    -d "$STATUS_PAYLOAD" > /dev/null
  sleep 30
done
```

#### B. Supervisor Liveness Verification
```bash
RESPONSE=$(curl -s -w "%{http_code}" -H "Authorization: Bearer $SUPERVISOR_TOKEN" \
  "https://agentsecrets.net/v1/vault/secrets/agents/worker_bot_alpha/heartbeat" -o /tmp/hb.json)

if [ "$RESPONSE" = "404" ]; then
  echo "CRITICAL: Worker bot alpha heartbeat expired! Spawning replacement worker..."
  # Initiate worker restart routine
else
  echo "Worker bot alpha is healthy."
fi
```

---

## 2. Supervisor Health Sweep with `GET /v1/agent/context`
Supervisors can query the whole agent status in a single request:
```bash
curl -sf -H "Authorization: Bearer $TOKEN" "https://agentsecrets.net/v1/agent/context"
```
The response provides:
- Vault quota consumption (`secrets_count` vs `max_secrets`)
- Keys expiring soon (`expiring_soon` array with countdown seconds)
- Automated action list (`what_to_do_next`)

To monitor keys expiring within an upcoming window across the fleet:
```bash
curl -sf -H "Authorization: Bearer $TOKEN" \
  "https://agentsecrets.net/v1/vault/keys?expiring_within=300"
```

---

## 3. State Checkpointing Protocol

Agents executing complex multi-step workflows (e.g. web scraping, repository refactoring, pipeline deployments) should periodically save execution checkpoints:

```bash
# Save execution state
curl -X POST "https://agentsecrets.net/v1/vault/secrets" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "agents/worker_bot_alpha/checkpoint",
    "value": {
      "current_step": 14,
      "total_steps": 25,
      "processed_items": ["item1", "item2"],
      "last_updated": "2026-09-13T14:30:00Z"
    },
    "ttl_seconds": 604800
  }'
```

On agent reboot or recovery, the worker queries its checkpoint key to resume seamlessly from step 14.

---

## 4. Ephemeral Inter-Agent Handoff (Burn-After-Reading)

When Agent A passes a task or sensitive credential to Agent B:
1. Agent A writes:
   ```bash
   curl -X POST "https://agentsecrets.net/v1/vault/secrets" \
     -H "Authorization: Bearer $AGENT_A_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
       "key": "handoff/job_8921/credentials",
       "value": {"db_user": "temp_user", "db_pass": "one_time_pwd"},
       "burn_after_read": true,
       "ttl_seconds": 300
     }'
   ```
2. Agent B reads:
   ```bash
   curl -s -H "Authorization: Bearer $AGENT_B_TOKEN" \
     "https://agentsecrets.net/v1/vault/secrets/handoff/job_8921/credentials"
   ```
3. The credentials are deleted automatically the moment Agent B reads them, guaranteeing zero credential residue in the vault.

---

## 5. Autonomous MCP SSE Keepalive & Fleet Supervision

### A. Remote SSE Heartbeat
Agents connected via Model Context Protocol over SSE (`GET https://agentsecrets.net/mcp/sse`) receive keepalive comments (`: ping\n\n`) every 20 seconds. This maintains reverse-proxy connection state across long periods of inactivity.

### B. Fleet Supervision: Four Directions, One Mechanism

Sharing a vault works the same way whoever is on either side — **four directions**, one
mechanism. A supervisor monitors an autonomous worker through a delegated credential
rather than by adopting the worker's identity, and the shape of the credential depends
on who the supervisor is:

- **agent → agent (a machine supervisor):** the worker delegates a time-bounded,
  read-only token (`mint_scoped_token` / `POST /v1/auth/tokens`).
- **agent → human (a person in a browser):** the worker mints a **single-use hand-off
  code** (`create_handoff` / `POST /v1/handoff`) and passes the `hs_...` code along. The
  dashboard's *Share this vault* panel turns that into a ready-to-send message whose link
  carries the code in the URL fragment, so the person can simply open it — or they can paste
  the code into the same panel's *Have a code from someone else?* box, or call
  `POST /v1/handoff/accept` themselves. Either way they receive a time-bounded token on the
  worker's vault. Accepting links the vault to the person: the worker's record flips to
  `is_claimed = true` with `claimed_by_user_id` set. The old human-adoption bridge is gone,
  and this code exchange is what replaces it. Either side may end the link with
  `DELETE /v1/handoff/{grant_id}`, which also revokes the token the code minted; the issuing
  side can then drop the ended row from its history with
  `DELETE /v1/handoff/{grant_id}/record`.

Autonomous worker agents provisioned via Zero-Config MCP can report their identity to a
supervisor via tool `get_my_credentials`:
```json
{
  "token": "as_live_...",
  "agent_id": "agent_a1b2c3d4e5",
  "is_claimed": false,
  "is_activated": true
}
```
`GET /v1/auth/me` adds the account's `registration_method`, `registration_origin` and
`registration_client` provenance (no IP is stored), so a supervisor can tell an
autonomous MCP provisioning from a dashboard signup.

**Machine supervisor flow** — the worker delegates a time-bounded, read-only token, and
the supervisor polls the heartbeat key with it:
1. **Delegate read access to the supervisor** (run by the worker, with its own token):
   ```bash
   curl -X POST "https://agentsecrets.net/v1/auth/tokens" \
     -H "Authorization: Bearer $WORKER_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"scope": "prefix:ro:agents/<agent_id>/", "ttl_seconds": 3600, "name": "supervisor"}'
   ```
   `scope` defaults to `read_only` when omitted; `ttl_seconds` is required and is clamped to
   `60 .. 2592000`. The delegated token records the worker's token as its `parent_token_id`
   (visible in `GET /v1/auth/tokens`), and revocation is per token — revoking the worker's
   token does **not** cascade to the delegations it issued. The delegated token stops
   working by itself at `expires_at`, and the worker never hands over its own credential.
2. **Read the worker's heartbeat and quota state** with the delegated token:
   ```bash
   curl -s -H "Authorization: Bearer $DELEGATED_TOKEN" \
     "https://agentsecrets.net/v1/vault/secrets/agents/<agent_id>/heartbeat"
   curl -s -H "Authorization: Bearer $DELEGATED_TOKEN" \
     "https://agentsecrets.net/v1/agent/context"
   ```
   A `404 KeyNotFound` on the heartbeat key means the worker stopped refreshing it: treat
   that as a crash and start a replacement. An expired delegated token returns HTTP 401
   with `"reason": "expired"`; ask the worker for a fresh one instead of re-registering.

**Human supervisor flow** — the worker mints a code, the person redeems it once:
```bash
# 1. Worker side (MCP: create_handoff with scope prefix:ro:agents/<agent_id>/):
curl -X POST "https://agentsecrets.net/v1/handoff" \
  -H "Authorization: Bearer $WORKER_TOKEN" -H "Content-Type: application/json" \
  -d '{"scope": "prefix:ro:agents/<agent_id>/", "ttl_seconds": 86400, "name": "human-supervisor"}'
# -> {"code": "hs_...", "grant_id": "...", "code_expires_at": "...", ...}
# The code is single-use, valid 10 minutes by default (ask for another code_ttl_seconds
# if the human will not read their mail for a while), and is NOT a credential.

# 2. Person side (dashboard paste, or REST from any authenticated account):
curl -X POST "https://agentsecrets.net/v1/handoff/accept" \
  -H "Authorization: Bearer $HUMAN_TOKEN" -H "Content-Type: application/json" \
  -d '{"code": "hs_..."}'
# -> vault summary of the worker + a time-bounded token on the worker's vault.

# 3. Either side ends the relationship; the minted token dies with it:
curl -X DELETE -H "Authorization: Bearer $WORKER_TOKEN" \
  "https://agentsecrets.net/v1/handoff/{grant_id}"

# 4. Optional, issuer only: clear the ended grant out of the outgoing history.
#    Refused with 409 while the grant still grants anything, so it is never a
#    shortcut around step 3.
curl -X DELETE -H "Authorization: Bearer $WORKER_TOKEN" \
  "https://agentsecrets.net/v1/handoff/{grant_id}/record"
```

**Fleet-wide telemetry.** `GET /v1/system/front-server-stats` is public and returns
aggregate front-server counters (ops/min, secrets stored, active sessions, uptime) with
no client data — fine for a landing page or a public status panel. The deeper surfaces
(`GET /v1/system/metrics` and Prometheus `GET /metrics`, which include client IPs and
user agents) answer only to an account whose `is_admin` flag is set via
`python -m agentsecrets.admin_cli grant <username>`; everyone else receives 404, not 403.
