> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orcbot.buzzchat.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Multi-Agent Orchestration

> Spawn agents, delegate tasks, and coordinate parallel work

# Multi-Agent Orchestration

OrcBot provides production-ready multi-agent orchestration for parallel task execution, specialization, and autonomous coordination. The orchestration system uses real Node.js worker processes with IPC communication.

## Architecture

### Orchestration Components

1. **AgentOrchestrator**: Manages worker pool and task distribution
2. **Worker Processes**: Isolated Node.js processes forked from main agent
3. **IPC Channel**: Inter-process communication for coordination
4. **Task Queue**: Shared priority queue for work distribution
5. **Message Bus**: Agent-to-agent messaging system

### Worker Lifecycle

```mermaid theme={null}
stateDiagram-v2
    [*] --> Spawning: spawn_agent()
    Spawning --> Idle: Worker ready
    Idle --> Working: Task assigned
    Working --> Idle: Task complete
    Idle --> [*]: terminate_agent()
    Working --> [*]: Crash/timeout
```

### Process Isolation

Each worker is a separate Node.js process with:

* **Isolated memory**: No shared state with main agent
* **Separate config**: Can override LLM model, API keys
* **Independent execution**: Runs tasks without blocking main agent
* **IPC communication**: Sends results back via message passing

## spawn\_agent

Create a sub-agent for parallel work.

### Parameters

<ParamField path="name" type="string" required>
  Agent name (used in logs and status)
</ParamField>

<ParamField path="role" type="string" required>
  Agent role: `"worker"` (general task execution) or `"researcher"` (specialized research)
</ParamField>

<ParamField path="capabilities" type="array">
  Optional skill subset this agent can use
</ParamField>

### Return Value

<ResponseField name="result" type="string">
  Confirmation with agent ID and PID (process ID)
</ResponseField>

### Roles

**Worker Agent:**

* General-purpose task execution
* Full skill access (unless restricted by capabilities)
* Suitable for parallel automation
* Example: scraping multiple websites simultaneously

**Researcher Agent:**

* Specialized for deep research tasks
* Higher `isResearch` skill budgets
* Optimized for multi-step web navigation
* Example: comprehensive market research

### Example Usage

**Spawn general worker:**

```json theme={null}
{
  "skill": "spawn_agent",
  "args": {
    "name": "scraper-1",
    "role": "worker"
  }
}
```

**Spawn researcher:**

```json theme={null}
{
  "skill": "spawn_agent",
  "args": {
    "name": "market-researcher",
    "role": "researcher"
  }
}
```

**Spawn with capability restrictions:**

```json theme={null}
{
  "skill": "spawn_agent",
  "args": {
    "name": "data-processor",
    "role": "worker",
    "capabilities": ["read_file", "write_file", "execute_python_code"]
  }
}
```

### Response Example

```
Agent spawned successfully:
ID: agent-1736954400000
Name: scraper-1
Role: worker
PID: 12345
Status: idle
```

### Worker Process Details

Workers inherit:

* Config from main agent (unless overridden)
* LLM credentials
* Memory store paths
* Skill registry

Workers DO NOT inherit:

* Channel connections (no Telegram/WhatsApp/Discord)
* Current action state
* Short-term memory (starts fresh)

### Metadata

* **isDeep**: `false`
* **isDangerous**: `false`
* **isElevated**: `false`

<Tip>
  **Spawn workers for I/O-bound parallelism.** If you need to scrape 10 websites, spawn 10 workers and delegate one URL to each.
</Tip>

## delegate\_task

Assign a task to an agent or the orchestrator.

### Parameters

<ParamField path="description" type="string" required>
  Natural language task description
</ParamField>

<ParamField path="priority" type="number" default="5">
  Task priority (1-10, higher = more urgent)
</ParamField>

<ParamField path="agent_id" type="string">
  Specific agent to assign to. If omitted, orchestrator auto-assigns to available worker.
</ParamField>

### Return Value

<ResponseField name="result" type="string">
  Confirmation with task ID and assigned agent
</ResponseField>

### Auto-Assignment

If `agent_id` is omitted, the orchestrator:

1. Finds idle workers
2. Assigns to least-loaded worker
3. If no workers idle, queues for next available

### Example Usage

**Delegate to specific agent:**

```json theme={null}
{
  "skill": "delegate_task",
  "args": {
    "description": "Scrape product prices from example.com",
    "priority": 8,
    "agent_id": "agent-1736954400000"
  }
}
```

**Auto-assign to available worker:**

```json theme={null}
{
  "skill": "delegate_task",
  "args": {
    "description": "Analyze sentiment of customer reviews",
    "priority": 5
  }
}
```

### Response Example

```
Task delegated successfully:
Task ID: task-1736954401000
Description: Scrape product prices from example.com
Assigned to: agent-1736954400000 (scraper-1)
Priority: 8
Status: pending
```

