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

# Sub-Agent

> Zeus Sub-Agent — Task Delegation & Parallel Execution

## Overview

Sub-Agent is Zeus's **task delegation mechanism**. The main Agent dispatches subtasks to independent sub-agents by calling the `task` tool. Each sub-agent has its own context and reasoning loop, and returns results to the main Agent as a standard Tool Result upon completion.

Core capabilities:

* **Task Decomposition** — Break complex tasks into independent subtasks
* **Context Isolation** — Each sub-agent has its own isolated context
* **Parallel Execution** — Multiple subtasks run concurrently for improved efficiency
* **Result Aggregation** — Sub-agent results return to the main Agent for continued reasoning

***

## Architecture

```mermaid theme={null}
graph TD
    subgraph MainAgent["Main Agent"]
        direction TB
        plan["1. Analyze task"]
        delegate["2. Call task tool"]
        collect["3. Collect Tool Results"]
        synthesize["4. Synthesize response"]
    end

    subgraph SubAgents["Sub-Agents"]
        direction TB
        sa1["Sub-Agent A<br/>Isolated context · Inherited tools"]
        sa2["Sub-Agent B<br/>Isolated context · Inherited tools"]
        sa3["Sub-Agent C<br/>Isolated context · Inherited tools"]
    end

    plan --> delegate
    delegate --> sa1 & sa2 & sa3
    sa1 & sa2 & sa3 --> collect
    collect --> synthesize
```

### Main Agent vs Sub-Agent

| Dimension  | Main Agent                                | Sub-Agent                            |
| ---------- | ----------------------------------------- | ------------------------------------ |
| Context    | Full System Prompt + conversation history | Minimal context + task description   |
| Tools      | All available tools                       | Inherits main Agent's tool set       |
| Model      | User-configured model                     | Inherits main Agent's model          |
| Lifecycle  | Session-level                             | Single task, destroyed on completion |
| Middleware | Full middleware stack                     | Lightweight middleware stack         |
| Todos      | Has its own task list                     | `write_todos` calls are skipped      |

***

## The `task` Tool

The main Agent triggers sub-agents through the `task` tool. This tool is automatically injected by the DeepAgents framework's `SubAgentMiddleware`.

### Parameters

| Parameter     | Type   | Description                                                              |
| ------------- | ------ | ------------------------------------------------------------------------ |
| `description` | string | Short task description (used for UI display)                             |
| `prompt`      | string | Detailed task instructions; the sub-agent executes based on this context |

### Example

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Main as Main Agent
    participant SA1 as Sub-Agent (Analysis)
    participant SA2 as Sub-Agent (Visualization)

    User->>Main: "Analyze data and generate report"
    Main->>Main: Plan task decomposition

    par Parallel execution
        Main->>SA1: task(description="Data analysis", prompt="Analyze sales.csv...")
        SA1->>SA1: read → bash → write
        SA1-->>Main: Tool Result: Analysis results
    and
        Main->>SA2: task(description="Generate charts", prompt="Create visualizations...")
        SA2->>SA2: read → bash → write
        SA2-->>Main: Tool Result: Chart results
    end

    Main->>Main: Synthesize analysis + charts
    Main-->>User: Complete report
```

***

## SubAgentMiddleware

Sub-Agent capability is provided by the DeepAgents framework's `SubAgentMiddleware`. It is registered automatically during Agent creation and injects the `task` tool into the main Agent's tool set.

### Backend Configuration

Configured in `BaseService._create_agent()`:

```python theme={null}
SubAgentMiddleware(
    default_model=model,           # Sub-agents inherit the main Agent's model
    default_tools=tools,           # Sub-agents inherit the main Agent's tool set
    subagents=subagents,           # Sub-agent configuration list
    default_middleware=[           # Sub-agents use a lightweight middleware stack
        TodoListMiddleware(),
        SummarizationMiddleware(),
        AnthropicPromptCachingMiddleware(),
        PatchToolCallsMiddleware(),
    ],
    default_interrupt_on=interrupt_on,
    general_purpose_agent=True,
)
```

### Execution Flow

```mermaid theme={null}
flowchart TD
    A["Main Agent calls task()"] --> B["SubAgentMiddleware intercepts"]
    B --> C["Create sub-Agent instance"]
    C --> D["Inject task description + inherit tools"]
    D --> E["Sub-Agent independent reasoning loop"]
    E --> F["Sub-Agent calls tools<br/>read / write / bash / ..."]
    F --> E
    E --> G{"Execution complete?"}
    G -->|"Done"| H["Return result to Main Agent"]
    G -->|"Failed"| I["Return error message"]
    H --> J["Main Agent continues reasoning"]
    I --> J
