# OpenCode Subagent 并行与线性调用指南

## 来源

- [OpenCode Agents 官方文档](https://opencode.ai/docs/agents/)
- [OpenCode 源码 task.ts](https://github.com/anomalyco/opencode/blob/main/packages/opencode/src/tool/task.ts)

## Subagent 类型

OpenCode 有两种 agent：
- **Primary agents**: 主 agent（build, plan），通过 Tab 切换
- **Subagents**: 子 agent，通过 `@mention` 或 Task tool 唤起

内置 subagent：
- `@general` - 通用任务 agent，可执行多步骤任务
- `@explore` - 代码库探索 agent，**只读**，不能修改文件

## 调用方式

### 1. @mention（当前会话调用）

在消息中直接使用 `@subagent` 唤起，subagent 在**当前会话**中执行：

```
@explore 帮我探索这个代码库的结构
```

### 2. Task tool（独立子会话并行调用）

**Task tool 是 OpenCode 官方实现的并行调用机制。**

```typescript
Task({
  description: "任务描述（3-5词）",
  prompt: "给 subagent 的指令",
  subagent_type: "explore"  // 或 "general"
})
```

**关键特性：**
- 每个 Task 调用创建**独立的 Session**（子会话）
- 多个 Task 同时调用 → 多个子会话**并行执行**
- 通过 `@mention` 调用时 `bypassAgentCheck` = true，跳过权限确认

## 并行 vs 线性调用

### 并行调用（Task tool）

```typescript
// 同时派遣，并行执行
Task({ description: "Task 1", prompt: "...", subagent_type: "explore" })
Task({ description: "Task 2", prompt: "...", subagent_type: "explore" })
Task({ description: "Task 3", prompt: "...", subagent_type: "explore" })
Task({ description: "Task 4", prompt: "...", subagent_type: "explore" })
```

```
┌─────────────────────────────────────────┐
│           Primary Agent                 │
└────────────────┬──────────────────────┘
                 │ Task tool (同时派遣)
    ┌────────────┼────────────┐
    ▼            ▼            ▼
┌────────┐  ┌────────┐  ┌────────┐
│ Session│  │ Session│  │ Session│
│   1    │  │   2    │  │   3    │
└────────┘  └────────┘  └────────┘
```

### 线性调用（@mention）

```typescript
// 顺序执行
@explore 任务1
@explore 任务2
@explore 任务3
```

## 何时使用

| 场景 | 方式 |
|------|------|
| 多个**独立**任务可同时执行 | Task tool 并行 |
| 任务**有依赖**，需等待结果 | @mention 线性 |
| 简单一次性指令 | @mention |
| 需要传递上下文/结果给下一步 | @mention 线性 |

## Task tool 参数说明

| 参数 | 说明 |
|------|------|
| `description` | 任务简短描述（3-5词） |
| `prompt` | 给 subagent 的详细指令 |
| `subagent_type` | subagent 类型：`explore` 或 `general` |
| `task_id` | 可选，用于恢复之前的任务会话 |

## 命令文件示例

### 并行调用（Task tool）

```markdown
## Steps 2-5: Dispatch via Task tool in PARALLEL

Once project is confirmed, dispatch these 4 tasks **simultaneously**:

**Task 1 - Security Check:**
```
@explore Search for security issues about [repo]
```

**Task 2 - Project Understanding:**
```
@explore Read README and understand the project
```

**Task 3 - Installation Guide:**
```
@explore Find installation instructions
```

**Task 4 - Usage Guide:**
```
@explore Find usage documentation
```
```

### 线性调用（@mention）

```markdown
## Steps: Sequential @explore calls

Execute tasks one by one:

**Step 1:**
```
@explore 任务1
```

Wait for result, then:

**Step 2:**
```
@explore 任务2（可基于任务1的结果）
```
```

## 参考

- 官方 Agents 文档: https://opencode.ai/docs/agents/
- Task tool 源码: https://github.com/anomalyco/opencode/blob/main/packages/opencode/src/tool/task.ts
