npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ai-agent-claude-swarm

v1.0.6

Published

Multi-agent swarm orchestration plugin for Claude Code with JSON-based cross-session memory

Readme

AI Agent Claude Swarm

Multi-agent swarm orchestration plugin for Claude Code with consensus algorithms, AI threat detection, security validation, work coordination, and cross-session JSON memory.

38 MCP tools | 25 agent types | 19 lifecycle hooks | 6 background workers | 0 external dependencies

Features

| Feature | Description | |---------|-------------| | Multi-Agent Swarm | Hierarchical/mesh topologies, auto-scaling agent pool, 3-tier model routing (haiku/sonnet/opus) | | Consensus Algorithms | Byzantine PBFT (3-phase), Raft (leader election + log replication), Gossip (epidemic protocol) | | AI Threat Detection | 50+ injection patterns, PII detection (SSN, credit cards, emails), confidence-weighted scoring | | Security Validation | Zod-based input validation, path traversal prevention, command injection prevention via execFile | | Work Coordination | Claims with handoffs, work stealing with contest windows, load balancing with utilization tracking | | Lifecycle Hooks | 19 built-in hooks, 5 priority levels, 6 background workers, 2 daemons (metrics + swarm monitor) | | Cross-Session Memory | JSON file storage with atomic writes (tmp+rename), LRU eviction, in-memory cache, namespaced | | O(1) Message Bus | Circular deque with ACK tracking, retry logic, topic subscriptions, broadcast/unicast | | Claude Code Plugin | Auto-registers MCP server + safety hooks via npx ai-agent-claude-swarm init |

Quick Start

Prerequisites

  • Node.js 20+
  • Claude Code (CLI)

Install

npm install -g ai-agent-claude-swarm

Or use directly with npx:

npx ai-agent-claude-swarm init

Initialize Plugin

Run inside your project directory:

npx ai-agent-claude-swarm init

This will:

  1. Create .ai-swarm/ directory with config and memory storage
  2. Register the MCP server in .claude/settings.json
  3. Add safety hooks (blocks git push --force and rm -rf)
  4. Add session-start hook for automatic initialization
  5. Update .gitignore to exclude .ai-swarm/ and .env

Restart Claude Code

After init, restart Claude Code to activate the plugin. You'll have access to all 38 MCP tools.

MCP Tools (38 Total)

Agent Management (5 tools)

| Tool | Description | |------|-------------| | agent_spawn | Create a new agent with type, name, and configuration | | agent_list | List all active agents with status | | agent_status | Get detailed status of a specific agent | | agent_stop | Gracefully stop an agent | | agent_types | List all 25 available agent types |

Swarm Orchestration (4 tools)

| Tool | Description | |------|-------------| | swarm_init | Initialize swarm with topology (hierarchical/mesh) and strategy | | swarm_execute | Execute a task across the swarm | | swarm_status | Get swarm health, agent count, task progress | | swarm_decompose | Break a complex task into subtasks for parallel execution |

Memory (5 tools)

| Tool | Description | |------|-------------| | memory_store | Store key-value data in a namespace | | memory_search | Search across memory with pattern matching | | memory_get | Retrieve a specific memory entry | | memory_stats | Get memory usage statistics | | memory_clear | Clear a namespace or all memory |

Security (5 tools)

| Tool | Description | |------|-------------| | security_validate_input | Validate input against Zod schemas (string, email, URL, path, command, JSON) | | security_validate_path | Check for path traversal attacks | | security_check_command | Validate commands for injection patterns | | security_generate_token | Generate HMAC-SHA256 signed tokens | | security_audit | Run a full security audit of the project |

AI Defence (4 tools)

| Tool | Description | |------|-------------| | aidefence_detect | Full threat analysis with 50+ patterns | | aidefence_quick_scan | Fast scan for common injection patterns | | aidefence_check_pii | Detect PII (SSN, credit cards, emails, phone numbers) | | aidefence_consensus | Multi-engine consensus threat detection |

Claims & Work Coordination (5 tools)

| Tool | Description | |------|-------------| | claims_claim | Claim a work item for an agent | | claims_release | Release a claimed work item | | claims_handoff | Hand off work from one agent to another | | claims_list | List all active claims | | claims_status | Get claim status and history |

Consensus (4 tools)