```

***

## Frontend Integration

### SSE Event Flow

Sub-agent execution is streamed to the frontend via standard SSE events. The frontend uses `tool_name` and `tool_call_id` to distinguish between main Agent and sub-agent messages.

```mermaid theme={null}
sequenceDiagram
    participant Backend
    participant Handler as Message Handlers
    participant Store as trajectoryStore
    participant UI as Frontend UI

    Backend->>Handler: tool_call (task)
    Handler->>Store: createAgentTrajectory(taskId)
    Handler->>Store: enterSubAgent(taskId)
    Store->>UI: Add sub-agent tab

    loop Sub-agent execution
        Backend->>Handler: tool_call (read/write/bash...)
        Handler->>Store: addToolExecutionToAgent(taskId, exec)
        Store->>UI: Update TaskToolCallCard + trajectory
    end

    Backend->>Handler: tool_call_result (task)
    Handler->>Store: exitSubAgent(taskId)
    Handler->>Store: completeAgentTrajectory(taskId)
    Store->>UI: Mark completed, switch back to main tab
```

### Message Isolation

Messages produced by sub-agents (tool calls, text) are tagged with a `subAgentTaskId` field and excluded from the main chat flow:

* **Chat area**: Sub-agent tool calls are only shown inside their corresponding `TaskToolCallCard`, not in the main message stream
* **Task grouping**: `groupMessagesIntoTasks` filters out `subAgentTaskId` messages before processing, preventing interference with main task status
* **Todos**: Sub-agent `write_todos` calls are completely skipped, leaving the main Agent's task list unaffected

### TaskToolCallCard

Each `task` tool call renders as an expandable card in the chat area:

* **Collapsed**: Shows status icon, task description, progress (e.g. 5/11), and current activity
* **Expanded**: Lists all internal tool calls with their status and parameter previews
* **Running state**: Blue border highlight with spinning loader
* Supports clicking "View in trajectory →" to jump to the corresponding trajectory tab

Parallel sub-agents each display their own independent `TaskToolCallCard` with individual progress tracking.

### Trajectory Tabs

When sub-agents are active, the trajectory area displays a tab bar at the top:

* **Main** — Main Agent's tool execution history
* **Sub-Agent** — Each sub-agent has its own tab showing its tool execution history

Each tab maintains an independent step slider, allowing users to browse different agents' execution history without interference. Switching tabs updates the trajectory content and code preview accordingly.

***

## Parallel Execution

The main Agent can call multiple `task` tools in a single turn, triggering parallel sub-agents:

```
Main Agent
├── task("Data cleaning")  → Sub-Agent A → read → bash → write → Done
├── task("Analysis")       → Sub-Agent B → read → bash → write → Done
└── task("Visualization")  → Sub-Agent C → read → bash → write → Done
```

The frontend uses a stack model (`subAgentStack`) to track the currently active sub-agent context, routing subsequent tool call events to the correct sub-agent trajectory.

***

## Design Principles

| Principle                 | Description                                                                                                   |
| ------------------------- | ------------------------------------------------------------------------------------------------------------- |
| **Minimal Context**       | Sub-agents receive only the task description, not the full conversation history, reducing token consumption   |
| **Tool Inheritance**      | Sub-agents automatically inherit the main Agent's tool set with no extra configuration                        |
| **Independent Execution** | Sub-agents have their own reasoning loop and do not block the main Agent                                      |
| **Result Pass-through**   | Results are returned as standard Tool Results; the main Agent treats them like any other tool output          |
| **Error Isolation**       | Sub-agent failures do not crash the main Agent; errors are returned as Tool Results                           |
| **UI Isolation**          | Sub-agent messages and tool calls are only displayed in TaskToolCallCard and the corresponding trajectory tab |

***

## Use Cases

| Scenario             | Example                                                                                           |
| -------------------- | ------------------------------------------------------------------------------------------------- |
| Code Development     | Delegate frontend components, backend APIs, and database schemas to separate sub-agents           |
| Data Analysis        | Split data cleaning, statistical analysis, and visualization into parallel subtasks               |
| Information Research | Search multiple sources simultaneously, each sub-agent retrieves independently before aggregation |
| Document Writing     | Delegate different sections to different sub-agents for parallel authoring                        |
| Batch Operations     | Apply the same operation to multiple files or data sources in parallel                            |
