Skip to main content

@agentlib/orchestrator

Agent orchestrator for AgentLIB — coordinate multiple specialized agents to solve complex tasks.

Installation

npm install @agentlib/orchestrator

Overview

The @agentlib/orchestrator package provides a meta-agent system that can:
  • Coordinate multiple specialized sub-agents
  • Execute agents in parallel or sequentially
  • Manage agent state and communication
  • Share global context across agents
  • Automatically summarize multi-agent workflows

Quick Start

import { createAgent } from '@agentlib/core'
import { Orchestrator } from '@agentlib/orchestrator'
import { openai } from '@agentlib/openai'

// Create specialized agents
const researcher = createAgent({
  name: 'researcher',
  description: 'Finds and analyzes information',
  model: openai({ apiKey: process.env.OPENAI_API_KEY! }),
  tools: [searchTool]
})

const writer = createAgent({
  name: 'writer',
  description: 'Creates written content',
  model: openai({ apiKey: process.env.OPENAI_API_KEY! })
})

// Create planner agent
const planner = createAgent({
  name: 'planner',
  description: 'Coordinates research and writing tasks',
  model: openai({ apiKey: process.env.OPENAI_API_KEY! }),
  reasoning: 'planner'
})

// Create orchestrator
const orchestrator = new Orchestrator(planner, {
  agents: { researcher, writer }
})

// Run coordinated task
const result = await orchestrator.run(
  'Research AI trends and write a blog post'
)
console.log(result.output)

Configuration

interface OrchestratorConfig {
  /** Map of agent name to agent instance */
  agents?: Record<string, AgentInstance>
  
  /** Global context shared across all agents */
  context?: Record<string, any>
  
  /** Auto-expose agents as tools to planner (default: true) */
  exposeAgentsAsTools?: boolean
  
  /** Enable automatic summarization of agent outputs */
  summarize?: boolean
  
  /** Include sub-agent buffers in context */
  extendedSubBuffers?: boolean
  
  /** Callback for each agent step */
  onStep?: (step: ReasoningStep & { agent: string }) => 'abort' | void
}

Core Concepts

Planner Agent

The planner is a special agent that controls the orchestrator. It decides:
  • Which agents to invoke
  • What prompts to send them
  • When to run agents in parallel vs sequential
  • How to synthesize results
const planner = createAgent({
  name: 'planner',
  description: 'Orchestrates multiple specialized agents',
  model: openai({ apiKey: process.env.OPENAI_API_KEY! }),
  reasoning: 'planner' // Recommended
})

Sub-Agents

Sub-agents are specialized workers that the planner can invoke:
const agents = {
  researcher: createAgent({
    name: 'researcher',
    description: 'Expert at finding information',
    tools: [webSearchTool, wikiTool]
  }),
  
  analyst: createAgent({
    name: 'analyst',
    description: 'Analyzes data and trends',
    tools: [calculatorTool, chartTool]
  }),
  
  writer: createAgent({
    name: 'writer',
    description: 'Creates polished written content'
  })
}

Built-in Tools

When exposeAgentsAsTools: true (default), the orchestrator automatically provides these tools to the planner:

invoke_agent

Launch an agent with a prompt (runs in parallel):
// Planner can call:
invoke_agent({
  agentName: 'researcher',
  prompt: 'Find latest AI breakthroughs'
})

wait_for_agent

Wait for a specific agent to finish and get its output:
// Must be called after invoke_agent:
const result = await wait_for_agent({ agentName: 'researcher' })

wait_all_agents

Wait for all currently running agents:
const results = await wait_all_agents()
// Returns: { researcher: '...', writer: '...' }

get_agent_state

Get current status of a specific agent:
const state = await get_agent_state({ agentName: 'researcher' })
// Returns: { name: 'researcher', status: 'running', lastOutput: '...' }

get_all_agent_states

Get status of all agents:
const states = await get_all_agent_states()
// Returns array of AgentState objects

clear_agent_history

Clear memory/history of a specific agent:
await clear_agent_history({ agentName: 'researcher' })

Execution Patterns

Sequential Execution

const orchestrator = new Orchestrator(planner, {
  agents: { researcher, writer }
})

await orchestrator.run(`
  1. Use researcher to find AI trends
  2. Use writer to create a blog post based on research
`)
The planner will:
  1. invoke_agent(researcher, 'Find AI trends')
  2. wait_for_agent(researcher)
  3. invoke_agent(writer, 'Write blog post about: ...')
  4. wait_for_agent(writer)

Parallel Execution

await orchestrator.run(`
  Research AI trends in healthcare AND education,
  then synthesize findings
`)
The planner can:
  1. invoke_agent(researcher, 'AI in healthcare')
  2. invoke_agent(researcher, 'AI in education') (parallel!)
  3. wait_all_agents()
  4. Synthesize results