| Tool | Description | |------|-------------| | consensus_create | Create a consensus group with algorithm selection | | consensus_propose | Submit a proposal for group voting | | consensus_status | Get consensus group state | | consensus_select_algorithm | Auto-select optimal algorithm based on requirements |

Hooks (3 tools)

| Tool | Description | |------|-------------| | hooks_list | List all registered hooks | | hooks_stats | Get hook execution statistics | | hooks_workers | List background worker status |

Task & Session (3 tools)

| Tool | Description | |------|-------------| | task_create | Create a new task | | task_list | List tasks with filtering | | session_status | Get current session information |

Agent Types (25)

| Type | Tier | Description | |------|------|-------------| | coder | Sonnet | Code writing, implementation, debugging | | reviewer | Sonnet | Code review, quality analysis | | tester | Sonnet | Test writing, coverage analysis | | researcher | Sonnet | Information gathering, analysis | | architect | Opus | System design, architecture decisions | | debugger | Sonnet | Bug investigation, root cause analysis | | optimizer | Sonnet | Performance optimization | | documenter | Haiku | Documentation generation | | devops | Sonnet | CI/CD, deployment, infrastructure | | security | Opus | Security auditing, vulnerability analysis | | data-analyst | Sonnet | Data analysis, SQL, visualization | | ml-engineer | Opus | Machine learning, model training | | frontend | Sonnet | UI/UX implementation | | backend | Sonnet | API, server-side development | | mobile | Sonnet | Mobile app development | | qa | Sonnet | Quality assurance, test planning | | technical-writer | Haiku | Technical documentation | | project-manager | Sonnet | Project coordination, planning | | mentor | Opus | Code teaching, best practices | | refactorer | Sonnet | Code refactoring, modernization | | integrator | Sonnet | System integration, API connections | | migrator | Sonnet | Database/code migration | | monitor | Haiku | System monitoring, alerting | | planner | Opus | Strategic planning, roadmapping | | general | Sonnet | General-purpose assistant |

3-Tier Model Routing

Agents are automatically routed to the optimal model tier:

| Tier | Model | Use Case | |------|-------|----------| | Fast | Haiku | Documentation, monitoring, simple tasks | | Balanced | Sonnet | Implementation, testing, most development work | | Deep | Opus | Architecture, security, ML, strategic planning |

Consensus Algorithms

Byzantine PBFT

Tolerates up to f < n/3 faulty or malicious nodes. Three-phase protocol:

  1. Pre-prepare: Leader broadcasts proposal
  2. Prepare: Nodes validate and broadcast prepare messages
  3. Commit: Nodes commit after receiving 2f+1 prepare messages

Best for: High-security decisions, untrusted environments.

Raft

Leader-based consensus tolerating f < n/2 failures:

  1. Leader Election: Candidates request votes with randomized timeouts
  2. Log Replication: Leader replicates entries to followers
  3. Commitment: Entry committed after majority acknowledgment

Best for: General coordination, agent task assignment.

Gossip

Epidemic protocol for eventual consistency:

  1. Infection: Nodes spread updates to random peers
  2. Convergence: All nodes eventually receive all updates
  3. Crumbling: Old data is eventually garbage collected

Best for: Large swarms, status propagation, soft state.

Algorithm Selection

Use consensus_select_algorithm to auto-select based on your requirements:

Fault tolerance priority → Byzantine PBFT
Performance priority     → Raft
Scalability priority     → Gossip

CLI Commands

npx ai-agent-claude-swarm <command>

| Command | Description | |---------|-------------| | init | Initialize plugin in current project | | agent spawn | Spawn a new agent | | agent list | List active agents | | agent status <id> | Get agent status | | agent stop <id> | Stop an agent | | swarm start | Start swarm orchestration | | swarm status | Get swarm status | | memory store | Store a memory entry | | memory search | Search memory | | task create | Create a task | | task list | List tasks | | session status | Current session info | | config show | Show configuration | | hooks list | List registered hooks | | hooks stats | Hook execution statistics | | hooks session-start | Trigger session start hooks | | doctor | Run health diagnostics | | mcp start | Start MCP server (used by Claude Code) | | status | Overall system status |

Programmatic Usage

Plugin Entry Point

import { AiSwarmPlugin, createPlugin } from 'ai-agent-claude-swarm';

