SKY-lv/skylv-multi-agent-orchestrator

Orquestrador Multi-Agente - Skill OpenClaw

O que é skylv-multi-agent-orchestrator?

Esta skill fornece uma estrutura completa para projetar e gerenciar sistemas de colaboração entre múltiplos agentes de IA. Ela implementa um orquestrador central que decompõe tarefas complexas em subtarefas, gerencia um grafo direcionado acíclico (DAG) de dependências e coordena a execução paralela de agentes especializados. O sistema inclui uma classe base de agente com memória semântica, um barramento de mensagens para comunicação entre agentes (suportando broadcast, ponto a ponto, publish/subscribe e quadronegro), um gerenciador de estados com máquina de estados, e padrões prontos para uso como role-play e debate. Projetada para plataformas como OpenClaw, a skill é altamente extensível e permite configurar agentes com diferentes LLMs, ferramentas e instruções, oferecendo também mecanismos de tolerância a falhas como controle de tempo limite e disjuntor. O usuário pode facilmente instalar a skill, configurar os agentes conforme necessário e executar fluxos de trabalho multiagente complexos.

Funciona com~Claude Code✓Codex CLI~Cursor
npx skills add SKY-lv/skylv-multi-agent-orchestrator

Installed? Explore more Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Multi-Agent Orchestrator

Funcionalidades

Projetar e gerenciar sistemas de colaboração entre múltiplos agentes.

Arquitetura

┌─────────────┐
│ Orchestrator │ ← Decomposição de tarefas, coordenação
└──────┬──────┘
       │
   ┌───┼───┐
   ▼   ▼   ▼
 ┌───┐┌───┐┌───┐
 │ A ││ B ││ C │ ← Agentes especializados
 └───┘└───┘└───┘

Implementação Principal

1. Classe Base do Agente

interface AgentConfig {
  name: string;
  role: string;
  capabilities: string[];
  llm: LLMConfig;
  tools: Tool[];
  instructions: string;
}

class BaseAgent {
  protected config: AgentConfig;
  protected memory: AgentMemory;
  
  constructor(config: AgentConfig) {
    this.config = config;
    this.memory = new AgentMemory(config.name);
  }
  
  async think(task: Task): Promise<Response> {
    const context = await this.memory.buildContext(task.description);
    const prompt = this.buildPrompt(task, context);
    const response = await this.callLLM(prompt);
    await this.memory.add({ type: 'semantic', content: task.description + ' -> ' + response.content, importance: 8 });
    return response;
  }
  
  protected buildPrompt(task: Task, context: string): Message[] {
    return [
      { role: 'system', content: this.config.instructions },
      { role: 'system', content: context },
      { role: 'user', content: task.description }
    ];
  }
  
