| Crates.io | mielin-cells |
| lib.rs | mielin-cells |
| version | 0.1.0-rc.1 |
| created_at | 2026-01-18 01:54:26.153592+00 |
| updated_at | 2026-01-18 01:54:26.153592+00 |
| description | Agent SDK providing agent lifecycle management, policy execution, and inter-agent communication |
| homepage | |
| repository | https://github.com/cool-japan/mielin |
| max_upload_size | |
| id | 2051574 |
| size | 1,046,885 |
Agent SDK - The Neurotransmitter (Layer 2)
Comprehensive SDK for creating, managing, and migrating autonomous AI agents in the MielinOS ecosystem. Mielin Cells provides the core abstractions that enable agents to traverse seamlessly across heterogeneous hardware—the computational "neurotransmitters" of the system.
Mielin Cells implements Layer 2 of the MielinOS architecture, providing complete agent lifecycle management, stateful migration capabilities, policy enforcement, and DNA (WebAssembly binary) management.
Current Status: v0.1.0-rc.1 "Oligodendrocyte" (Released 2026-01-18)
Layer 2 in the 5-layer neural architecture:
┌─────────────────────────────────────────────────────────────┐
│ Layer 2: Mielin Cells (The Neurotransmitter) │
│ • Agent Lifecycle Manager │
│ • DNA (WASM) Management │
│ • Migration Snapshot/Restore │
│ • Policy Enforcement Engine │
└─────────────────────────────────────────────────────────────┘
mielin-cells/
├── src/
│ ├── agent.rs # Agent lifecycle and state management
│ ├── dna.rs # WebAssembly binary (DNA) management
│ ├── migration.rs # Snapshot/restore and migration logic
│ ├── policy.rs # Execution policy definitions
│ └── lib.rs # Public API and error types
└── Cargo.toml
Add to your Cargo.toml:
[dependencies]
mielin-cells = { path = "../mielin-cells" }
use mielin_cells::Agent;
// Create agent with WASM binary
let wasm_binary = vec![0x00, 0x61, 0x73, 0x6d, /* ... */];
let agent = Agent::new(wasm_binary);
println!("Agent ID: {}", agent.id());
println!("State: {:?}", agent.state());
println!("DNA hash: {:x?}", agent.dna().hash());
use mielin_cells::migration::{MigrationSnapshot, MigrationManager};
let mut manager = MigrationManager::new();
// Phase 1: Initiate migration
let snapshot = manager.initiate_migration(
&agent,
Some(*target_node_id.as_bytes())
)?;
// Phase 2: Serialize for network transfer
let bytes = snapshot.serialize()?;
println!("Snapshot size: {} bytes", bytes.len());
// ... send over network (QUIC) ...
// Phase 3: Restore on target node
let restored_snapshot = MigrationSnapshot::deserialize(&bytes)?;
let restored_agent = restored_snapshot.restore()?;
// Verify integrity
assert_eq!(restored_agent.dna().hash(), agent.dna().hash());
The fundamental unit of computation in MielinOS—autonomous entities that can execute and migrate.
use mielin_cells::{Agent, AgentState};
let mut agent = Agent::new(wasm_binary);
// Lifecycle management
agent.set_state(AgentState::Running);
agent.set_state(AgentState::Suspended);
agent.set_state(AgentState::Migrating);
agent.set_state(AgentState::Terminated);
// Access components
let dna = agent.dna(); // Immutable WASM bytecode
let policy = agent.policy(); // Execution constraints
let id = agent.id(); // Content-addressable ID
pub enum AgentState {
Created, // Just created, not yet running
Running, // Actively executing on current node
Suspended, // Paused execution, can resume
Migrating, // In process of migration to another node
Terminated, // Execution completed or killed
}
State transitions:
Created → Running → Migrating → Running (on new node)
↓ ↓ ↓
Terminated ← Suspended → Running
Immutable code representation with content addressing for verification and deduplication.
use mielin_cells::Dna;
let dna = Dna::new(wasm_binary);
// Get binary content
let binary = dna.binary();
println!("WASM size: {} bytes", binary.len());
// Get content hash (SHA-256)
let hash = dna.hash();
println!("DNA hash: {:x?}", hash);
// Verify integrity after migration
fn verify_agent(original: &Agent, migrated: &Agent) -> bool {
original.dna().hash() == migrated.dna().hash()
}
DNA Features:
Complete migration workflow with checkpoint/restore support.
use mielin_cells::migration::{MigrationSnapshot, MigrationManager};
// Capture agent state
let snapshot = MigrationSnapshot::capture(&agent, None)?;
// Snapshot components
println!("Agent ID: {:x?}", snapshot.agent_id);
println!("WASM binary: {} bytes", snapshot.wasm_binary.len());
println!("WASM state: {} bytes", snapshot.wasm_state.len());
println!("Policy: {:?}", snapshot.policy);
println!("Timestamp: {}", snapshot.timestamp);
// Serialize to bytes (network transfer format)
let serialized = snapshot.serialize()?;
println!("Total snapshot: {} bytes", serialized.len());
// Deserialize on remote node
let restored = MigrationSnapshot::deserialize(&serialized)?;
// Restore agent
let new_agent = restored.restore()?;
assert_eq!(new_agent.id(), agent.id());
Migration Performance:
Tracks and manages pending migrations across the mesh:
let mut manager = MigrationManager::new();
// Start migration
let snapshot = manager.initiate_migration(&agent, target_node)?;
// Check status
println!("Pending migrations: {}", manager.pending_count());
// Complete migration (cleanup source)
manager.complete_migration(&agent_id);
// Or cancel if failed
manager.cancel_migration(&agent_id);
Define execution constraints and migration triggers for intelligent agent placement.
use mielin_cells::Policy;
let policy = Policy {
min_battery_percent: 20, // Don't run if battery < 20%
max_latency_ms: 100, // Prefer nodes with <100ms latency
preferred_architectures: vec!["aarch64".to_string(), "x86_64".to_string()],
};
let mut agent = Agent::new(wasm_binary);
agent.set_policy(policy);
// Check policy compliance
fn can_run_on_node(agent: &Agent, battery: u8, latency: u32, arch: &str) -> bool {
let p = agent.policy();
battery >= p.min_battery_percent &&
latency <= p.max_latency_ms &&
(p.preferred_architectures.is_empty() ||
p.preferred_architectures.contains(&arch.to_string()))
}
Policy Use Cases:
Agentpub struct Agent {
id: AgentId,
dna: Dna,
state: AgentState,
policy: Policy,
}
impl Agent {
pub fn new(wasm_binary: Vec<u8>) -> Self;
pub fn id(&self) -> AgentId;
pub fn state(&self) -> &AgentState;
pub fn set_state(&mut self, state: AgentState);
pub fn dna(&self) -> &Dna;
pub fn policy(&self) -> &Policy;
pub fn set_policy(&mut self, policy: Policy);
}
Dnapub struct Dna {
wasm_binary: Vec<u8>,
hash: [u8; 32], // SHA-256
}
impl Dna {
pub fn new(wasm_binary: Vec<u8>) -> Self;
pub fn binary(&self) -> &[u8];
pub fn hash(&self) -> &[u8; 32];
}
MigrationSnapshotpub struct MigrationSnapshot {
pub agent_id: [u8; 16], // UUID
pub wasm_binary: Vec<u8>, // WASM bytecode
pub wasm_state: Vec<u8>, // Linear memory snapshot
pub policy: Policy, // Execution policy
pub timestamp: u64, // Creation time (Unix epoch)
pub source_node: Option<[u8; 16]>, // Origin node ID
}
impl MigrationSnapshot {
pub fn capture(agent: &Agent, source: Option<[u8; 16]>)
-> Result<Self, CellError>;
pub fn restore(&self) -> Result<Agent, CellError>;
pub fn serialize(&self) -> Result<Vec<u8>, CellError>;
pub fn deserialize(data: &[u8]) -> Result<Self, CellError>;
pub fn size_bytes(&self) -> usize;
pub fn age_seconds(&self) -> u64;
}
MigrationManagerpub struct MigrationManager {
pending_migrations: HashMap<AgentId, MigrationSnapshot>,
}
impl MigrationManager {
pub fn new() -> Self;
pub fn initiate_migration(
&mut self,
agent: &Agent,
target: Option<[u8; 16]>,
) -> Result<MigrationSnapshot, CellError>;
pub fn complete_migration(&mut self, agent_id: &AgentId);
pub fn pending_count(&self) -> usize;
}
Policypub struct Policy {
pub min_battery_percent: u8,
pub max_latency_ms: u32,
pub preferred_architectures: Vec<String>,
}
impl Policy {
pub fn allows_low_battery(&self) -> bool;
pub fn default() -> Self; // Permissive defaults
}
use mielin_cells::{Agent, AgentState};
use mielin_cells::migration::{MigrationSnapshot, MigrationManager};
// === Source Node ===
let wasm = vec![/* WASM bytecode */];
let mut agent = Agent::new(wasm);
agent.set_state(AgentState::Running);
// Trigger migration (e.g., low battery)
let mut manager = MigrationManager::new();
let snapshot = manager.initiate_migration(&agent, Some(target_id))?;
agent.set_state(AgentState::Migrating);
// Serialize for network
let bytes = snapshot.serialize()?;
// === Network Transfer (QUIC) ===
// send_over_quic(bytes)?;
// === Target Node ===
let received_snapshot = MigrationSnapshot::deserialize(&bytes)?;
let mut migrated_agent = received_snapshot.restore()?;
migrated_agent.set_state(AgentState::Running);
// Verify integrity
assert_eq!(migrated_agent.dna().hash(), snapshot.wasm_binary[..32]);
// === Source Node (Cleanup) ===
manager.complete_migration(&agent.id());
agent.set_state(AgentState::Terminated);
use mielin_cells::{Agent, Policy};
// Define strict policy for production agent
let policy = Policy {
min_battery_percent: 30,
max_latency_ms: 50,
preferred_architectures: vec!["aarch64".to_string()],
};
let mut agent = Agent::new(wasm_binary);
agent.set_policy(policy);
// Node selection based on policy
struct NodeStatus {
battery: u8,
latency: u32,
arch: String,
}
fn select_node(agent: &Agent, nodes: &[NodeStatus]) -> Option<usize> {
let policy = agent.policy();
nodes.iter().position(|node| {
node.battery >= policy.min_battery_percent &&
node.latency <= policy.max_latency_ms &&
(policy.preferred_architectures.is_empty() ||
policy.preferred_architectures.contains(&node.arch))
})
}
let snapshot = MigrationSnapshot::capture(&agent, None)?;
println!("Snapshot Analysis:");
println!(" Agent ID: 16 bytes");
println!(" WASM binary: {} bytes", snapshot.wasm_binary.len());
println!(" WASM state: {} bytes", snapshot.wasm_state.len());
println!(" Policy: ~32 bytes");
println!(" Metadata: ~24 bytes");
println!(" Total: {} bytes", snapshot.size_bytes());
// Optimization strategies:
// 1. Minimize agent state (keep memory usage low)
// 2. Share DNA across agents (deduplicate bytecode)
// 3. Compress state (LZ4, coming in Phase 2)
// 4. Delta encoding (only changed pages, Phase 3)
pub enum CellError {
ExecutionFailed(String),
MigrationFailed(String),
InvalidState(String),
SerializationFailed(String),
DeserializationFailed(String),
}
impl std::fmt::Display for CellError { /* ... */ }
impl std::error::Error for CellError {}
All operations return Result<T, CellError> for explicit error handling.
Run the comprehensive test suite:
# All tests
cargo test -p mielin-cells
# Specific test
cargo test test_agent_migration
# With output
cargo test -- --nocapture
Test Coverage (39 tests, 100% pass rate):
Typical measurements on x86_64 (3.5 GHz):
| Operation | Time | Size | Notes |
|---|---|---|---|
| Agent creation | ~1 μs | 64 bytes | Overhead only |
| DNA hash (SHA-256) | ~0.5 μs/KB | - | For 1KB WASM |
| Snapshot creation | ~10 μs | Variable | Excludes WASM copy |
| Serialization | ~5 μs | +24 bytes | Overhead |
| Deserialization | ~5 μs | - | Plus allocation |
| Restoration | ~1 μs | - | Struct creation |
Snapshot Sizes:
// Good: Small, focused agents
struct SensorAgent {
reading: f32,
timestamp: u64,
}
// Avoid: Large, stateful agents
struct MonolithAgent {
history: Vec<f32>, // Grows unbounded
cache: HashMap<String, Vec<u8>>, // Large memory
}
// Define clear policies
let policy = Policy {
min_battery_percent: 20, // Reasonable threshold
max_latency_ms: 100, // Based on requirements
preferred_architectures: vec!["aarch64".to_string()],
};
// Not overly restrictive
let bad_policy = Policy {
min_battery_percent: 90, // Too strict
max_latency_ms: 1, // Unrealistic
preferred_architectures: vec!["very-specific-cpu".to_string()],
};
// Always verify DNA integrity
fn verify_migration(original: &Agent, migrated: &Agent) -> bool {
original.dna().hash() == migrated.dna().hash()
}
if !verify_migration(&original_agent, &restored_agent) {
panic!("Migration integrity check failed!");
}
match snapshot.restore() {
Ok(agent) => {
println!("Migration successful");
agent.set_state(AgentState::Running);
}
Err(e) => {
eprintln!("Migration failed: {}", e);
// Implement retry logic or fallback
}
}
let snapshot = MigrationSnapshot::capture(&agent, None)?;
if snapshot.age_seconds() > 60 {
println!("Warning: Snapshot is {} seconds old", snapshot.age_seconds());
// Consider re-capturing
}
See TODO.md for detailed roadmap.
See CONTRIBUTING.md for guidelines.
Key areas for contribution:
Licensed under either of:
at your option.
Mielin Cells - The neurotransmitters enabling autonomous agents to traverse the computational nervous system 🧠⚡
Current Version: v0.1.0-rc.1 "Oligodendrocyte" | Released 2026-01-18