const plugin = createPlugin();
await plugin.initialize();

Security Module

import {
  createSecurityModule,
  validateInput,
  validatePath,
  SafeExecutor,
} from 'ai-agent-claude-swarm';

// Create full security module
const security = createSecurityModule({ baseDir: process.cwd() });

// Input validation
const result = security.inputValidator.validateString('user input', {
  maxLength: 1000,
  pattern: /^[a-zA-Z0-9\s]+$/,
});

// Path validation
const pathResult = security.pathValidator.validate('/safe/path/file.ts');

// Safe command execution (no shell, uses execFile)
const executor = new SafeExecutor({ allowedCommands: ['git', 'npm', 'node'] });
const output = await executor.execute('git', ['status']);

Consensus

import { ConsensusEngine, selectOptimalAlgorithm } from 'ai-agent-claude-swarm';

// Auto-select algorithm
const algorithm = selectOptimalAlgorithm({
  faultTolerance: 'high',
  performance: 'medium',
  scalability: 'low',
});

// Create consensus group
const engine = new ConsensusEngine();
const group = engine.createGroup({
  algorithm: 'raft', // or 'byzantine', 'gossip'
  nodes: ['agent-1', 'agent-2', 'agent-3'],
});

// Submit proposal
const result = await group.propose({
  type: 'task-assignment',
  value: { task: 'implement-feature', assignee: 'agent-1' },
});

AI Threat Detection

import { detectThreats, quickScan, checkPII } from 'ai-agent-claude-swarm';

// Full threat analysis (50+ patterns)
const threats = detectThreats('user input to analyze');
console.log(threats.severity); // 'none' | 'low' | 'medium' | 'high' | 'critical'
console.log(threats.patterns); // matched injection patterns

// Quick scan (fast, fewer patterns)
const quick = quickScan('check this input');

// PII detection
const pii = checkPII('Call me at 555-123-4567 or email [email protected]');
console.log(pii.found); // ['phone', 'email']

Claims & Work Coordination

import { ClaimService, WorkStealingService, LoadBalancer } from 'ai-agent-claude-swarm';

const claimService = new ClaimService();

// Claim work
const claim = await claimService.claim('issue-123', 'agent-coder-1');

// Handoff to another agent
await claimService.handoff('issue-123', 'agent-coder-1', 'agent-reviewer-1');

// Work stealing (detect stale claims)
const stealer = new WorkStealingService(claimService);
const stolen = await stealer.detectAndSteal({ staleThresholdMs: 300000 });

// Load balancing
const balancer = new LoadBalancer();
const optimal = balancer.selectAgent(availableAgents, taskRequirements);

Hooks System

import { HookRegistry, HookExecutor, WorkerManager, DaemonManager } from 'ai-agent-claude-swarm';

const registry = new HookRegistry();
const executor = new HookExecutor(registry);

// Register a custom hook
registry.register({
  name: 'my-hook',
  event: 'post-task',
  priority: 500,
  handler: async (context) => {
    console.log('Task completed:', context.taskId);
  },
});

// Start background workers
const workers = new WorkerManager();
workers.startAll();

// Start daemons
const daemons = new DaemonManager();
daemons.startAll();

Memory

import { JsonStore } from 'ai-agent-claude-swarm';

const store = new JsonStore({ basePath: '.ai-swarm/memory' });

// Store with namespace
await store.set('agents', 'coder-1-state', { status: 'active', task: 'feature-x' });

// Retrieve
const state = await store.get('agents', 'coder-1-state');

// Search
const results = await store.search('agents', 'active');

// Stats
const stats = store.getStats();

Configuration

.ai-swarm/config.json

{
  "swarm": {
    "topology": "hierarchical",
    "maxAgents": 8,
    "strategy": "specialized"
  },
  "memory": {
    "path": ".ai-swarm/memory",
    "maxEntriesPerNamespace": 1000
  },
  "agents": {
    "defaultTimeout": 120000,
    "modelRouting": {
      "simple": "haiku",
      "medium": "sonnet",
      "complex": "opus"
    }
  },
  "hooks": {
    "enabled": true,
    "builtIn": true
  }
}

Safety Hooks (Auto-Registered)

The plugin automatically registers safety hooks in .claude/settings.json:

