{"_id":"@aigentic/edge","_rev":"2-63676a18d9ae4bae45a4ee234418796d","name":"@aigentic/edge","dist-tags":{"alpha":"0.1.9","latest":"0.1.9"},"versions":{"0.1.9":{"name":"@aigentic/edge","version":"0.1.9","keywords":["wasm","rust","ai","swarm","p2p","cryptography","post-quantum","hnsw","vector-search","neural-network","raft","consensus","ed25519","aes-gcm","webassembly","semantic-search","machine-learning"],"author":{"name":"RuVector Team"},"license":"MIT","_id":"@aigentic/edge@0.1.9","maintainers":[{"name":"aigentic","email":"engineering@aigentic.net"}],"homepage":"https://github.com/ruvnet/ruvector/tree/main/examples/edge","bugs":{"url":"https://github.com/ruvnet/ruvector/issues"},"dist":{"shasum":"7891ff7bbfe894efed2cd0456ae189598f7da918","tarball":"https://registry.npmjs.org/@aigentic/edge/-/edge-0.1.9.tgz","fileCount":10,"integrity":"sha512-Qf0uw+zn+gfynuXBF1RkEr+1fIxrEGEsgVvxnGNVgx9ySYdZE7OLo2Ej5uiJGP2rGEi0kozG0agg+oG0ymuYKQ==","signatures":[{"sig":"MEUCIQDlfWVq3fb+ZPrYGQolGU3Aw7o8IltdcZSX0bRIArXlPQIgMPo/Uj1POxZdxbwQUuNXNUwl4uzE6aMxrfFgw115EPc=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":565253},"main":"ruvector_edge.js","type":"module","types":"ruvector_edge.d.ts","module":"ruvector_edge.js","exports":{".":{"types":"./ruvector_edge.d.ts","import":"./ruvector_edge.js"},"./worker":{"import":"./worker.js"},"./worker-pool":{"import":"./worker-pool.js"}},"gitHead":"e2cb6210ce8d478b39cad81872a4aef78a05ceb4","_npmUser":{"name":"aigentic","email":"engineering@aigentic.net"},"repository":{"url":"git+https://github.com/ruvnet/ruvector.git","type":"git"},"_npmVersion":"11.12.0","description":"Free edge-based AI swarms in the browser - P2P, crypto, vector search, neural networks. Install @aigentic/edge-full for graph DB, SQL, ONNX embeddings.","directories":{},"sideEffects":["./snippets/*"],"_nodeVersion":"22.22.1","_hasShrinkwrap":false,"peerDependencies":{"@aigentic/edge-full":"^0.1.0"},"optionalDependencies":{"@aigentic/edge-full":"^0.1.0"},"peerDependenciesMeta":{"@aigentic/edge-full":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/edge_0.1.9_1779324102824_0.7859715609974431","host":"s3://npm-registry-packages-npm-production"}}},"time":{"created":"2026-05-21T00:41:42.685Z","modified":"2026-09-13T15:30:29.594Z","0.1.9":"2026-05-21T00:41:43.014Z"},"bugs":{"url":"https://github.com/ruvnet/ruvector/issues"},"author":{"name":"RuVector Team"},"license":"MIT","homepage":"https://github.com/ruvnet/ruvector/tree/main/examples/edge","keywords":["wasm","rust","ai","swarm","p2p","cryptography","post-quantum","hnsw","vector-search","neural-network","raft","consensus","ed25519","aes-gcm","webassembly","semantic-search","machine-learning"],"repository":{"url":"git+https://github.com/ruvnet/ruvector.git","type":"git"},"description":"Free edge-based AI swarms in the browser - P2P, crypto, vector search, neural networks. Install @aigentic/edge-full for graph DB, SQL, ONNX embeddings.","maintainers":[{"email":"engineering@aigentic.net","name":"aiggy"}],"readme":"# @aigentic/edge\n\n[![npm](https://img.shields.io/npm/v/@aigentic/edge.svg)](https://www.npmjs.com/package/@aigentic/edge)\n[![Rust](https://img.shields.io/badge/rust-1.75%2B-orange.svg)](https://www.rust-lang.org/)\n[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)\n[![WASM](https://img.shields.io/badge/wasm-364KB-purple.svg)]()\n[![Tests](https://img.shields.io/badge/tests-60%20passing-brightgreen.svg)]()\n\n## Free Self-Learning AI Swarms at the Edge\n\n**Build and deploy self-optimizing AI agent swarms that run entirely in web browsers, mobile devices, and edge servers - without paying for cloud infrastructure.**\n\nImagine having dozens of AI agents working together - analyzing data, routing tasks, making decisions, and getting smarter with every interaction - all running directly in your users' browsers. No API costs. No server bills. No data leaving your network. That's what @aigentic/edge makes possible.\n\nThis library gives you everything you need to build distributed AI systems: cryptographic identity for each agent, encrypted communication between them, lightning-fast vector search for finding the right agent for each task, consensus protocols so your agents can coordinate without a central server, and self-learning neural networks that continuously optimize agent routing based on real-world outcomes. It's all compiled to a tiny 364KB WebAssembly binary that runs anywhere JavaScript runs.\n\n**The key insight:** Instead of paying cloud providers to run your AI infrastructure, you use the computing power that's already there - your users' devices. Each browser becomes a node in your swarm. The more users you have, the more powerful your system becomes - and with built-in self-learning capabilities (LoRA fine-tuning, EWC++ continual learning, ReasoningBank experience replay), your swarm gets smarter over time while still costing you nothing.\n\n```\n┌─────────────────────────────────────────────────────────────────────┐\n│                         ZERO COST SWARMS                            │\n├─────────────────────────────────────────────────────────────────────┤\n│                                                                     │\n│   ┌─────────┐      ┌─────────┐      ┌─────────┐      ┌─────────┐   │\n│   │ Browser │◄────►│ Browser │◄────►│  Edge   │◄────►│  Mobile │   │\n│   │ Agent A │      │ Agent B │      │ Agent C │      │ Agent D │   │\n│   └─────────┘      └─────────┘      └─────────┘      └─────────┘   │\n│        │                │                │                │        │\n│        └────────────────┴────────────────┴────────────────┘        │\n│                              P2P Mesh                               │\n│                                                                     │\n│   Compute: FREE (runs on user devices)                              │\n│   Network: FREE (public relays + P2P)                               │\n│   Storage: FREE (distributed across nodes)                          │\n│   Scale:   UNLIMITED (each user = new node)                         │\n│                                                                     │\n└─────────────────────────────────────────────────────────────────────┘\n```\n\n### What You Get\n\n| Capability | Technology | Performance |\n|------------|------------|-------------|\n| **Agent Identity** | Ed25519 signatures | 50,000 ops/sec |\n| **Encryption** | AES-256-GCM | 1 GB/sec |\n| **Vector Search** | HNSW index | 150x faster than brute force |\n| **Task Routing** | Semantic LSH | Sub-millisecond |\n| **Trusted Consensus** | Raft protocol | For stable cohorts (teams, rooms) |\n| **Open Swarm** | Gossip + CRDT | High-churn, Byzantine-tolerant |\n| **Post-Quantum** | Hybrid signatures | Future-proof |\n| **Neural Networks** | Spiking + STDP | Bio-inspired learning |\n| **Compression** | Adaptive 4-32x | Network-aware |\n| **Web Workers** | Worker pool | Parallel ops, non-blocking UI |\n\n### What It Costs\n\n| Component | Cloud Solution | @aigentic/edge |\n|-----------|---------------|----------------|\n| Compute | $200-500/month | **$0** (user's CPU) |\n| Vector DB | $100-300/month | **$0** (in-browser HNSW) |\n| Encryption | $50-100/month | **$0** (built-in AES) |\n| Bandwidth | $0.09/GB | **$0** (P2P direct) |\n| Consensus | $100-200/month | **$0** (built-in Raft) |\n| **Total** | **$450-1100/month** | **$0/month** |\n\n---\n\n## Full Platform Capabilities\n\nRuVector provides a complete edge AI platform. This package (`@aigentic/edge`) is the lightweight core. For the full toolkit, install `@aigentic/edge-full`.\n\n```\n┌─────────────────────────────────────────────────────────────────────────────┐\n│                        RUVECTOR EDGE PLATFORM                               │\n├─────────────────────────────────────────────────────────────────────────────┤\n│                                                                             │\n│  @aigentic/edge (364KB)              @aigentic/edge-full (+8MB)             │\n│  ─────────────────────               ───────────────────────────            │\n│  ✓ Ed25519 Identity                  Everything in edge, PLUS:              │\n│  ✓ AES-256-GCM Encryption                                                   │\n│  ✓ HNSW Vector Search                ✓ Graph DB (288KB)                     │\n│  ✓ Semantic Task Routing               Neo4j-style API, Cypher queries      │\n│  ✓ Raft (trusted cohorts)              Relationship modeling, traversals    │\n│  ✓ Gossip + CRDT (open swarms)                                              │\n│  ✓ Post-Quantum Crypto               ✓ RVLite Vector DB (260KB)             │\n│  ✓ Spiking Neural Networks             SQL + SPARQL + Cypher queries        │\n│  ✓ Adaptive Compression                IndexedDB persistence                │\n│  ✓ Web Worker Pool                                                          │\n│                                                                             │\n│  Best for:                           ✓ SONA Neural Router (238KB)           │\n│  • Lightweight P2P apps                Self-learning with LoRA              │\n│  • Secure messaging                    EWC++ continual learning             │\n│  • Trusted team swarms                 ReasoningBank experience replay      │\n│  • Mobile/embedded                                                          │\n│                                                                             │\n│                                      ✓ DAG Workflows (132KB)                │\n│                                        Task orchestration                   │\n│                                        Dependency resolution                │\n│                                        Topological execution                │\n│                                                                             │\n│                                      ✓ ONNX Embeddings (7.1MB)              │\n│                                        6 HuggingFace models                 │\n│                                        3.8x parallel speedup                │\n│                                        MiniLM, BGE, E5, GTE                 │\n│                                                                             │\n│                                      Best for:                              │\n│                                      • Full RAG pipelines                   │\n│                                      • Knowledge graphs                     │\n│                                      • Self-learning agents                 │\n│                                      • Complex workflows                    │\n│                                                                             │\n└─────────────────────────────────────────────────────────────────────────────┘\n```\n\n### Choose Your Package\n\n```bash\n# Lightweight core (364KB) - P2P, crypto, vectors, consensus\nnpm install @aigentic/edge\n\n# Full platform (8.4MB) - adds graph DB, SQL, neural routing, ONNX\nnpm install @aigentic/edge-full\n```\n\n### Using Both Together\n\n```javascript\n// Start with edge core\nimport init, { WasmIdentity, WasmHnswIndex } from '@aigentic/edge';\n\n// Add full capabilities when needed\nimport { graph, rvlite, sona, dag } from '@aigentic/edge-full';\nimport onnxInit from '@aigentic/edge-full/onnx';\n```\n\n---\n\n### Consensus Modes: Trusted vs Open\n\nRuVector provides two coordination strategies for different deployment scenarios:\n\n| Mode | Protocol | When to Use |\n|------|----------|-------------|\n| **Trusted Cohort** | Raft | Private teams, enterprise LANs, known membership, low churn |\n| **Open Swarm** | Gossip + CRDT | Public networks, anonymous browsers, high churn, adversarial environments |\n\n```javascript\n// Trusted cohort (Raft) - stable team of 3-7 nodes\nconst raftNode = new WasmRaftNode('node-1', ['node-1', 'node-2', 'node-3']);\nraftNode.start_election();  // Leader election for consistent state\n\n// Open swarm (Gossip + CRDT) - dynamic browser mesh\nconst gossipNode = new WasmGossipNode(identity);\ngossipNode.join_swarm(relayUrl);  // Eventually consistent, Byzantine-tolerant\n```\n\n**Why two modes?** Raft assumes known membership and trusted nodes - perfect for your dev team or enterprise deployment. But a public browser swarm has nodes joining/leaving constantly and can't trust everyone. Gossip protocols with CRDTs handle this gracefully: no leader election, no membership tracking, eventual consistency that converges even with malicious actors.\n\n---\n\n### Web Workers: Keep the UI Responsive\n\nHeavy operations (vector search, encryption, neural network inference) run in Web Workers to avoid blocking the main thread. The package includes a ready-to-use worker pool:\n\n```javascript\nimport { WorkerPool } from '@aigentic/edge/worker-pool';\n\n// Create worker pool (auto-detects CPU cores)\nconst pool = new WorkerPool(\n  new URL('@aigentic/edge/worker', import.meta.url),\n  new URL('@aigentic/edge/ruvector_edge_bg.wasm', import.meta.url),\n  {\n    poolSize: navigator.hardwareConcurrency,\n    dimensions: 384,\n    useHnsw: true\n  }\n);\n\nawait pool.init();\n\n// Operations run in parallel across workers\nawait pool.insert(embedding, 'doc-1', { title: 'Hello' });\nawait pool.insertBatch([\n  { vector: emb1, id: 'doc-2' },\n  { vector: emb2, id: 'doc-3' },\n  { vector: emb3, id: 'doc-4' }\n]);\n\n// Search distributed across workers\nconst results = await pool.search(queryEmbedding, 10);\n\n// Batch search (each query on different worker)\nconst batchResults = await pool.searchBatch([query1, query2, query3], 10);\n\n// Pool statistics\nconsole.log(pool.getStats());\n// { poolSize: 8, busyWorkers: 2, idleWorkers: 6, pendingRequests: 0 }\n\n// Clean up\npool.terminate();\n```\n\n**Worker Pool Features:**\n- Round-robin task distribution with load balancing\n- Automatic batch splitting across workers\n- Promise-based API with 30s timeout\n- Zero-copy transfers via transferable objects\n- Works in browsers, Deno, and Cloudflare Workers\n\n---\n\n### Quick Start\n\n```bash\nnpm install @aigentic/edge\n```\n\n```javascript\nimport init, { WasmIdentity, WasmHnswIndex, WasmSemanticMatcher } from '@aigentic/edge';\n\nawait init();\n\n// Create agent identity\nconst identity = WasmIdentity.generate();\nconsole.log(`Agent: ${identity.agent_id()}`);\n\n// Vector search (150x faster)\nconst index = new WasmHnswIndex(128, 16, 200);\nindex.insert(\"agent-1\", new Float32Array(128));\n\n// Semantic task routing\nconst matcher = new WasmSemanticMatcher();\nmatcher.register_agent(\"coder\", \"rust typescript javascript\");\nconst best = matcher.find_best_agent(\"write a function\");\n```\n\n---\n\n## Table of Contents\n\n1. [Why Edge-First?](#why-edge-first)\n2. [Features](#features)\n3. [Tutorial: Build Your First Swarm](#tutorial-build-your-first-swarm)\n4. [P2P Transport Options](#p2p-transport-options)\n5. [Free Infrastructure](#free-infrastructure-zero-cost-at-any-scale)\n6. [Architecture](#architecture)\n7. [API Reference](#api-reference)\n8. [Performance](#performance)\n9. [Security](#security)\n\n---\n\n## Why Edge-First?\n\n| Traditional Cloud Swarms | RuVector Edge Swarms |\n|--------------------------|---------------------|\n| Pay per API call | **Free forever** |\n| Data leaves your network | **Data stays local** |\n| Central point of failure | **Fully distributed** |\n| Vendor lock-in | **Open source** |\n| High latency (round-trip to cloud) | **Sub-millisecond (peer-to-peer)** |\n| Limited by server capacity | **Scales with your devices** |\n\n### The Economics of Edge AI\n\n```\nCloud AI Swarm (10 agents, 1M operations/month):\n├── API calls:        $500-2000/month\n├── Compute:          $200-500/month\n├── Bandwidth:        $50-100/month\n└── Total:            $750-2600/month\n\nRuVector Edge Swarm:\n├── Infrastructure:   $0\n├── API calls:        $0\n├── Bandwidth:        $0 (P2P)\n└── Total:            $0/month forever\n```\n\n### How Is It Free?\n\nThe code runs on devices you already own - there's no server to pay for:\n\n```\nTraditional Architecture:\n┌──────────┐     ┌─────────────────┐     ┌──────────┐\n│ Agent A  │────►│  Cloud Server   │◄────│ Agent B  │\n└──────────┘     │  ($$$$/month)   │     └──────────┘\n                 └─────────────────┘\n\nEdge Architecture:\n┌──────────┐◄───────────────────────────►┌──────────┐\n│ Agent A  │         Direct P2P          │ Agent B  │\n│ (Browser)│         Connection          │ (Browser)│\n└──────────┘                             └──────────┘\n                 No server = No cost\n```\n\n---\n\n## Features\n\n| Feature | Description |\n|---------|-------------|\n| **Ed25519 Identity** | Cryptographic agent identity with signing |\n| **AES-256-GCM** | Authenticated encryption for all messages |\n| **Post-Quantum Hybrid** | Future-proof against quantum attacks |\n| **HNSW Vector Index** | 150x faster similarity search |\n| **Semantic Matching** | Intelligent task-to-agent routing |\n| **Raft Consensus** | Distributed leader election |\n| **Spiking Networks** | Bio-inspired temporal learning |\n| **Adaptive Compression** | Network-aware bandwidth optimization |\n\n---\n\n## Quick Start\n\n### Installation\n\n```bash\nnpm install @aigentic/edge\n```\n\n### Basic Usage\n\n```javascript\nimport init, {\n  WasmIdentity,\n  WasmCrypto,\n  WasmHnswIndex,\n  WasmSemanticMatcher\n} from '@aigentic/edge';\n\n// Initialize WASM (required once)\nawait init();\n\n// Create an agent\nconst agent = WasmIdentity.generate();\nconsole.log(`Agent: ${agent.agent_id()}`);\n\n// Encrypt a message\nconst crypto = new WasmCrypto();\nconst key = crypto.generate_key();\nconst encrypted = crypto.encrypt(key, new TextEncoder().encode(\"Hello swarm!\"));\n\n// Search vectors\nconst index = new WasmHnswIndex(128, 16, 200);\nindex.insert(\"doc-1\", new Float32Array(128).fill(0.5));\nconst results = index.search(new Float32Array(128).fill(0.5), 5);\n\n// Route tasks\nconst matcher = new WasmSemanticMatcher();\nmatcher.register_agent(\"coder\", \"rust typescript javascript\");\nconst best = matcher.find_best_agent(\"write a function\");\n```\n\n---\n\n## Tutorial: Build Your First Swarm\n\nThis tutorial walks you through building a complete AI agent swarm that runs entirely in browsers with no backend.\n\n### Prerequisites\n\n```bash\nmkdir my-swarm && cd my-swarm\nnpm init -y\nnpm install @aigentic/edge\n```\n\nCreate `index.html`:\n\n```html\n<!DOCTYPE html>\n<html>\n<head><title>My AI Swarm</title></head>\n<body>\n  <div id=\"status\"></div>\n  <script type=\"module\" src=\"swarm.js\"></script>\n</body>\n</html>\n```\n\n---\n\n### Step 1: Agent Identity\n\nEvery agent needs a unique cryptographic identity. This enables signing messages and verifying authenticity.\n\nCreate `swarm.js`:\n\n```javascript\nimport init, { WasmIdentity } from '@aigentic/edge';\n\nasync function createAgent(name) {\n  await init();\n\n  // Generate Ed25519 keypair\n  const identity = WasmIdentity.generate();\n\n  console.log(`Agent: ${name}`);\n  console.log(`  ID: ${identity.agent_id()}`);\n  console.log(`  Public Key: ${identity.public_key_hex().slice(0, 16)}...`);\n\n  return identity;\n}\n\n// Create our agent\nconst myAgent = await createAgent(\"Worker-001\");\n\n// Sign a message to prove identity\nconst message = new TextEncoder().encode(\"I am Worker-001\");\nconst signature = myAgent.sign(message);\nconsole.log(`  Signature: ${signature.slice(0, 8).join(',')}...`);\n\n// Verify the signature\nconst isValid = myAgent.verify(message, signature);\nconsole.log(`  Valid: ${isValid}`); // true\n```\n\n**What's happening:**\n- `WasmIdentity.generate()` creates an Ed25519 keypair\n- `agent_id()` returns a unique identifier derived from the public key\n- `sign()` creates a cryptographic signature proving the message came from this agent\n- `verify()` checks if a signature is valid\n\n---\n\n### Step 2: Secure Communication\n\nAgents need to encrypt messages so only intended recipients can read them.\n\n```javascript\nimport init, { WasmIdentity, WasmCrypto } from '@aigentic/edge';\n\nawait init();\n\nconst crypto = new WasmCrypto();\n\n// Agent A wants to send a secret message to Agent B\nconst agentA = WasmIdentity.generate();\nconst agentB = WasmIdentity.generate();\n\n// Generate a shared secret key (in real app, use key exchange)\nconst sharedKey = crypto.generate_key();\n\n// Agent A encrypts\nconst plaintext = new TextEncoder().encode(JSON.stringify({\n  task: \"analyze_data\",\n  payload: { dataset: \"sales_2024.csv\" }\n}));\n\nconst ciphertext = crypto.encrypt(sharedKey, plaintext);\nconsole.log(`Encrypted: ${ciphertext.length} bytes`);\n\n// Agent B decrypts\nconst decrypted = crypto.decrypt(sharedKey, ciphertext);\nconst message = JSON.parse(new TextDecoder().decode(decrypted));\nconsole.log(`Decrypted: ${message.task}`); // \"analyze_data\"\n```\n\n**Security features:**\n- AES-256-GCM authenticated encryption\n- Random nonce per message (replay protection)\n- Ciphertext integrity verification\n\n---\n\n### Step 3: Vector Search\n\nAgents need to find each other based on capabilities. HNSW enables fast similarity search.\n\n```javascript\nimport init, { WasmHnswIndex } from '@aigentic/edge';\n\nawait init();\n\n// Create index: 128 dimensions, M=16 connections, ef=200 search quality\nconst index = new WasmHnswIndex(128, 16, 200);\n\n// Register agents with their capability embeddings\n// (In production, use real embeddings from a model)\nfunction mockEmbedding(weights) {\n  const vec = new Float32Array(128);\n  weights.forEach((w, i) => vec[i] = w);\n  return vec;\n}\n\n// Register specialized agents\nindex.insert(\"rust-expert\", mockEmbedding([0.9, 0.1, 0.0, 0.0]));\nindex.insert(\"python-expert\", mockEmbedding([0.1, 0.9, 0.0, 0.0]));\nindex.insert(\"ml-expert\", mockEmbedding([0.0, 0.5, 0.9, 0.0]));\nindex.insert(\"devops-expert\", mockEmbedding([0.0, 0.0, 0.2, 0.9]));\n\nconsole.log(`Index size: ${index.len()} agents`);\n\n// Find best agent for a Rust task\nconst rustTask = mockEmbedding([0.85, 0.1, 0.05, 0.0]);\nconst results = index.search(rustTask, 3);\n\nconsole.log(\"Best agents for Rust task:\");\nresults.forEach(([id, distance]) => {\n  console.log(`  ${id}: distance=${distance.toFixed(3)}`);\n});\n// Output: rust-expert: distance=0.050\n```\n\n**Why HNSW?**\n- O(log n) search instead of O(n)\n- 150x faster than brute force at 10K+ vectors\n- Memory-efficient graph structure\n\n---\n\n### Step 4: Task Routing\n\nRoute tasks to the best agent using semantic matching.\n\n```javascript\nimport init, { WasmSemanticMatcher } from '@aigentic/edge';\n\nawait init();\n\nconst matcher = new WasmSemanticMatcher();\n\n// Register agents with capability descriptions\nmatcher.register_agent(\"code-agent\",\n  \"rust typescript javascript python programming coding functions classes\");\nmatcher.register_agent(\"data-agent\",\n  \"python pandas numpy data analysis statistics csv excel\");\nmatcher.register_agent(\"devops-agent\",\n  \"docker kubernetes terraform aws deploy infrastructure cicd\");\nmatcher.register_agent(\"writing-agent\",\n  \"documentation markdown readme technical writing blog\");\n\nconsole.log(`Registered ${matcher.agent_count()} agents`);\n\n// Route tasks to best agent\nconst tasks = [\n  \"Write a Rust function to parse JSON\",\n  \"Analyze the sales data in this CSV\",\n  \"Deploy the app to Kubernetes\",\n  \"Update the API documentation\"\n];\n\ntasks.forEach(task => {\n  const best = matcher.find_best_agent(task);\n  console.log(`\"${task.slice(0, 30)}...\" → ${best}`);\n});\n\n// Output:\n// \"Write a Rust function...\" → code-agent\n// \"Analyze the sales data...\" → data-agent\n// \"Deploy the app to Kube...\" → devops-agent\n// \"Update the API documen...\" → writing-agent\n```\n\n**How it works:**\n- LSH (Locality-Sensitive Hashing) creates semantic fingerprints\n- Tasks are matched to agents by fingerprint similarity\n- Sub-millisecond routing even with many agents\n\n---\n\n### Step 5: Distributed Consensus\n\nWhen multiple agents need to agree on a leader or shared state, use Raft consensus.\n\n```javascript\nimport init, { WasmRaftNode } from '@aigentic/edge';\n\nawait init();\n\n// Create a 3-node cluster\nconst members = [\"node-1\", \"node-2\", \"node-3\"];\n\nconst node1 = new WasmRaftNode(\"node-1\", members);\nconst node2 = new WasmRaftNode(\"node-2\", members);\nconst node3 = new WasmRaftNode(\"node-3\", members);\n\nconsole.log(`Node 1 state: ${node1.state()}`); // \"follower\"\nconsole.log(`Node 1 term: ${node1.current_term()}`); // 0\n\n// Node 1 times out and starts election\nconst voteRequest = node1.start_election();\nconsole.log(`Node 1 state: ${node1.state()}`); // \"candidate\"\nconsole.log(`Node 1 term: ${node1.current_term()}`); // 1\n\n// Simulate: Node 2 and 3 grant votes\n// (In real app, send voteRequest over network, receive responses)\nconst granted1 = node1.receive_vote(true);\nconst granted2 = node1.receive_vote(true);\n\nconsole.log(`Node 1 state: ${node1.state()}`); // \"leader\"\n\n// Leader can now coordinate the swarm!\nconsole.log(\"Leader elected - swarm can coordinate\");\n```\n\n**Raft guarantees:**\n- Only one leader at a time\n- Leader election in 1-2 round trips\n- Tolerates f failures in 2f+1 nodes\n\n---\n\n## P2P Transport Options\n\nRuVector Edge provides the intelligence layer. You need a transport layer for agents to communicate. Here are your free options:\n\n### Architecture Overview\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│                    @aigentic/edge (WASM)                    │\n│  Identity, Crypto, HNSW, Semantic Matching, Raft, etc.      │\n└─────────────────────────────────────────────────────────────┘\n                              │\n                    Transport Layer (choose one)\n                              │\n        ┌─────────────────────┼─────────────────────┐\n        ▼                     ▼                     ▼\n   ┌─────────┐          ┌─────────┐          ┌─────────┐\n   │ WebRTC  │          │  GUN.js │          │  IPFS/  │\n   │  (P2P)  │          │  (P2P)  │          │ libp2p  │\n   └─────────┘          └─────────┘          └─────────┘\n```\n\n---\n\n### Option 1: WebRTC (Browser-to-Browser)\n\n**Best for:** Direct browser-to-browser communication\n**Cost:** Free (need minimal signaling server)\n\n```javascript\nimport init, { WasmIdentity, WasmCrypto } from '@aigentic/edge';\n\nawait init();\n\nconst identity = WasmIdentity.generate();\nconst crypto = new WasmCrypto();\n\n// Create peer connection\nconst pc = new RTCPeerConnection({\n  iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] // Free STUN\n});\n\n// Create data channel for agent messages\nconst channel = pc.createDataChannel('swarm');\n\nchannel.onopen = () => {\n  console.log('P2P connection established!');\n\n  // Send encrypted message\n  const key = crypto.generate_key(); // Exchange via signaling\n  const message = { type: 'task', data: 'analyze this' };\n  const encrypted = crypto.encrypt(key,\n    new TextEncoder().encode(JSON.stringify(message))\n  );\n\n  channel.send(encrypted);\n};\n\nchannel.onmessage = (event) => {\n  const decrypted = crypto.decrypt(key, new Uint8Array(event.data));\n  const message = JSON.parse(new TextDecoder().decode(decrypted));\n  console.log('Received:', message);\n};\n\n// Signaling (exchange offer/answer via any method)\nconst offer = await pc.createOffer();\nawait pc.setLocalDescription(offer);\n// Send offer to peer via signaling server, WebSocket, or even QR code\n```\n\n**Free signaling options:**\n- PeerJS Cloud (free tier)\n- Firebase Realtime Database (free tier)\n- Your own WebSocket on Fly.io/Railway free tier\n\n---\n\n### Option 2: GUN.js (Decentralized Database)\n\n**Best for:** Real-time sync, offline-first, no server needed\n**Cost:** Completely free (public relay network)\n\n```javascript\nimport init, { WasmIdentity, WasmSemanticMatcher } from '@aigentic/edge';\nimport Gun from 'gun';\n\nawait init();\n\nconst identity = WasmIdentity.generate();\nconst matcher = new WasmSemanticMatcher();\n\n// Connect to public GUN relays (free!)\nconst gun = Gun(['https://gun-manhattan.herokuapp.com/gun']);\n\n// Create swarm namespace\nconst swarm = gun.get('my-ai-swarm');\n\n// Register this agent\nswarm.get('agents').get(identity.agent_id()).put({\n  id: identity.agent_id(),\n  capabilities: 'rust typescript programming',\n  publicKey: identity.public_key_hex(),\n  online: true,\n  timestamp: Date.now()\n});\n\n// Listen for new agents\nswarm.get('agents').map().on((agent, id) => {\n  if (agent && agent.id !== identity.agent_id()) {\n    console.log(`Discovered agent: ${agent.id}`);\n    matcher.register_agent(agent.id, agent.capabilities);\n  }\n});\n\n// Publish tasks\nswarm.get('tasks').set({\n  id: crypto.randomUUID(),\n  description: 'Write a Rust function',\n  from: identity.agent_id(),\n  timestamp: Date.now()\n});\n\n// Listen for tasks\nswarm.get('tasks').map().on((task) => {\n  if (task) {\n    const bestAgent = matcher.find_best_agent(task.description);\n    if (bestAgent === identity.agent_id()) {\n      console.log(`I should handle: ${task.description}`);\n    }\n  }\n});\n```\n\n**Why GUN?**\n- No server required - uses public relays\n- Offline-first with automatic sync\n- Real-time updates via WebSocket\n- Already integrated in RuVector Edge (Rust side)\n\n---\n\n### Option 3: IPFS + libp2p\n\n**Best for:** Content-addressed storage + P2P messaging\n**Cost:** Free (self-host) or free tier (Pinata, Infura)\n\n```javascript\nimport init, { WasmIdentity, WasmCrypto } from '@aigentic/edge';\nimport { createLibp2p } from 'libp2p';\nimport { webSockets } from '@libp2p/websockets';\nimport { noise } from '@chainsafe/libp2p-noise';\nimport { gossipsub } from '@chainsafe/libp2p-gossipsub';\n\nawait init();\n\nconst identity = WasmIdentity.generate();\nconst crypto = new WasmCrypto();\n\n// Create libp2p node\nconst node = await createLibp2p({\n  transports: [webSockets()],\n  connectionEncryption: [noise()],\n  pubsub: gossipsub()\n});\n\nawait node.start();\n\n// Subscribe to swarm topic\nconst topic = 'my-ai-swarm';\n\nnode.pubsub.subscribe(topic);\nnode.pubsub.addEventListener('message', (event) => {\n  if (event.detail.topic === topic) {\n    const message = JSON.parse(new TextDecoder().decode(event.detail.data));\n    console.log('Received:', message);\n  }\n});\n\n// Publish to swarm\nnode.pubsub.publish(topic, new TextEncoder().encode(JSON.stringify({\n  from: identity.agent_id(),\n  type: 'announce',\n  capabilities: ['rust', 'wasm']\n})));\n```\n\n**IPFS for artifacts:**\n\n```javascript\nimport { create } from 'ipfs-http-client';\n\n// Use free Infura IPFS gateway\nconst ipfs = create({ url: 'https://ipfs.infura.io:5001' });\n\n// Store agent output\nconst result = await ipfs.add(JSON.stringify({\n  task: 'analyze-data',\n  output: { summary: '...' },\n  agent: identity.agent_id(),\n  signature: identity.sign(...)\n}));\n\nconsole.log(`Stored at: ipfs://${result.cid}`);\n\n// Share CID with swarm - anyone can fetch\n```\n\n---\n\n### Option 4: Nostr Relays\n\n**Best for:** Simple pub/sub with free public infrastructure\n**Cost:** Free (many public relays)\n\n```javascript\nimport init, { WasmIdentity } from '@aigentic/edge';\nimport { relayInit, getEventHash, signEvent } from 'nostr-tools';\n\nawait init();\n\nconst identity = WasmIdentity.generate();\n\n// Connect to free public relay\nconst relay = relayInit('wss://relay.damus.io');\nawait relay.connect();\n\n// Create Nostr event (signed message)\nconst event = {\n  kind: 29000, // Custom kind for AI swarm\n  created_at: Math.floor(Date.now() / 1000),\n  tags: [['swarm', 'my-ai-swarm']],\n  content: JSON.stringify({\n    agentId: identity.agent_id(),\n    type: 'task',\n    data: 'Write a function'\n  })\n};\n\n// Sign with identity (Nostr uses secp256k1, so bridge needed)\n// Or use Nostr's native keys alongside RuVector identity\n\n// Subscribe to swarm events\nconst sub = relay.sub([\n  { kinds: [29000], '#swarm': ['my-ai-swarm'] }\n]);\n\nsub.on('event', (event) => {\n  const message = JSON.parse(event.content);\n  console.log(`From ${message.agentId}: ${message.type}`);\n});\n```\n\n---\n\n### Transport Comparison\n\n| Transport | Latency | Offline | Complexity | Best For |\n|-----------|---------|---------|------------|----------|\n| **WebRTC** | ~50ms | No | Medium | Real-time, gaming |\n| **GUN.js** | ~100ms | Yes | Low | General purpose |\n| **IPFS/libp2p** | ~200ms | Partial | High | Content storage |\n| **Nostr** | ~150ms | No | Low | Simple messaging |\n\n### Recommended: Start with GUN.js\n\n```bash\nnpm install gun @aigentic/edge\n```\n\nGUN requires zero setup, works offline, and has a free public relay network.\n\n---\n\n## Free Infrastructure (Zero Cost at Any Scale)\n\nThe entire stack can run for **$0/month** using public infrastructure:\n\n### Free GUN Relays (Unlimited)\n\n```javascript\nconst gun = Gun([\n  'https://gun-manhattan.herokuapp.com/gun',\n  'https://gun-us.herokuapp.com/gun',\n  'https://gunjs.herokuapp.com/gun',\n  'https://gun-eu.herokuapp.com/gun'\n]);\n// No signup, no limits, community-run\n```\n\n### Free STUN Servers (WebRTC)\n\n```javascript\nconst rtcConfig = {\n  iceServers: [\n    { urls: 'stun:stun.l.google.com:19302' },      // Google\n    { urls: 'stun:stun1.l.google.com:19302' },     // Google\n    { urls: 'stun:stun.cloudflare.com:3478' },     // Cloudflare\n    { urls: 'stun:stun.services.mozilla.com' },    // Mozilla\n    { urls: 'stun:stun.stunprotocol.org:3478' }    // Open source\n  ]\n};\n// Unlimited, no account needed\n```\n\n### Free TURN Servers (NAT Traversal)\n\n| Provider | Free Tier | Signup |\n|----------|-----------|--------|\n| **Metered.ca** | 500MB/month | Yes |\n| **Xirsys** | 500MB/month | Yes |\n| **Twilio** | $15 free credit | Yes |\n| **OpenRelay** | Unlimited | No |\n\n### Free Signaling Services\n\n| Service | Free Tier | Best For |\n|---------|-----------|----------|\n| **PeerJS Cloud** | Unlimited connections | WebRTC signaling |\n| **Firebase Realtime** | 1GB storage, 10GB/month | Real-time sync |\n| **Supabase Realtime** | 500MB, unlimited connections | PostgreSQL + realtime |\n| **Ably** | 6M messages/month | Pub/sub |\n| **Pusher** | 200K messages/day | Simple messaging |\n\n### Free Nostr Relays (Unlimited)\n\n```javascript\nconst NOSTR_RELAYS = [\n  'wss://relay.damus.io',\n  'wss://nos.lol',\n  'wss://relay.nostr.band',\n  'wss://nostr.wine',\n  'wss://relay.snort.social'\n];\n// No signup, no limits, decentralized\n```\n\n### Free Self-Hosting\n\n| Platform | Free Tier | Use Case |\n|----------|-----------|----------|\n| **Fly.io** | 3 shared VMs, 160GB transfer | GUN/WebSocket relay |\n| **Railway** | $5 credit/month | Any relay |\n| **Render** | 750 hours/month | Static + WebSocket |\n| **Cloudflare Workers** | 100K requests/day | Edge signaling |\n| **Deno Deploy** | 1M requests/month | Edge relay |\n| **Vercel Edge** | 1M invocations/month | Signaling |\n\n### Complete Free Stack Example\n\n```javascript\nimport init, { WasmIdentity, WasmSemanticMatcher } from '@aigentic/edge';\nimport Gun from 'gun';\n\nawait init();\n\n// 1. Free GUN relays (unlimited scale)\nconst gun = Gun(['https://gun-manhattan.herokuapp.com/gun']);\n\n// 2. Free WebRTC STUN (unlimited)\nconst rtcConfig = {\n  iceServers: [\n    { urls: 'stun:stun.l.google.com:19302' },\n    { urls: 'stun:stun.cloudflare.com:3478' }\n  ]\n};\n\n// 3. Your swarm - $0/month forever\nconst identity = WasmIdentity.generate();\nconst matcher = new WasmSemanticMatcher();\nconst swarm = gun.get('my-ai-swarm');\n\n// Register agent\nswarm.get('agents').get(identity.agent_id()).put({\n  id: identity.agent_id(),\n  capabilities: 'coding analysis research',\n  publicKey: identity.public_key_hex(),\n  online: true\n});\n\n// Discover other agents\nswarm.get('agents').map().on((agent, id) => {\n  if (agent && agent.id !== identity.agent_id()) {\n    matcher.register_agent(agent.id, agent.capabilities);\n    console.log(`Discovered: ${agent.id}`);\n  }\n});\n\n// Route and execute tasks\nswarm.get('tasks').map().on((task) => {\n  if (task) {\n    const best = matcher.find_best_agent(task.description);\n    if (best === identity.agent_id()) {\n      console.log(`Handling: ${task.description}`);\n      // Execute task...\n    }\n  }\n});\n```\n\n### Cost Summary\n\n| Scale | Infrastructure | Monthly Cost |\n|-------|----------------|--------------|\n| 1 - 10K users | Public GUN + Google STUN | **$0** |\n| 10K - 100K users | Public GUN + Google STUN | **$0** |\n| 100K - 1M users | Public GUN + Google STUN | **$0** |\n| 1M+ users | Public GUN + Google STUN | **$0** |\n| Any scale (private) | Fly.io free tier | **$0** |\n| Enterprise (dedicated) | Self-hosted VPS | $5-20 |\n\n**Key insight:** Public infrastructure scales infinitely. You only pay if you want private/dedicated relays.\n\n---\n\n## Architecture\n\n### Complete System\n\n```\n┌─────────────────────────────────────────────────────────────────────────┐\n│                              Your Application                            │\n├─────────────────────────────────────────────────────────────────────────┤\n│                                                                          │\n│   ┌─────────────────────────────────────────────────────────────────┐   │\n│   │                      @aigentic/edge (WASM)                       │   │\n│   │                                                                  │   │\n│   │   ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐        │   │\n│   │   │ Identity │  │  Crypto  │  │   HNSW   │  │ Semantic │        │   │\n│   │   │ Ed25519  │  │ AES-GCM  │  │  Index   │  │ Matcher  │        │   │\n│   │   └──────────┘  └──────────┘  └──────────┘  └──────────┘        │   │\n│   │                                                                  │   │\n│   │   ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐        │   │\n│   │   │   Raft   │  │ Hybrid   │  │ Spiking  │  │Quantizer │        │   │\n│   │   │Consensus │  │Post-QC   │  │ Neural   │  │Compress  │        │   │\n│   │   └──────────┘  └──────────┘  └──────────┘  └──────────┘        │   │\n│   │                                                                  │   │\n│   └─────────────────────────────────────────────────────────────────┘   │\n│                                    │                                     │\n│                          Transport Adapter                               │\n│                                    │                                     │\n│   ┌────────────────┬───────────────┼───────────────┬────────────────┐   │\n│   │                │               │               │                │   │\n│   ▼                ▼               ▼               ▼                ▼   │\n│ WebRTC          GUN.js          libp2p          Nostr           Custom  │\n│                                                                          │\n└─────────────────────────────────────────────────────────────────────────┘\n         │                │                │                │\n         ▼                ▼                ▼                ▼\n    ┌─────────┐      ┌─────────┐      ┌─────────┐      ┌─────────┐\n    │ Browser │      │ Browser │      │  Edge   │      │  Node   │\n    │ Agent A │◄────►│ Agent B │◄────►│ Agent C │◄────►│ Agent D │\n    └─────────┘      └─────────┘      └─────────┘      └─────────┘\n                           │\n                   No Central Server\n                   No Cloud Costs\n                   No Data Leakage\n```\n\n### What Runs Where\n\n| Component | Runs On | Cost |\n|-----------|---------|------|\n| RuVector Edge (WASM) | User's browser/device | Free - their CPU |\n| Vector index (HNSW) | User's browser/device | Free - their RAM |\n| Encryption (AES-GCM) | User's browser/device | Free - their CPU |\n| Raft consensus | Distributed across agents | Free - P2P |\n| Transport (GUN/WebRTC) | P2P or free relays | Free |\n\n---\n\n## API Reference\n\n### WasmIdentity\n```javascript\nconst id = WasmIdentity.generate();\nid.agent_id()           // Unique identifier\nid.public_key_hex()     // Hex public key\nid.sign(Uint8Array)     // Sign message\nid.verify(msg, sig)     // Verify signature\n```\n\n### WasmCrypto\n```javascript\nconst crypto = new WasmCrypto();\ncrypto.generate_key()            // 32-byte key\ncrypto.encrypt(key, plaintext)   // AES-256-GCM\ncrypto.decrypt(key, ciphertext)  // Decrypt\n```\n\n### WasmHnswIndex\n```javascript\nconst index = new WasmHnswIndex(dims, m, ef);\nindex.insert(id, Float32Array)   // Add vector\nindex.search(query, k)           // Find k nearest\nindex.len()                      // Count\n```\n\n### WasmSemanticMatcher\n```javascript\nconst matcher = new WasmSemanticMatcher();\nmatcher.register_agent(id, capabilities)\nmatcher.find_best_agent(task)\nmatcher.agent_count()\n```\n\n### WasmRaftNode\n```javascript\nconst raft = new WasmRaftNode(id, members);\nraft.start_election()    // Become candidate\nraft.receive_vote(bool)  // Handle vote\nraft.state()             // \"follower\"|\"candidate\"|\"leader\"\nraft.current_term()      // Raft term number\n```\n\n### WasmHybridKeyPair\n```javascript\nconst keys = WasmHybridKeyPair.generate();\nkeys.sign(message)       // Post-quantum signature\nkeys.verify(signature)   // Verify\nkeys.public_key_bytes()  // Export\n```\n\n### WasmSpikingNetwork\n```javascript\nconst net = new WasmSpikingNetwork(in, hidden, out);\nnet.forward(spikes)              // Process\nnet.stdp_update(pre, post, lr)   // Learn\nnet.reset()                      // Reset state\n```\n\n### WasmQuantizer\n```javascript\nconst q = new WasmQuantizer();\nq.quantize(Float32Array)    // 4x compression\nq.reconstruct(Uint8Array)   // Restore\n```\n\n### WasmAdaptiveCompressor\n```javascript\nconst comp = new WasmAdaptiveCompressor();\ncomp.update_metrics(bandwidth, latency)\ncomp.compress(data)\ncomp.decompress(data)\ncomp.condition()  // \"excellent\"|\"good\"|\"poor\"|\"critical\"\n```\n\n---\n\n## Performance\n\n| Operation | Speed | Notes |\n|-----------|-------|-------|\n| Identity generation | 0.5ms | Ed25519 keypair |\n| Sign message | 0.02ms | 50,000 ops/sec |\n| AES-256-GCM encrypt | 1GB/sec | Hardware accelerated |\n| HNSW search (10K vectors) | 0.1ms | 150x faster than brute |\n| Semantic match | 0.5ms | LSH-based |\n| Raft election | 1ms | Single round-trip |\n| Quantization | 100M floats/sec | 4x compression |\n| WASM load | ~50ms | 364KB binary |\n\n---\n\n## Security\n\n- **Ed25519** - Elliptic curve signatures (128-bit security)\n- **X25519** - Secure key exchange\n- **AES-256-GCM** - Authenticated encryption\n- **Post-Quantum Hybrid** - Ed25519 + Dilithium-style\n- **Zero-Trust** - Verify all messages\n- **Replay Protection** - Nonces and timestamps\n\n---\n\n## Interactive Swarm Generator\n\nDon't know where to start? We've included an interactive code generator that helps you build swarm configurations visually. Just select your options and get production-ready code instantly.\n\n### How to Use the Generator\n\n```bash\n# Option 1: Use a local server (recommended)\nnpm install @aigentic/edge\nnpx serve node_modules/@aigentic/edge/\n# Then open http://localhost:3000/generator.html\n\n# Option 2: Open directly in browser\n# Navigate to: node_modules/@aigentic/edge/generator.html\n```\n\nThe generator runs live demos directly in your browser using the actual WASM library - you can test everything before copying the code.\n\n### What You Can Configure\n\n**Network Topologies** - How agents connect to each other:\n\n| Topology | Best For | Description |\n|----------|----------|-------------|\n| **Mesh** | General purpose | Every agent can talk to every other agent directly |\n| **Star** | Centralized control | All agents connect through one coordinator |\n| **Hierarchical** | Large organizations | Tree structure with managers and workers |\n| **Ring** | Sequential processing | Messages pass around in a circle |\n| **Gossip** | Eventual consistency | Information spreads like rumors |\n| **Sharded** | Domain separation | Different groups handle different topics |\n\n**Transport Layers** - How messages travel between agents:\n\n| Transport | Latency | Offline? | Best For |\n|-----------|---------|----------|----------|\n| **GUN.js** | ~100ms | Yes | Getting started, offline-first apps |\n| **WebRTC** | ~50ms | No | Real-time gaming, video, low latency |\n| **libp2p** | ~200ms | Partial | IPFS integration, content addressing |\n| **Nostr** | ~150ms | No | Decentralized social, simple pub/sub |\n\n**Use Cases** - Pre-built patterns for common scenarios:\n\n| Use Case | What It Does |\n|----------|--------------|\n| **AI Assistants** | Multiple specialized agents handling different types of questions |\n| **Data Pipeline** | Distributed ETL with parallel processing stages |\n| **Multiplayer Gaming** | Real-time game state sync with authoritative host |\n| **IoT Swarm** | Coordinate sensors and actuators across locations |\n| **Marketplace** | Agents that negotiate, bid, and trade autonomously |\n| **Research Compute** | Distribute calculations across many devices |\n\n**Features** - Building blocks you can mix and match:\n\n| Feature | What It Adds |\n|---------|--------------|\n| **Identity** | Ed25519 cryptographic keypairs for each agent |\n| **Encryption** | AES-256-GCM for all messages |\n| **HNSW Index** | Fast similarity search (150x faster than brute force) |\n| **Semantic Matching** | Route tasks to the best agent automatically |\n| **Raft Consensus** | Elect leaders and agree on shared state |\n| **Post-Quantum** | Future-proof signatures against quantum computers |\n| **Spiking Neural** | Bio-inspired learning and pattern recognition |\n| **Compression** | Adaptive bandwidth optimization (4-32x) |\n\n**Exotic Patterns** - Advanced capabilities for specialized needs:\n\n| Pattern | What It Does |\n|---------|--------------|\n| **MCP Tools** | Browser-based Model Context Protocol for AI collaboration |\n| **Byzantine Fault** | Tolerate malicious or faulty nodes |\n| **Quantum Resistant** | Hybrid signatures safe from future quantum attacks |\n| **Neural Consensus** | Use spiking networks for group decisions |\n| **Swarm Intelligence** | Particle swarm optimization for problem solving |\n| **Self-Healing** | Automatic failure detection and recovery |\n| **Emergent Behavior** | Evolutionary algorithms for agent adaptation |\n\n### Browser-Based MCP Tools\n\nThe generator includes a complete MCP (Model Context Protocol) implementation that runs entirely in the browser. This lets you create AI tools that work with Claude and other MCP-compatible systems, but without needing a server.\n\n```javascript\n// Create a browser-based MCP server\nconst mcp = new BrowserMCPServer();\nawait mcp.init();\n\n// Built-in tools ready to use:\n// - discover_agents: Find the right agent for a task\n// - send_secure_message: Encrypted P2P communication\n// - store_memory: Save vectors for semantic search\n// - search_memory: Find similar items by meaning\n// - sign_message: Cryptographically prove authorship\n\n// Example: Route a request to find coding help\nconst response = await mcp.handleRequest({\n  method: 'tools/call',\n  params: {\n    name: 'discover_agents',\n    arguments: { query: 'help me write a Python script' }\n  }\n});\n\n// Connect multiple MCP servers for collaboration\nconst network = new MCPCollaborativeNetwork();\nawait network.addServer('coder', 'programming development');\nawait network.addServer('analyst', 'data analysis statistics');\nawait network.addServer('writer', 'documentation technical writing');\n\n// Requests automatically route to the best server\nconst result = await network.routeRequest(request);\n```\n\n**Why browser-based MCP?**\n- No server costs - runs on user devices\n- Works offline - all tools available without internet\n- Privacy-first - sensitive data never leaves the browser\n- Instant deployment - just include the library\n\n---\n\n## License\n\nMIT License - Free for commercial and personal use.\n\n---\n\n## Next Steps\n\n1. **Install:** `npm install @aigentic/edge`\n2. **Try the tutorial:** Build your first swarm\n3. **Choose transport:** Start with GUN.js\n4. **Scale:** Add more agents as needed\n\n**Stop paying for cloud AI. Start running free edge swarms.**\n\n[GitHub](https://github.com/ruvnet/ruvector) | [npm](https://www.npmjs.com/package/@aigentic/edge) | [Issues](https://github.com/ruvnet/ruvector/issues)\n","readmeFilename":"README.md"}