  protected async callLLM(messages: Message[]): Promise<Response> {
    const res = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}` },
      body: JSON.stringify({ model: this.config.llm.model, messages, tools: this.config.tools.map(t => t.definition) })
    });
    return res.json();
  }
}

2. Orquestrador

interface TaskResult {
  agentId: string;
  status: 'pending' | 'running' | 'done' | 'failed';
  output?: string;
  dependencies: string[];
  startTime?: number;
  endTime?: number;
}

class Orchestrator {
  private agents: Map<string, BaseAgent> = new Map();
  private taskGraph: DAG<Task>;
  
  constructor(private llmRouter: LLMRouter) {}
  
  registerAgent(agent: BaseAgent) {
    this.agents.set(agent.config.name, agent);
  }
  
  async execute(goal: string): Promise<string> {
    // 1. Decompor tarefa
    const plan = await this.decompose(goal);
    
    // 2. Construir DAG
    this.taskGraph = this.buildDAG(plan);
    
    // 3. Agendar execução
    const results = await this.schedule();
    
    // 4. Consolidar resultados
    return this.summarize(goal, results);
  }
  
  private async decompose(goal: string): Promise<Task[]> {
    const response = await this.llmRouter.route({
      prompt: `Divida a tarefa a seguir em subtarefas executáveis, retornando um array JSON:
      
Objetivo: ${goal}

Requisitos:
- Cada subtarefa é responsabilidade de apenas um agente
- Especifique claramente as dependências entre tarefas
- Formato de retorno: [{"id":"t1","description":"...","agent":"pesquisador","depends":[]},...]`,
      system: 'Você é um especialista em decomposição de tarefas.'
    });
    
    return JSON.parse(response.content);
  }
  
  private async schedule(): Promise<Map<string, TaskResult>> {
    const results = new Map<string, TaskResult>();
    const pending = new Set(this.taskGraph.nodes);
    const running: Promise<void>[] = [];
    const maxConcurrent = 3;
    
    while (pending.size > 0 || running.length > 0) {
      // Iniciar tarefas paralelizáveis
      while (running.length < maxConcurrent) {
        const next = this.findNextRunnable(pending, results);
        if (!next) break;
        
        pending.delete(next.id);
        const p = this.runTask(next, results).catch(console.error);
        running.push(p);
      }
      
      // Aguardar conclusão de uma
      await Promise.race(running);
      running.splice(running.findIndex(p => false), 1);
    }
    
    return results;
  }
  
  private async runTask(task: Task, results: Map<string, TaskResult>) {
    results.set(task.id, { agentId: task.agent, status: 'running', dependencies: task.depends || [], startTime: Date.now() });
    
    try {
      // Aguardar dependências
      for (const depId of task.depends || []) {
        const dep = results.get(depId);
        if (dep?.status !== 'done') {
          await this.waitFor(depId, results);
        }
      }
      
      const agent = this.agents.get(task.agent);
      const context = this.buildContext(task, results);
      const response = await agent.think({ id: task.id, description: task.description, context });
      
      results.set(task.id, { ...results.get(task.id)!, status: 'done', output: response.content, endTime: Date.now() });
    } catch (error) {
      results.set(task.id, { ...results.get(task.id)!, status: 'failed', output: String(error), endTime: Date.now() });
    }
  }
  
  private buildContext(task: Task, results: Map<string, TaskResult>): string {
    return (task.depends || []).map(depId => {
      const dep = results.get(depId);
      return dep?.output || '';
    }).join('\n\n');
  }
}

3. Barramento de Mensagens

class MessageBus {
  private subscriptions = new Map<string, Subscriber[]>();
  
  publish(channel: string, message: Message) {
    const subs = this.subscriptions.get(channel) || [];
    for (const sub of subs) {
      sub.handler(message);
    }
  }
  
  subscribe(channel: string, handler: (msg: Message) => void): () => void {
    if (!this.subscriptions.has(channel)) {
      this.subscriptions.set(channel, []);
    }
    const sub = { id: crypto.randomUUID(), handler };
    this.subscriptions.get(channel)!.push(sub);
    return () => this.unsubscribe(channel, sub.id);
  }
  
  unsubscribe(channel: string, subId: string) {
    const subs = this.subscriptions.get(channel) || [];
    const idx = subs.findIndex(s => s.id === subId);
    if (idx >= 0) subs.splice(idx, 1);
  }
}

// Tipos de mensagem
interface Message {
  id: string;
  type: 'request' | 'response' | 'broadcast' | 'event';
  from: string;
  to?: string;
  content: any;
  timestamp: number;
}

4. Máquina de Estados

type AgentState = 'idle' | 'thinking' | 'waiting' | 'acting' | 'error';

interface AgentSession {
  id: string;
  agentId: string;
  state: AgentState;
  currentTask?: string;
  history: Turn[];
  sharedContext: Record<string, any>;
}

class StateManager {
  private sessions = new Map<string, AgentSession>();
  
  transition(sessionId: string, newState: AgentState) {
    const session = this.sessions.get(sessionId);
    if (!session) return;
    
    const oldState = session.state;
    session.state = newState;
    
    // Ganchos de transição de estado
    this.onTransition(sessionId, oldState, newState);
  }
  
  // Regras de transição de estado
  private canTransition(from: AgentState, to: AgentState): boolean {
    const rules: Record<AgentState, AgentState[]> = {
      idle: ['thinking'],
      thinking: ['waiting', 'acting', 'error', 'idle'],
      waiting: ['thinking', 'error', 'idle'],
      acting: ['thinking', 'error', 'idle'],
      error: ['idle', 'thinking']
    };
    return rules[from]?.includes(to) || false;
  }
}

Padrões de Comunicação

PadrãoDescriçãoCenário de Uso
BroadcastTodos os agentes recebemNotificações globais
Ponto a pontoAgente específico recebeAtribuição de tarefas
Publicar/AssinarDistribuição por tópicoOrientado a eventos
QuadronegroEspaço de conhecimento compartilhadoRaciocínio colaborativo

Padrões Comuns

Role Play (Interpretação de Papéis)

class RolePlayOrchestrator extends Orchestrator {
  async execute(goal: string) {
    // Atribuir papéis
    const planner = this.getAgent('planner');
    const executor = this.getAgent('executor');
    const critic = this.getAgent('critic');
    
    const plan = await planner.think({ description: goal });
    const result = await executor.think({ description: plan.output, context: '' });
    const review = await critic.think({ description: result.output, context: '' });
    
    return review.output;
  }
}

Debate

async debate(topic: string, rounds = 3) {
  const pro = this.getAgent('pro');
  const con = this.getAgent('con');
  const judge = this.getAgent('judge');
  
  let context = '';
  for (let i = 0; i < rounds; i++) {
    const proArg = await pro.think({ description: `Argumento a favor (Rodada ${i+1}): ${topic}`, context });
    context += `\nA favor: ${proArg.output}`;
    
    const conArg = await con.think({ description: `Argumento contra (Rodada ${i+1}): ${topic}`, context });
    context += `\nContra: ${conArg.output}`;
  }
  
  return judge.think({ description: `Julgamento: ${topic}`, context });
}

Melhores Práticas

  1. Responsabilidade Única: Cada agente possui um domínio de especialização claro
  2. Baixo Acoplamento: Comunicação via barramento de mensagens, evitando dependências diretas
  3. Controle de Tempo Limite: Evitar que um agente fique travado
  4. Mecanismo Disjuntor: Degradação automática em caso de falhas excessivas
  5. Observabilidade: Logs e rastreamento completos

Uso

  1. Instale a skill
  2. Configure conforme necessário
  3. Execute com OpenClaw

Habilidades Relacionadas