| Hook | Trigger | Action | |------|---------|--------| | PreToolUse | git push --force* | Blocks force pushes | | PreToolUse | rm -rf* | Blocks recursive deletes | | SessionStart | Session begins | Initializes swarm session |

Architecture

src/
├── index.ts              # Plugin entry point (AiSwarmPlugin, createPlugin)
├── agents/               # Agent lifecycle, model routing, spawning
│   ├── agent.ts          # Agent entity with state management
│   ├── model-router.ts   # 3-tier model routing (haiku/sonnet/opus)
│   └── spawner.ts        # Agent creation and claude -p execution
├── swarm/                # Swarm coordination and orchestration
│   ├── coordinator.ts    # Main orchestration engine
│   ├── topology.ts       # Hierarchical/mesh topology management
│   ├── task-queue.ts     # Priority queue with dependency resolution
│   ├── message-bus.ts    # O(1) circular deque message bus
│   ├── agent-pool.ts     # Auto-scaling agent pool
│   └── consensus/        # Distributed consensus algorithms
│       ├── raft.ts       # Leader election + log replication
│       ├── byzantine.ts  # PBFT 3-phase consensus
│       ├── gossip.ts     # Epidemic protocol
│       └── index.ts      # Factory + algorithm selection
├── security/             # Security validation and hardening
│   ├── input-validator.ts    # Zod-based input validation
│   ├── path-validator.ts     # Path traversal prevention
│   ├── safe-executor.ts      # Command injection prevention
│   ├── password-hasher.ts    # bcrypt hashing
│   ├── token-generator.ts    # HMAC-SHA256 signed tokens
│   ├── credential-generator.ts # Secure credential generation
│   └── index.ts
├── claims/               # Work coordination and claiming
│   ├── types.ts          # Claim types, work stealing, load balancing
│   ├── rules.ts          # Pure validation functions
│   ├── events.ts         # Domain events + factory functions
│   ├── claim-service.ts  # Claiming, handoffs, auto-assign
│   ├── work-stealing.ts  # Stale work detection and stealing
│   ├── load-balancer.ts  # Agent utilization and rebalancing
│   └── index.ts
├── aidefence/            # AI threat detection
│   ├── types.ts          # Threat types and interfaces
│   ├── threat-detection.ts   # 50+ patterns, PII detection
│   ├── threat-learning.ts    # Pattern learning, mitigation tracking
│   └── index.ts              # Facade with convenience functions
├── memory/               # JSON file-based cross-session memory
│   ├── json-store.ts     # Atomic writes, LRU eviction, in-memory cache
│   └── namespaces.ts     # Convenience helpers
├── hooks/                # Lifecycle hooks system
│   ├── registry.ts       # Priority-sorted registration, stats tracking
│   ├── executor.ts       # Timeout handling, context threading
│   ├── built-in.ts       # 19 built-in hooks
│   ├── workers.ts        # 6 background workers
│   └── daemons.ts        # MetricsDaemon, SwarmMonitorDaemon
├── mcp/                  # MCP server for Claude Code
│   ├── server.ts         # stdio JSON-RPC server
│   ├── tools.ts          # 17 core MCP tools
│   ├── tools-security.ts # 9 security + aidefence tools
│   ├── tools-coordination.ts # 12 claims + consensus + hooks tools
│   └── tools-extended.ts # Aggregator
├── cli/                  # CLI commands
│   └── commands/         # 11 commands
├── types/                # Shared type definitions
└── utils/
    └── id.ts             # ID generation utilities

Development

# Install dependencies
npm install

# Build
npm run build

# Type-check
npm run typecheck

# Clean
npm run clean

Dependencies

| Package | Purpose | |---------|---------| | bcrypt | Password hashing (security module) | | zod | Runtime input validation schemas | | typescript | Build toolchain (dev only) |

No database required. All storage uses JSON files in .ai-swarm/memory/.

How It Works

  1. Plugin registers as an MCP server in Claude Code via .claude/settings.json
  2. Claude Code discovers the 38 tools at startup via stdio JSON-RPC
  3. You interact with Claude Code normally — it uses swarm tools when beneficial
  4. Agents coordinate through the message bus, consensus protocols, and shared memory
  5. Safety hooks prevent dangerous operations (force push, recursive delete)
  6. Memory persists across sessions via JSON files with atomic writes

License

MIT