agent-mesh-architecture
Use this skill when designing peer-to-peer multi-agent systems. Activate when the user needs agents that collaborate without central control, wants resilient agent networks, needs swarm-like agent behavior, or is building decentralized agent architectures.
What this skill does
# Agent Mesh Architecture
Design resilient peer-to-peer agent networks where agents collaborate without central orchestration.
## When to Use
- Resilience is critical (no single point of failure)
- Agents need to collaborate dynamically
- Tasks benefit from emergent behavior
- Scale varies (agents join/leave dynamically)
- Different perspectives improve outcomes
## Architecture Overview
```
┌─────────┐ ┌─────────┐
│ Agent A │◄───►│ Agent B │
└────┬────┘ └────┬────┘
│ │
│ ┌───────┐ │
└──►│ Agent │◄──┘
│ C │
┌──►│ │◄──┐
│ └───────┘ │
┌────┴────┐ ┌────┴────┐
│ Agent D │◄───►│ Agent E │
└─────────┘ └─────────┘
```
## Core Components
### 1. Agent Node
Each agent is an independent node with communication capabilities.
```typescript
interface AgentNode {
id: string;
capabilities: string[];
state: AgentState;
// Communication
broadcast(message: Message): Promise<void>;
sendTo(agentId: string, message: Message): Promise<void>;
onMessage(handler: MessageHandler): void;
// Discovery
discoverPeers(): Promise<AgentNode[]>;
announceCapability(capability: string): void;
// Task handling
canHandle(task: Task): boolean;
handle(task: Task): Promise<Result>;
}
interface Message {
type: 'task_request' | 'task_result' | 'collaboration_invite' |
'capability_query' | 'heartbeat' | 'consensus_vote';
from: string;
to: string | 'broadcast';
payload: unknown;
timestamp: Date;
correlationId: string;
}
```
### 2. Message Bus / Communication Layer
```typescript
interface MessageBus {
publish(topic: string, message: Message): Promise<void>;
subscribe(topic: string, handler: MessageHandler): Subscription;
request(agentId: string, message: Message): Promise<Message>;
}
// In-memory implementation for local agents
class LocalMessageBus implements MessageBus {
private subscribers = new Map<string, MessageHandler[]>();
async publish(topic: string, message: Message) {
const handlers = this.subscribers.get(topic) || [];
await Promise.all(handlers.map(h => h(message)));
}
subscribe(topic: string, handler: MessageHandler) {
const handlers = this.subscribers.get(topic) || [];
handlers.push(handler);
this.subscribers.set(topic, handlers);
return {
unsubscribe: () => {
const idx = handlers.indexOf(handler);
if (idx >= 0) handlers.splice(idx, 1);
}
};
}
}
```
### 3. Service Discovery
```typescript
interface ServiceRegistry {
register(agent: AgentNode): Promise<void>;
deregister(agentId: string): Promise<void>;
findByCapability(capability: string): Promise<AgentNode[]>;
getAll(): Promise<AgentNode[]>;
onAgentJoin(handler: (agent: AgentNode) => void): void;
onAgentLeave(handler: (agentId: string) => void): void;
}
class AgentRegistry implements ServiceRegistry {
private agents = new Map<string, AgentNode>();
private capabilities = new Map<string, Set<string>>();
async findByCapability(capability: string): Promise<AgentNode[]> {
const agentIds = this.capabilities.get(capability) || new Set();
return Array.from(agentIds)
.map(id => this.agents.get(id))
.filter(Boolean) as AgentNode[];
}
}
```
## Communication Patterns
### Pattern 1: Request-Response
```typescript
// Agent A needs help from specialized agent
async function requestHelp(task: Task): Promise<Result> {
// Find capable agents
const candidates = await registry.findByCapability(task.requiredCapability);
if (candidates.length === 0) {
throw new Error(`No agent can handle: ${task.requiredCapability}`);
}
// Select best candidate (load balancing, proximity, etc.)
const selected = selectBestAgent(candidates, task);
// Send request and await response
const response = await messageBus.request(selected.id, {
type: 'task_request',
payload: task
});
return response.payload as Result;
}
```
### Pattern 2: Collaborative Consensus
```typescript
// Multiple agents vote on a decision
async function reachConsensus(question: string, voters: AgentNode[]): Promise<Decision> {
const correlationId = generateId();
// Broadcast question to all voters
const votePromises = voters.map(voter =>
messageBus.request(voter.id, {
type: 'consensus_vote',
correlationId,
payload: { question }
})
);
const votes = await Promise.all(votePromises);
// Aggregate votes
const tally = new Map<string, number>();
for (const vote of votes) {
const choice = vote.payload.choice;
tally.set(choice, (tally.get(choice) || 0) + 1);
}
// Determine winner
const winner = [...tally.entries()]
.sort((a, b) => b[1] - a[1])[0];
return {
choice: winner[0],
confidence: winner[1] / voters.length,
votes: votes.map(v => ({ agent: v.from, choice: v.payload.choice }))
};
}
```
### Pattern 3: Task Auction
```typescript
// Agents bid on tasks
async function auctionTask(task: Task): Promise<AgentNode> {
const correlationId = generateId();
// Broadcast task availability
await messageBus.publish('tasks', {
type: 'task_auction',
correlationId,
payload: { task, deadline: Date.now() + 5000 }
});
// Collect bids within deadline
const bids: Bid[] = [];
return new Promise((resolve) => {
const sub = messageBus.subscribe(`bids:${correlationId}`, (msg) => {
bids.push(msg.payload as Bid);
});
setTimeout(() => {
sub.unsubscribe();
// Select winning bid
const winner = bids.sort((a, b) => {
// Consider: capability match, current load, past performance
return scoreBid(b, task) - scoreBid(a, task);
})[0];
resolve(winner.agent);
}, 5000);
});
}
```
### Pattern 4: Gossip Protocol
```typescript
// Agents share state updates through gossip
class GossipProtocol {
private state = new Map<string, StateEntry>();
async gossip() {
// Select random peers
const peers = selectRandomPeers(this.registry, 3);
for (const peer of peers) {
// Exchange state digests
const theirDigest = await this.requestDigest(peer);
const myDigest = this.getDigest();
// Find differences
const theyNeed = this.findMissing(myDigest, theirDigest);
const iNeed = this.findMissing(theirDigest, myDigest);
// Exchange missing entries
if (theyNeed.length) await this.sendUpdates(peer, theyNeed);
if (iNeed.length) this.applyUpdates(await this.requestUpdates(peer, iNeed));
}
}
// Run gossip periodically
startGossipLoop(intervalMs: number) {
setInterval(() => this.gossip(), intervalMs);
}
}
```
## Agent Behavior Patterns
### Self-Organizing Task Distribution
```typescript
const agentBehavior = {
onTaskReceived: async (task: Task) => {
// Can I handle this?
if (this.canHandle(task)) {
if (this.currentLoad < this.capacity) {
return this.handle(task);
} else {
// Overloaded, find help
return this.delegateToCapablePeer(task);
}
}
// Find someone who can
const capable = await this.findCapablePeer(task);
if (capable) {
return this.forwardTo(capable, task);
}
// No one can handle
return { error: 'No capable agent found' };
}
};
```
### Collaborative Problem Solving
```typescript
async function collaborativeSolve(problem: Problem): Promise<Solution> {
// Phase 1: Brainstorm
const ideas = await broadcastAndCollect<Idea>('brainstorm', {
problem,
timeout: 10000
});
// Phase 2: Critique and refine
const refinedIdeas = await broadcastAndCollect<Idea>('critique', {
ideas,
timeout: 15000
});
// Phase 3: Vote on best solution
const decision = await reachConsensus(
'Which solution should we implement?',
this.getAllAgents()
);
// Phase 4: Collaborate on implementation
return collaborativeImplement(decision.choice);
}
```
## ReRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.