ai-agent-orchestrator
Orchestrates multi-agent AI systems with task delegation, agent communication, shared memory, and workflow coordination. Use when users request "multi-agent system", "agent orchestration", "AI agents", "agent coordination", or "autonomous agents".
What this skill does
# AI Agent Orchestrator
Build coordinated multi-agent systems for complex task automation.
## Core Workflow
1. **Define agents**: Create specialized agents
2. **Design workflow**: Plan agent coordination
3. **Implement handoffs**: Agent-to-agent communication
4. **Add shared memory**: Persistent context
5. **Create supervisor**: Orchestrate execution
6. **Monitor execution**: Track agent activities
## Agent Architecture
### Agent Definition
```typescript
// agents/base.ts
import { ChatOpenAI } from '@langchain/openai';
import { SystemMessage, HumanMessage, AIMessage } from '@langchain/core/messages';
export interface AgentConfig {
name: string;
role: string;
systemPrompt: string;
tools?: Tool[];
model?: string;
}
export interface AgentResponse {
content: string;
toolCalls?: ToolCall[];
nextAgent?: string;
completed?: boolean;
}
export class Agent {
private model: ChatOpenAI;
private config: AgentConfig;
private messageHistory: BaseMessage[] = [];
constructor(config: AgentConfig) {
this.config = config;
this.model = new ChatOpenAI({
modelName: config.model || 'gpt-4-turbo-preview',
temperature: 0.7,
});
}
async execute(input: string, context?: Record<string, any>): Promise<AgentResponse> {
const systemMessage = new SystemMessage(
this.buildSystemPrompt(context)
);
const messages = [
systemMessage,
...this.messageHistory,
new HumanMessage(input),
];
const response = await this.model.invoke(messages, {
tools: this.config.tools,
});
this.messageHistory.push(new HumanMessage(input));
this.messageHistory.push(new AIMessage(response.content as string));
return this.parseResponse(response);
}
private buildSystemPrompt(context?: Record<string, any>): string {
let prompt = this.config.systemPrompt;
if (context) {
prompt += `\n\nContext:\n${JSON.stringify(context, null, 2)}`;
}
return prompt;
}
private parseResponse(response: any): AgentResponse {
// Parse tool calls and determine next actions
return {
content: response.content as string,
toolCalls: response.tool_calls,
completed: response.content?.includes('[TASK_COMPLETE]'),
};
}
clearHistory() {
this.messageHistory = [];
}
}
```
### Specialized Agents
```typescript
// agents/specialists.ts
import { Agent, AgentConfig } from './base';
export const ResearchAgent = new Agent({
name: 'researcher',
role: 'Research Specialist',
systemPrompt: `You are a research specialist. Your job is to:
- Search for and gather relevant information
- Analyze sources and extract key insights
- Summarize findings clearly
- Cite sources when possible
When you have gathered sufficient information, include [TASK_COMPLETE] in your response.
If you need help from another agent, specify: [HANDOFF:agent_name]`,
tools: [searchTool, webScrapeTool],
});
export const WriterAgent = new Agent({
name: 'writer',
role: 'Content Writer',
systemPrompt: `You are a professional content writer. Your job is to:
- Create engaging, well-structured content
- Adapt tone and style to the target audience
- Incorporate research and data effectively
- Edit and refine for clarity
Use the research provided to create compelling content.
When complete, include [TASK_COMPLETE].`,
});
export const ReviewerAgent = new Agent({
name: 'reviewer',
role: 'Quality Reviewer',
systemPrompt: `You are a quality reviewer. Your job is to:
- Review content for accuracy and clarity
- Check for errors and inconsistencies
- Suggest improvements
- Approve or request revisions
Provide specific feedback. If approved, include [APPROVED].
If revisions needed, include [REVISIONS_NEEDED] with specific changes.`,
});
export const PlannerAgent = new Agent({
name: 'planner',
role: 'Task Planner',
systemPrompt: `You are a task planner. Your job is to:
- Break down complex tasks into subtasks
- Identify which specialist agent should handle each subtask
- Create an execution order
- Track progress
Output a structured plan in JSON format:
{
"goal": "...",
"steps": [
{ "step": 1, "agent": "researcher", "task": "..." },
{ "step": 2, "agent": "writer", "task": "..." }
]
}`,
});
```
## Orchestrator
### Simple Sequential Orchestrator
```typescript
// orchestrator/sequential.ts
import { Agent } from '../agents/base';
interface WorkflowStep {
agent: Agent;
task: string;
inputFrom?: string;
}
export class SequentialOrchestrator {
private agents: Map<string, Agent> = new Map();
private results: Map<string, string> = new Map();
registerAgent(name: string, agent: Agent) {
this.agents.set(name, agent);
}
async execute(workflow: WorkflowStep[]): Promise<Record<string, string>> {
for (const step of workflow) {
const agent = step.agent;
// Get input from previous step if specified
let input = step.task;
if (step.inputFrom && this.results.has(step.inputFrom)) {
input = `${step.task}\n\nPrevious output:\n${this.results.get(step.inputFrom)}`;
}
console.log(`Executing: ${agent.name} - ${step.task}`);
const result = await agent.execute(input);
this.results.set(agent.name, result.content);
console.log(`Completed: ${agent.name}`);
}
return Object.fromEntries(this.results);
}
}
// Usage
const orchestrator = new SequentialOrchestrator();
orchestrator.registerAgent('researcher', ResearchAgent);
orchestrator.registerAgent('writer', WriterAgent);
orchestrator.registerAgent('reviewer', ReviewerAgent);
const results = await orchestrator.execute([
{ agent: ResearchAgent, task: 'Research the latest AI trends in 2024' },
{ agent: WriterAgent, task: 'Write a blog post about AI trends', inputFrom: 'researcher' },
{ agent: ReviewerAgent, task: 'Review the blog post', inputFrom: 'writer' },
]);
```
### Supervisor Orchestrator
```typescript
// orchestrator/supervisor.ts
import { ChatOpenAI } from '@langchain/openai';
import { Agent } from '../agents/base';
interface AgentRegistry {
[name: string]: {
agent: Agent;
description: string;
};
}
export class SupervisorOrchestrator {
private supervisor: ChatOpenAI;
private agents: AgentRegistry = {};
private sharedContext: Record<string, any> = {};
private maxIterations = 10;
constructor() {
this.supervisor = new ChatOpenAI({
modelName: 'gpt-4-turbo-preview',
temperature: 0,
});
}
registerAgent(name: string, agent: Agent, description: string) {
this.agents[name] = { agent, description };
}
async execute(task: string): Promise<string> {
let iteration = 0;
let currentTask = task;
const history: string[] = [];
while (iteration < this.maxIterations) {
iteration++;
// Supervisor decides next action
const decision = await this.supervise(currentTask, history);
if (decision.complete) {
return decision.finalResponse!;
}
// Execute selected agent
const { agent } = this.agents[decision.nextAgent!];
const result = await agent.execute(decision.agentTask!, this.sharedContext);
// Update shared context
this.sharedContext[decision.nextAgent!] = result.content;
history.push(`${decision.nextAgent}: ${result.content}`);
// Check for handoff
if (result.nextAgent) {
currentTask = `Continue with: ${result.content}`;
}
}
throw new Error('Max iterations reached');
}
private async supervise(
task: string,
history: string[]
): Promise<{
complete: boolean;
finalResponse?: string;
nextAgent?: string;
agentTask?: string;
}> {
const agentList = Object.entries(this.agents)
.map(([name, { description }]) => `- ${name}: ${description}`)
.join('\n');
const prompt = `You are a supervisor coordinating AI agents.
Available agents:
${agentList}
Task: ${task}
History:
${history.join('\n')}
Decide the next action.Related 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.