### Task Dependencies

Tasks support `dependsOn` metadata for chaining:

```typescript theme={null}
// Task A must complete before Task B
delegate_task("Download dataset", 10) // Returns task-A
delegate_task("Process dataset", 8, { dependsOn: "task-A" })
```

### Metadata

* **isDeep**: `false`

## distribute\_tasks

Auto-assign pending tasks to available workers.

### Parameters

None. Distributes all pending tasks in the queue.

### Return Value

<ResponseField name="result" type="string">
  Summary of distributed tasks
</ResponseField>

### Example Usage

```json theme={null}
{
  "skill": "distribute_tasks",
  "args": {}
}
```

### Response Example

```
Task distribution complete:
- 3 tasks assigned to workers
- 2 tasks still pending (no idle workers)
- 1 task blocked by dependencies

Assignments:
- agent-1: task-A (priority 10)
- agent-2: task-B (priority 8)
- agent-3: task-C (priority 7)
```

### Metadata

* **isDeep**: `false`

## orchestrator\_status

Get orchestration summary.

### Parameters

None.

### Return Value

<ResponseField name="status" type="object">
  Orchestration state including active workers, pending tasks, and completion stats
</ResponseField>

### Example Usage

```json theme={null}
{
  "skill": "orchestrator_status",
  "args": {}
}
```

### Response Example

```json theme={null}
{
  "workers": {
    "total": 3,
    "idle": 1,
    "working": 2,
    "crashed": 0
  },
  "tasks": {
    "pending": 5,
    "in_progress": 2,
    "completed": 12,
    "failed": 1
  },
  "agents": [
    {
      "id": "agent-1",
      "name": "scraper-1",
      "status": "working",
      "current_task": "task-A",
      "uptime": "00:15:32"
    },
    {
      "id": "agent-2",
      "name": "researcher-1",
      "status": "idle"
    }
  ]
}
```

### Metadata

* **isDeep**: `false`

## complete\_delegated\_task

Mark a delegated task as completed. Typically called by workers.

### Parameters

<ParamField path="task_id" type="string" required>
  Task ID to mark complete
</ParamField>

<ParamField path="result" type="string">
  Optional result summary
</ParamField>

### Example Usage

```json theme={null}
{
  "skill": "complete_delegated_task",
  "args": {
    "task_id": "task-1736954401000",
    "result": "Found 42 products with prices ranging from $10 to $500"
  }
}
```

### Metadata

* **isDeep**: `false`

## fail\_delegated\_task

Mark a delegated task as failed.

### Parameters

<ParamField path="task_id" type="string" required>
  Task ID to mark failed
</ParamField>

<ParamField path="error" type="string" required>
  Error message or reason for failure
</ParamField>

### Example Usage

```json theme={null}
{
  "skill": "fail_delegated_task",
  "args": {
    "task_id": "task-1736954401000",
    "error": "Target website returned 403 Forbidden"
  }
}
```

### Metadata

* **isDeep**: `false`

## Inter-Agent Messaging

### send\_agent\_message

Send a message to another agent.

**Parameters:**

<ParamField path="to_agent_id" type="string" required>
  Recipient agent ID
</ParamField>

<ParamField path="message" type="string" required>
  Message content
</ParamField>

<ParamField path="type" type="string" default="info">
  Message type: info, request, response, alert
</ParamField>

**Example:**

```json theme={null}
{
  "skill": "send_agent_message",
  "args": {
    "to_agent_id": "agent-2",
    "message": "Scraping complete. Found 100 URLs for you to process.",
    "type": "info"
  }
}
```

### broadcast\_to\_agents

Broadcast a message to all agents.

**Parameters:**

<ParamField path="message" type="string" required>
  Message to broadcast
</ParamField>

**Example:**

```json theme={null}
{
  "skill": "broadcast_to_agents",
  "args": {
    "message": "Main agent shutting down in 60 seconds. Complete current tasks."
  }
}
```

### get\_agent\_messages

Retrieve messages for an agent.

**Parameters:**

<ParamField path="agent_id" type="string">
  Agent ID. If omitted, returns messages for current agent.
</ParamField>

<ParamField path="limit" type="number" default="10">
  Max messages to return
</ParamField>

**Example:**

```json theme={null}
{
  "skill": "get_agent_messages",
  "args": {
    "agent_id": "agent-1",
    "limit": 5
  }
}
```

## Peer Agents

### create\_peer\_agent

Create an independent peer agent with specialized configuration.

**Parameters:**

<ParamField path="name" type="string" required>
  Peer agent name
</ParamField>

<ParamField path="role" type="string" required>
  Role description
</ParamField>

<ParamField path="specialized_governance" type="object">
  Custom WORLD.md governance rules
</ParamField>

**Example:**

