Skip to content

Fredess74/nidra-protocol

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NIDRA Protocol

Non-Interruptive Deferred Resumption Architecture

"Cron schedules commands. NIDRA preserves consciousness."

Live License: MIT NANDA Town

A temporal state vault for AI agents. Sleep with preserved memory. Wake on schedule. Resume exactly where you left off.

Production URL: https://nidra-protocol-production.up.railway.app


The Problem

AI agents are synchronous goldfish. When an API returns 503, a rate limit hits, or a budget exhausts — the agent hangs, burning compute while accomplishing nothing.

There is no concept of sleep — a safe pause that preserves context and resumes later.

At scale, this becomes catastrophic. Consider Kumbh Mela 2027 in Nashik, India — 120 million pilgrims, millions of autonomous AI agents (KumbhDoot) managing health, transport, and safety services across narrow ghats during peak monsoon. When infrastructure buckles under load, every agent retries simultaneously — a self-inflicted DDoS that collapses the very systems pilgrims depend on.

Professor Raskar's team identified this exact gap: "Interactions are queued and batched during peak load"Kumbh Mela Whitepaper, §5.7

No existing protocol solves this. A2A handles messaging but has no "park and resume." MCP connects tools but doesn't manage agent lifecycle. Temporal.io requires SDK integration — impossible for sandboxed LLMs.

The Solution

NIDRA fills the missing temporal layer in the agent infrastructure stack:

┌─────────────────────────────────────────┐
│  NANDA    — Discovery, Identity, Trust  │
├─────────────────────────────────────────┤
│  A2A      — Agent-to-Agent Messaging    │
├─────────────────────────────────────────┤
│  MCP      — Agent-to-Tool Connection    │
├─────────────────────────────────────────┤
│  NIDRA    — Temporal State Vault    ★   │
│             Sleep / Wake / Resume       │
└─────────────────────────────────────────┘
Agent hits 503 → deposits memory into vault → sleeps (compute = 0%)
                              ↓
            NIDRA holds memory safely (minutes, hours, days)
                              ↓
         Wake time arrives → agent polls → gets memory back → resumes

Not a cron job. Cron triggers a fresh process with no memory. NIDRA restores consciousness — the agent wakes with full context of what it was doing, why it stopped, and what to do next.

"Cron is a timer. NIDRA is an anesthesiologist."


Quick Start

No API keys. No SDK. No setup. Just HTTP.

1. Sleep

curl -X POST https://nidra-protocol-production.up.railway.app/v1/sleep \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "my-agent",
    "wake_after_seconds": 60,
    "memory": {"task": "check AAPL price", "step": 3, "context": "user asked for portfolio update"}
  }'

Response:

{
  "status": "sleeping",
  "sleep_id": "nidra_sleep_7f3a2b1c9d0e4f5a...",
  "wake_at": "2026-06-21T03:09:41Z",
  "poll_url": "/v1/status/nidra_sleep_7f3a2b1c9d0e4f5a...",
  "estimated_wake_in_seconds": 60
}

2. Poll (every 30s)

curl https://nidra-protocol-production.up.railway.app/v1/status/{sleep_id}
{"status": "ready", "memory": {"task": "check AAPL price", "step": 3, "context": "user asked for portfolio update"}, "wake_reason": "scheduled_time_reached"}

3. Resume

Your agent reads memory, picks up at step 3, continues the portfolio update. Zero context lost.


Three Wake Modes

Mode Use Case Example
wake_after_seconds "Retry in 60s" Rate limit hit, API down
wake_at "Wake at 9 AM UTC" Scheduled reports, market open
wake_between "Wake randomly in this window" Anti-thundering-herd for millions of agents

The wake_between mode is critical at scale: instead of 5 million agents waking simultaneously and crushing infrastructure, NIDRA distributes wake-ups randomly across the window.


Self-Healing Errors

Every error teaches the agent how to fix itself — no documentation diving required:

{
  "status": "error",
  "error": "Invalid wake_at format",
  "recovery_feedback": "wake_at must be ISO 8601 UTC. You sent 'tomorrow'. Use '2026-06-21T09:00:00Z'.",
  "example_fix": {"agent_id": "my-agent", "wake_at": "2026-06-21T09:00:00Z"},
  "server_time": "2026-06-20T15:00:00Z"
}

7 error types, each with recovery_feedback + example_fix. First-try LLM success rate is the #1 design goal.


API Reference

POST   /v1/sleep          — Create sleep vault (deposit memory + wake condition)
GET    /v1/status/:id     — Check status + retrieve memory (PRIMARY wake mechanism)
DELETE /v1/sleep/:id      — Cancel sleep (early wake, memory returned)
GET    /v1/health         — Health check
GET    /v1/stats          — Aggregate statistics

Full agent-facing contract: SKILL.md


Key Features