Global Context

Share read-only context across all agents:
const orchestrator = new Orchestrator(planner, {
  agents: { researcher, writer },
  context: {
    company: 'Acme Corp',
    audience: 'enterprise developers',
    style: 'technical but accessible'
  }
})
This context is injected into system prompts:
### Global Context (READ ONLY):
{
  "company": "Acme Corp",
  "audience": "enterprise developers",
  "style": "technical but accessible"
}

Memory Management

Each sub-agent automatically gets a BufferMemory if none is provided:
// These agents will have independent memory
const orchestrator = new Orchestrator(planner, {
  agents: { researcher, writer }
})

// Multiple calls to same agent maintain context
await orchestrator.run('Ask researcher about AI')
await orchestrator.run('Ask researcher to elaborate') // Remembers previous
Clear an agent’s memory:
await orchestrator.clearAgentHistory('researcher')

Summarization

Enable automatic summarization of agent work:
const orchestrator = new Orchestrator(planner, {
  agents: { researcher, writer },
  summarize: true
})
When enabled:
  • Each agent’s output is summarized
  • Summaries are injected into subsequent planner runs
  • Helps maintain context across long workflows

Event Handling

import { Orchestrator } from '@agentlib/orchestrator'

const orchestrator = new Orchestrator(planner, config)

// Agent invoked
orchestrator.on('agent:invoke', ({ agent, prompt }) => {
  console.log(`Starting ${agent}: ${prompt}`)
})

// Agent completed
orchestrator.on('agent:completed', ({ agent, output }) => {
  console.log(`${agent} finished: ${output}`)
})

// Agent step
orchestrator.on('agent:step', ({ agent, step }) => {
  console.log(`[${agent}] ${step.type}:`, step)
})

// Planner step
orchestrator.on('planner:step', ({ step }) => {
  console.log(`[planner] ${step.type}:`, step)
})

// Step summary (if summarize: true)
orchestrator.on('step:summary', (summary) => {
  console.log('Summary:', summary)
})

// Orchestrator finished
orchestrator.on('finished', ({ output }) => {
  console.log('Done:', output)
})

Advanced Usage

Step Interception

const orchestrator = new Orchestrator(planner, {
  agents: { researcher, writer },
  onStep: (step) => {
    console.log(`[${step.agent}] ${step.type}`)
    
    // Abort on certain conditions
    if (step.type === 'error') {
      return 'abort'
    }
  }
})

Manual Agent Control

// Manually invoke an agent
await orchestrator.invokeAgent('researcher', 'Find AI trends')

// Wait for specific agent
const output = await orchestrator.waitAgent('researcher')

// Wait for all
const allOutputs = await orchestrator.waitAll()

// Get state
const state = orchestrator.getAgentState('researcher')
const allStates = orchestrator.getAllStates()

Extended Sub-Buffers

const orchestrator = new Orchestrator(planner, {
  agents: { researcher, writer },
  extendedSubBuffers: true
})

// Planner can see last activity from each agent
const history = await orchestrator.getHistory()

Agent State

interface AgentState {
  name: string
  status: 'idle' | 'running' | 'error'
  lastOutput?: string
  error?: Error
}

Use Cases

Research + Writing Pipeline

const orchestrator = new Orchestrator(planner, {
  agents: {
    researcher: createAgent({ /* ... */ }),
    writer: createAgent({ /* ... */ }),
    editor: createAgent({ /* ... */ })
  }
})

await orchestrator.run('Write a technical blog post about Rust')

Multi-Modal Analysis

const orchestrator = new Orchestrator(planner, {
  agents: {
    vision: createAgent({ tools: [imageAnalysisTool] }),
    text: createAgent({ tools: [textAnalysisTool] }),
    synthesis: createAgent({ /* ... */ })
  }
})

await orchestrator.run('Analyze this image and caption')

Customer Support

const orchestrator = new Orchestrator(planner, {
  agents: {
    classifier: createAgent({ /* categorize issue */ }),
    knowledge: createAgent({ tools: [kbSearchTool] }),
    responder: createAgent({ /* draft response */ })
  }
})

await orchestrator.run('Help customer with login issue')

Requirements

  • Node.js: >= 18.0.0
  • Dependencies:
    • @agentlib/core (workspace)
    • @agentlib/memory (workspace)
    • @agentlib/utils (workspace)

Exports

Classes

  • Orchestrator - Main orchestrator class

Types

  • OrchestratorConfig
  • AgentState
  • StepSummary
  • OrchestratorEvents

Build docs developers (and LLMs) love