```json theme={null}
{
  "skill": "create_peer_agent",
  "args": {
    "name": "customer-support-bot",
    "role": "Handles customer inquiries on Discord",
    "specialized_governance": {
      "response_time": "<5 minutes",
      "tone": "friendly and helpful"
    }
  }
}
```

**Difference from Workers:**

* **Peer agents** are independent long-lived agents with their own identity
* **Workers** are temporary sub-processes for parallel task execution

Peers inherit WORLD.md governance but can have specialized rules.

### configure\_peer\_agent

Update peer agent configuration and restart.

**Parameters:**

<ParamField path="agent_id" type="string" required>
  Peer agent ID
</ParamField>

<ParamField path="updates" type="object" required>
  Configuration updates (API keys, channel tokens, etc.)
</ParamField>

**Example:**

```json theme={null}
{
  "skill": "configure_peer_agent",
  "args": {
    "agent_id": "peer-1736954400000",
    "updates": {
      "discordToken": "new-discord-token",
      "modelName": "gpt-4o-mini"
    }
  }
}
```

## Common Patterns

### Parallel Web Scraping

```typescript theme={null}
// 1. Define URLs to scrape
const urls = [
  "https://example.com/page1",
  "https://example.com/page2",
  "https://example.com/page3"
];

// 2. Spawn workers (one per URL)
for (let i = 0; i < urls.length; i++) {
  spawn_agent(`scraper-${i}`, "worker")
}

// 3. Delegate tasks
for (let i = 0; i < urls.length; i++) {
  delegate_task(
    `Scrape products from ${urls[i]} and save to scrape-${i}.json`,
    8,
    `agent-${i}`
  )
}

// 4. Monitor progress
orcherator_status()

// 5. Collect results
// Workers write results to files, main agent aggregates
```

### Research Coordination

```typescript theme={null}
// 1. Spawn specialized researchers
spawn_agent("tech-researcher", "researcher")
spawn_agent("market-researcher", "researcher")

// 2. Delegate research topics
delegate_task(
  "Research latest AI model architectures and summarize",
  10,
  "tech-researcher"
)
delegate_task(
  "Research competitor pricing strategies",
  9,
  "market-researcher"
)

// 3. Researchers save findings to LEARNING.md
// 4. Main agent synthesizes final report
```

### Task Pipeline

```typescript theme={null}
// 1. Create dependency chain
const taskA = delegate_task("Download dataset from API", 10)
const taskB = delegate_task("Clean and validate dataset", 8, { dependsOn: taskA })
const taskC = delegate_task("Train ML model on dataset", 7, { dependsOn: taskB })

// 2. Distribute to workers
distribute_tasks()

// 3. Workers execute in order
// 4. Monitor with orchestrator_status()
```

## Best Practices

<Tip>
  **When to spawn workers:**

  1. I/O-bound parallelism (multiple web scrapes, API calls)
  2. Long-running tasks that shouldn't block main agent
  3. Specialized work requiring different LLM models
  4. Tasks with natural parallelization boundaries
</Tip>

<Warning>
  **Resource considerations:**

  * Each worker is a full Node.js process (\~50-100MB RAM)
  * Limit workers to 5-10 on typical servers
  * Workers don't share memory, so results must be communicated via IPC or files
  * Channel connections (Telegram, etc.) are NOT available in workers
</Warning>

<Note>
  **Workers vs peer agents:**

  * **Use workers** for temporary parallel task execution
  * **Use peer agents** for long-lived specialized bots
  * Workers are cheaper (terminate after task completion)
  * Peers have full autonomy and channel access
</Note>

## Configuration

```yaml theme={null}
# Max worker processes
maxWorkers: 10

# Worker idle timeout (milliseconds)
workerIdleTimeout: 600000 # 10 minutes

# Allow workers to connect to channels
allowWorkerChannels: false

# IPC timeout (milliseconds)
ipcTimeout: 30000
```

## Troubleshooting

### "Worker crashed"

* **Cause**: Unhandled exception in worker process
* **Fix**: Check daemon logs, add error handling to delegated tasks

### "Task stuck in pending"

* **Cause**: No idle workers or dependency not met
* **Fix**: Check `orchestrator_status()`, spawn more workers or resolve dependencies

### "IPC timeout"

* **Cause**: Worker took too long to respond
* **Fix**: Increase `ipcTimeout` or split task into smaller chunks

### "No workers available"

* **Cause**: All workers busy or crashed
* **Fix**: Spawn more workers or terminate/restart hung workers

## Related Skills

<CardGroup cols={2}>
  <Card title="Scheduling" icon="clock" href="/api/skills/scheduling">
    Schedule autonomous tasks for workers
  </Card>

  <Card title="Memory" icon="brain" href="/api/skills/memory">
    Share context between agents
  </Card>
</CardGroup>