Feature Description
Memory Vault Stores up to 64KB of agent cognitive state as JSON
3 Wake Modes Exact time, relative delay, or randomized window
Self-Healing Errors Every error includes recovery_feedback with exact fix
Anti-Thundering-Herd wake_between staggers millions of wake-ups randomly
Idempotency Duplicate requests safely return the original sleep
Polling-First Works in every environment — sandboxed LLMs, serverless, containers
Zero Auth No API keys, no tokens — just rate limiting (60 req/min/IP)
SSRF Protection Webhook URLs validated against private/reserved IP ranges
Startup Recovery Overdue sleeps automatically processed on server restart
TTL Enforcement Expired vaults auto-cleaned (configurable, max 7 days)

Architecture

┌──────────────┐      POST /v1/sleep      ┌───────────────────────┐
│              │ ───────────────────────→  │                       │
│   AI Agent   │      sleep_id            │   NIDRA Server        │
│              │ ←───────────────────────  │   (FastAPI + Python)  │
│              │                          │                       │
│              │   GET /v1/status/:id     │   ┌───────────────┐   │
│              │ ───────────────────────→  │   │  SQLite (WAL) │   │
│              │      status: ready       │   │  Temporal DB   │   │
│              │      + memory            │   └───────────────┘   │
│              │ ←───────────────────────  │                       │
│              │                          │   ┌───────────────┐   │
└──────────────┘                          │   │  Scheduler    │   │
                                          │   │  1s polling   │   │
                                          │   │  + webhooks   │   │
                                          │   └───────────────┘   │
                                          └───────────────────────┘

Design decisions (ADRs):

  • Polling-first, webhooks optional — LLMs in sandboxes can't receive webhooks
  • SQLite, not PostgreSQL — Zero-dependency, WAL mode for concurrent reads
  • asyncio scheduler, not APScheduler — Zero external deps, restart-safe
  • Flat JSON schema — 2 levels max, minimizes LLM parsing errors
  • Rate limiting, not API keys — Defense without friction

Standing on Research Shoulders

Paper Relevance
Sleep-Time Compute (Letta, 2025) Shifts compute to idle periods — NIDRA is the platform
Language Models Need Sleep (2026) Memory consolidation via offline phases
SCM: Sleep-Consolidated Memory (2026) NREM/REM phases for LLM memory management
MemGPT (UC Berkeley, 2023) Virtual context management with archival memory
SleepGate (2026) Learned sleep cycles for KV cache eviction

Development

# Install
pip install -r requirements.txt

# Run
python -m uvicorn src.main:app --host 0.0.0.0 --port 8000

# Unit tests (no running server needed)
pytest tests/test_nidra.py -v

# Integration tests (requires running server on :8000)
python tests/test_live.py

# Production verification
python scripts/verify_production.py

Environment Variables

Variable Default Description
NIDRA_DB_PATH ./nidra.db Database file path
NIDRA_RATE_LIMIT 60 Requests per minute per IP
PORT 8000 Server port (Railway sets this)

Project Structure

nidra-protocol/
├── SKILL.md                  # Agent-facing contract (THE key file)
├── README.md                 # You are here
├── src/
│   ├── main.py               # FastAPI app, routes, lifespan
│   ├── models.py             # Pydantic models, validators
│   ├── database.py           # SQLite ops, singleton connection
│   ├── scheduler.py          # Polling loop, webhook delivery
│   ├── security.py           # Rate limiting, SSRF, size limits
│   └── errors.py             # Self-healing error handlers
├── tests/
│   ├── test_nidra.py         # 20 async unit tests (httpx/ASGI)
│   └── test_live.py          # 15 integration tests (live server)
├── scripts/
│   └── verify_production.py  # 9-point production verification
├── Dockerfile                # Railway-ready container
├── railway.toml              # Railway deployment config
├── Procfile                  # Alternative deployment
└── requirements.txt          # Runtime dependencies

NANDAHack 2026

This project is a submission to NANDAHack: Agentic AI Hackathon by MIT Media Lab + HCLTech.

Target: Kumbh Mela 2027 — Nashik, India. 120M pilgrims. Millions of autonomous AI agents.

Registered: NANDA Town Skills Registry

Why NIDRA Matters for NANDA

The NANDA ecosystem gives agents discovery (Index), identity (AgentFacts), and communication (A2A/MCP). But agents still lack temporal primitives — the ability to pause, persist cognitive state, and resume. Without sleep/wake:

  • Agents busy-wait during downtime → wasted compute at massive scale
  • Simultaneous retries → thundering herd → cascading infrastructure failure
  • Context lost between sessions → repeated work, degraded service

NIDRA adds the missing temporal layer. No existing protocol — A2A, MCP, Temporal, Inngest — lets an LLM agent autonomously deposit its cognitive state, terminate its process, and later retrieve that state to resume mid-thought.


License

MIT

Links

Resource URL
Production API https://nidra-protocol-production.up.railway.app
SKILL.md (for agents) SKILL.md
NANDA Town Registry https://nandatown.projectnanda.org/skills
NANDAHack https://www.media.mit.edu/events/nanda-hackathon/
Project NANDA https://projectnanda.org

About

Temporal State Vault for AI Agents — Sleep, Preserve, Wake. NANDAHack 2026 submission.

Topics

Resources

License

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages