Skip to content
nerva docs v0.2.1

Primitives Overview

Nerva provides 8 primitives. Each is a Protocol (Python), interface (TypeScript), or interface (Go) with one or more default implementations. Use one, use all, replace any.

The Primitives

0. ExecContext — The Connective Tissue

Every method in every primitive receives an ExecContext. It carries:

  • Identity — request ID, trace ID, user ID, session ID
  • Permissions — what this user/agent can access
  • Memory scope — user, session, agent, or global
  • Observability — trace spans, structured events, token usage
  • Lifecycle — creation time, timeout, cooperative cancellation
  • Streaming — optional stream sink for real-time token delivery

Without it, you end up passing 6 separate arguments to every function, or building a god-object later. Every project that starts without this adds it in v2.

from nerva import ExecContext
ctx = ExecContext.create(
user_id="user_123",
session_id="session_abc",
memory_scope="session",
timeout_seconds=30,
)

1. Router — Intent Classification

Takes a raw message and returns a structured intent with confidence score and matched handler.

Provided strategies:

StrategyHow it worksTrade-off
RuleRouterRegex/keyword matchingFast, deterministic, no LLM cost
EmbeddingRouterCosine similarity against handler descriptionsFast, no LLM call, needs embedding model
LLMRouterStructured output from LLM with handler catalogAccurate, slower, costs tokens
HybridRouterEmbedding pre-filter then LLM re-rankBest accuracy, moderate cost
from nerva.router.rule import RuleRouter, Rule
router = RuleRouter(
rules=[
Rule(pattern=r"weather", handler="weather_agent", intent="weather"),
Rule(pattern=r"calendar|schedule", handler="calendar_agent", intent="calendar"),
],
default_handler="general_agent",
)
result = await router.classify("What's the weather?", ctx)
# intent="weather", confidence=1.0, handler="weather_agent"

2. Runtime — Agent Execution

Executes agent code in isolation, manages lifecycle, collects structured output.

Provided strategies:

StrategyIsolationUse case
InProcessRuntimeNone — runs in main processDevelopment, simple agents
SubprocessRuntimeProcess boundaryProduction, untrusted agents
ContainerRuntimeDocker/FirecrackerMaximum isolation

Built-in: timeout, circuit breaker, structured output parsing, error classification, streaming.

3. Tools — Discovery and Invocation

Discovers tools, sandboxes their execution, injects them into agent context.

Provided strategies:

StrategySourceUse case
FunctionToolManagerPlain functionsSimple tools, testing
MCPToolManagerMCP protocol serversProduction, sandboxed tools
CompositeToolManagerMultiple sources combinedMixed environments

Built-in: permission model, sandboxing, connection pooling, schema validation, result size limits.

4. Memory — Tiered Context Storage

Agents read from and write to tiered memory with automatic lifecycle management.

Tiers:

TierScopeStorage
HotCurrent session — conversation + working stateIn-memory / Redis
WarmRecent episodes and extracted factsKey-value store
ColdLong-term searchable knowledgeVector DB

Built-in: episode extraction, fact deduplication, tier promotion/demotion, token budget fitting, scope isolation.

5. Responder — Output Formatting

Takes raw agent output and formats it for the target channel.

Provided strategies:

StrategyBehavior
PassthroughResponderReturns raw output (APIs, programmatic consumers)
ToneResponderRewrites output with personality/tone
MultimodalResponderAttaches media, cards, buttons based on channel capabilities

6. Registry — Component Catalog

Unified catalog of everything in the system. Every other primitive queries it instead of implementing its own discovery.

Provided backends:

BackendPersistenceUse case
InMemoryRegistryNoneTesting, simple deployments
SqliteRegistryDiskSingle-node production
RedisRegistryDistributedMulti-node clusters

7. Policy — Governance

Layered rules that govern execution. Declarative defaults in config, per-agent overrides via decorators, runtime adaptation.

Provided strategies:

StrategyBehavior
NoopPolicyEngineAllow everything (development/testing)
YamlPolicyEngineLoad policies from nerva.yaml, evaluate at runtime
AdaptivePolicyEngineExtends YAML engine with runtime condition monitoring

Policy covers: rate limits, cost budgets, approval gates, safety screening, execution depth limits, circuit breakers.

Composition

The Orchestrator wires all 8 primitives together and threads ExecContext through the pipeline:

Message -> ExecContext -> Policy -> Router -> Runtime (Tools + Memory) -> Responder -> Output

But you do not need the Orchestrator. Use any primitive standalone, compose a subset, or build your own orchestration logic.