> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_17_hands-on_labs/17.5_lab5_simplified_multi-agent_orchestration_system.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 17.5 Lab 5: Implementing a Simplified Multi-Agent Orchestration System

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2026-02-18

***

The first four labs gave us command of the core components of an AI programming assistant: LLM conversation, Tool Use, MCP extensions, and the Plugin mechanism. But a truly powerful AI programming assistant is not a single Agent working alone -- it is **multiple Agents collaborating**.

In Chapter 15, we dissected oh-my-opencode's multi-Agent architecture in depth: Sisyphus serves as the chief orchestrator, Oracle provides technical consultation, Explore handles code searching, Prometheus plans complex tasks... This pattern of **division of labor and collaboration** dramatically improves the AI's task completion capabilities.

In this section, we will build a **simplified multi-Agent orchestration system** from scratch, emulating the core architecture of oh-my-opencode to experience the design essence of Agent orchestration.

## 17.5.1 Objectives

Build a multi-Agent system with the following components:

1. **Commander Agent (Chief Orchestrator)**: Receives user tasks and decides whether to handle them directly or delegate to sub-Agents
2. **Researcher Agent**: Specializes in code searching and information gathering
3. **Coder Agent**: Specializes in code writing and modification
4. **Task tool**: Implements the inter-Agent task delegation mechanism
5. **Session management**: Maintains independent context for each Agent

> **Extended Explanation -- What Is Multi-Agent Orchestration?**
>
> Multi-Agent orchestration refers to running multiple AI Agents with different capabilities and "personas" within a single system, coordinating them through some mechanism to collaborate on complex tasks.
>
> The key differences from a single-Agent approach are:
>
> * **Specialized division of labor**: Each Agent has a different System Prompt, toolset, and behavioral constraints, like different roles on a team
> * **Cost optimization**: Simple tasks go to lightweight Agents (cheaper models), complex tasks go to powerful Agents (more expensive models)
> * **Parallel processing**: Multiple sub-Agents can work simultaneously, improving efficiency
> * **Context isolation**: Each Agent has its own independent conversation context, preventing mutual interference
>
> oh-my-opencode's approach is similar to a "virtual technical team": Sisyphus is the tech lead who assigns work to different specialists based on the nature of the task.

## 17.5.2 Architecture Design

Before we start coding, let us design the overall system architecture:

```
┌─────────────────────────────────────────────┐
│                  User Input                  │
└──────────────────────┬──────────────────────┘
                       ▼
┌─────────────────────────────────────────────┐
│         Commander Agent (Chief Orchestrator)  │
│                                              │
│  System Prompt: Task classification +        │
│                 delegation decisions          │
│  Tools: task, read, edit, bash               │
│                                              │
│  Decision logic:                             │
│  ┌─────────────────────────────────┐        │
│  │ Simple question → Answer directly │        │
│  │ Needs search → Delegate to       │        │
│  │                Researcher         │        │
│  │ Needs coding → Delegate to Coder │        │
│  │ Complex task → Researcher first,  │        │
│  │                then Coder         │        │
│  └─────────────────────────────────┘        │
└──────┬──────────────────────┬───────────────┘
       │                      │
       ▼                      ▼
┌──────────────┐    ┌──────────────┐
│  Researcher  │    │    Coder     │
│   Agent      │    │    Agent     │
│              │    │              │
│ Tools: read, │    │ Tools: read, │
│ glob, grep   │    │ edit, write, │
│              │    │ bash         │
└──────────────┘    └──────────────┘
```

### Correspondence with oh-my-opencode

| Our System | oh-my-opencode       | Role                                                                   |
| ---------- | -------------------- | ---------------------------------------------------------------------- |
| Commander  | Sisyphus             | Chief orchestrator; responsible for task classification and delegation |
| Researcher | Explore              | Code searching specialist                                              |
| Coder      | Hephaestus           | Code writing craftsman                                                 |
| task tool  | delegate-task / task | Inter-Agent task delegation                                            |

## 17.5.3 Implementation Steps

### Step 1: Project Initialization and Base Structure

```bash
mkdir multi-agent-orchestrator
cd multi-agent-orchestrator
bun init -y
bun add ai @ai-sdk/openai zod
```

Create the directory structure:

```
multi-agent-orchestrator/
├── src/
│   ├── index.ts          # Entry file
│   ├── agents/           # Agent definitions
│   │   ├── commander.ts
│   │   ├── researcher.ts
│   │   └── coder.ts
│   ├── tools/            # Tool implementations
│   │   ├── file-tools.ts
│   │   ├── search-tools.ts
│   │   └── task-tool.ts
│   ├── session/          # Session management
│   │   └── manager.ts
│   └── types.ts          # Type definitions
├── package.json
└── tsconfig.json
```

### Step 2: Define Core Types

Create `src/types.ts`:

```typescript
import type { CoreMessage, CoreTool } from "ai"

// Agent definition
export interface AgentDefinition {
  name: string
  description: string
  systemPrompt: string
  tools: Record<string, CoreTool>
  model: string // Model ID
  maxSteps: number // Maximum tool call iterations
}

// Session record
export interface Session {
  id: string
  agentName: string
  messages: CoreMessage[]
  parentSessionId?: string // Link to parent session
  status: "active" | "completed" | "error"
  result?: string // Task result
}

// Task delegation request
export interface TaskRequest {
  targetAgent: string
  description: string
  context?: string // Optional context information
  parentSessionId: string
}
```

These types correspond to the OpenCode data models analyzed in Chapter 4: `AgentDefinition` corresponds to `Agent.Info`, `Session` corresponds to `Session.Info`, and `TaskRequest` corresponds to the parameters of the `task` tool.

### Step 3: Implement the Session Manager

Create `src/session/manager.ts` -- managing independent sessions for multiple Agents:

```typescript
import type { Session } from "../types"
import { randomUUID } from "crypto"

export class SessionManager {
  private sessions = new Map<string, Session>()

  // Create a new session
  create(agentName: string, parentSessionId?: string): Session {
    const session: Session = {
      id: `ses_${randomUUID().slice(0, 8)}`,
      agentName,
      messages: [],
      parentSessionId,
      status: "active",
    }
    this.sessions.set(session.id, session)
    return session
  }

  // Get a session
  get(sessionId: string): Session | undefined {
    return this.sessions.get(sessionId)
  }

  // Get all child sessions of a given session
  getChildren(parentSessionId: string): Session[] {
    return [...this.sessions.values()].filter(
      (s) => s.parentSessionId === parentSessionId
    )
  }

  // Complete a session
  complete(sessionId: string, result: string) {
    const session = this.sessions.get(sessionId)
    if (session) {
      session.status = "completed"
      session.result = result
    }
  }

  // List all sessions
  list(): Session[] {
    return [...this.sessions.values()]
  }
}
```

This design emulates the core concepts of Session in OpenCode (Section 4.1):

* **`parentSessionId`**: Implements parent-child session association. When Commander delegates a task to Researcher, the Researcher's session records Commander's session ID, forming a hierarchical relationship.
* **Independent `messages` array**: Each Agent has its own context, without mutual interference.
* **`status` state machine**: `active` -> `completed`/`error`, corresponding to OpenCode's `SessionStatus`.

### Step 4: Define the Agents

Create `src/agents/researcher.ts` -- the Researcher Agent:

```typescript
import type { AgentDefinition } from "../types"
import { createSearchTools } from "../tools/search-tools"

export function createResearcher(workDir: string): AgentDefinition {
  return {
    name: "researcher",
    description: "Codebase search expert, skilled at quickly locating files and code snippets",
    model: "gpt-4o-mini", // Use a cheaper model since search tasks are relatively simple
    maxSteps: 10,
    systemPrompt: `You are a codebase search expert (Researcher). Your responsibilities are:

1. Efficiently search for and locate code files
2. Read and understand code content
3. Organize search results and report them in a structured manner

## Behavioral Guidelines

- Only use the read, glob, and grep tools; do not modify any files
- Search results should include file paths and key code snippets
- If you cannot find relevant content, state so clearly rather than guessing
- Responses should be concise and structured for easy consumption by the caller

## Output Format

After completing your search, report in the following format:
- List of files found and their respective purposes
- Key code snippets (with line numbers noted)
- Your analysis and recommendations`,
    tools: createSearchTools(workDir),
  }
}
```

Create `src/agents/coder.ts` -- the Coder Agent:

```typescript
import type { AgentDefinition } from "../types"
import { createFileTools } from "../tools/file-tools"

export function createCoder(workDir: string): AgentDefinition {
  return {
    name: "coder",
    description: "Code writing craftsman, skilled at implementing features and fixing bugs",
    model: "gpt-4o", // Use a more powerful model since coding requires higher reasoning ability
    maxSteps: 20,
    systemPrompt: `You are a code writing craftsman (Coder). Your responsibilities are:

1. Write or modify code according to task descriptions
2. Ensure code quality -- follow the project's existing style and best practices
3. Briefly explain what changes you made upon completion

## Behavioral Guidelines

- Read existing content before modifying a file
- Use the edit tool for precise replacements rather than rewriting entire files with write
- Do not introduce unnecessary dependencies
- Code style should be consistent with the project
- Upon completion, report which files were modified and a summary of changes for each

## Safety Rules

- Do not execute dangerous commands (rm -rf, git push --force, etc.)
- Do not modify .env files or files containing secrets
- If the task is unclear, it is better to do nothing than to speculatively modify code`,
    tools: createFileTools(workDir),
  }
}
```

Create `src/agents/commander.ts` -- the Chief Orchestrator Agent:

```typescript
import type { AgentDefinition } from "../types"
import { createFileTools } from "../tools/file-tools"
import { createSearchTools } from "../tools/search-tools"
import { createTaskTool } from "../tools/task-tool"
import type { SessionManager } from "../session/manager"

export function createCommander(
  workDir: string,
  sessionManager: SessionManager,
  executeAgent: (agentName: string, task: string, parentSessionId: string) => Promise<string>
): AgentDefinition {
  return {
    name: "commander",
    description: "Chief orchestrator, responsible for understanding user intent and assigning tasks",
    model: "gpt-4o",
    maxSteps: 30,
    systemPrompt: `You are Commander -- the tech lead of an AI programming team. Your team has the following members:

## Team Members

| Agent | Expertise | Cost | When to Use |
|-------|-----------|------|-------------|
| researcher | Code search, file location | Low | When you need to find code or understand project structure |
| coder | Code writing, bug fixing | High | When you need to actually write or modify code |

## Decision Process

1. **Analyze user intent**: Understand what the user wants
2. **Assess complexity**:
   - Simple questions (e.g., explaining concepts) -> Answer directly, do not delegate
   - Needs code search -> Delegate to researcher
   - Needs code writing -> Delegate to coder
   - Complex task -> Have researcher search first, then have coder write
3. **Delegate tasks**: Use the task tool to delegate to the appropriate Agent
4. **Integrate results**: Consolidate results from each Agent and provide the user with a complete response

## Delegation Protocol

When using the task tool, the description should include:
- TASK: Specific task description
- CONTEXT: Necessary background information
- EXPECTED_OUTCOME: Expected output format

## Key Principles

- Cost awareness: Use researcher (cheap) for simple searches, not coder
- Do not delegate multiple interdependent tasks simultaneously -- wait for the previous one to complete before delegating the next
- If a sub-Agent fails, try re-delegating in a different way or handle it yourself
- Always give the user a clear final response; do not simply forward a sub-Agent's raw output`,
    tools: {
      ...createFileTools(workDir),
      ...createSearchTools(workDir),
      ...createTaskTool(sessionManager, executeAgent),
    },
  }
}
```

Note the design of Commander's System Prompt -- it emulates the core philosophy of Sisyphus in oh-my-opencode (Section 15.3.3):

1. **Intent classification**: Analyzing task complexity, similar to Sisyphus's Trivial/Explicit/Exploratory/Open-ended classification
2. **Delegation protocol**: A structured task description format, similar to Sisyphus's 6-section delegation structure
3. **Cost awareness**: Distinguishing which tasks use cheap Agents versus expensive Agents
4. **Error recovery**: Fallback strategies when sub-Agents fail

### Step 5: Implement the Tool Sets

Create `src/tools/search-tools.ts`:

```typescript
import { z } from "zod"
import type { CoreTool } from "ai"
import * as fs from "fs"
import * as path from "path"
import { execSync } from "child_process"

export function createSearchTools(workDir: string): Record<string, CoreTool> {
  return {
    read: {
      description: "Read file contents. Returns file content with line numbers.",
      parameters: z.object({
        file_path: z.string().describe("Path of the file to read"),
        offset: z.number().optional().describe("Starting line number (1-based)"),
        limit: z.number().optional().describe("Limit on the number of lines to read"),
      }),
      execute: async (args) => {
        try {
          const fullPath = path.resolve(workDir, args.file_path)
          const content = fs.readFileSync(fullPath, "utf-8")
          const lines = content.split("\n")

          const start = (args.offset || 1) - 1
          const end = args.limit ? start + args.limit : lines.length
          const selectedLines = lines.slice(start, end)

          return selectedLines
            .map((line, i) => `${start + i + 1}\t${line}`)
            .join("\n")
        } catch (error) {
          return `Error: ${error instanceof Error ? error.message : String(error)}`
        }
      },
    },

    glob: {
      description: "Search for files using glob patterns. Returns a list of matching file paths.",
      parameters: z.object({
        pattern: z.string().describe("Glob pattern, e.g., '**/*.ts' or 'src/**/*.tsx'"),
      }),
      execute: async (args) => {
        try {
          const glob = new Bun.Glob(args.pattern)
          const matches: string[] = []
          for await (const file of glob.scan({ cwd: workDir })) {
            if (!file.includes("node_modules") && !file.includes(".git")) {
              matches.push(file)
            }
          }
          return matches.length > 0
            ? matches.join("\n")
            : "No matching files found"
        } catch (error) {
          return `Error: ${error instanceof Error ? error.message : String(error)}`
        }
      },
    },

    grep: {
      description: "Search for a regular expression in file contents. Returns matching files and lines.",
      parameters: z.object({
        pattern: z.string().describe("Regular expression pattern"),
        include: z.string().optional().describe("File pattern filter, e.g., '*.ts'"),
      }),
      execute: async (args) => {
        try {
          const includeArg = args.include ? `--include='${args.include}'` : ""
          const result = execSync(
            `grep -rn ${includeArg} '${args.pattern}' . 2>/dev/null | head -50`,
            { cwd: workDir, encoding: "utf-8", timeout: 10000 }
          )
          return result || "No matching content found"
        } catch {
          return "No matching content found"
        }
      },
    },
  }
}
```

Create `src/tools/file-tools.ts`:

```typescript
import { z } from "zod"
import type { CoreTool } from "ai"
import * as fs from "fs"
import * as path from "path"
import { execSync } from "child_process"

export function createFileTools(workDir: string): Record<string, CoreTool> {
  // Include base functionality from search tools
  const searchTools = (await import("./search-tools")).createSearchTools(workDir)

  return {
    // Inherit the read tool
    read: searchTools.read,

    edit: {
      description:
        "Precisely replace content in a file. old_string must exist exactly once in the file.",
      parameters: z.object({
        file_path: z.string().describe("Path of the file to edit"),
        old_string: z.string().describe("The original text to replace"),
        new_string: z.string().describe("The new text to replace it with"),
      }),
      execute: async (args) => {
        try {
          const fullPath = path.resolve(workDir, args.file_path)
          const content = fs.readFileSync(fullPath, "utf-8")

          // Check that old_string exists exactly once
          const count = content.split(args.old_string).length - 1
          if (count === 0) {
            return `Error: old_string does not exist in the file`
          }
          if (count > 1) {
            return `Error: old_string appears ${count} times in the file; it must be unique`
          }

          // Perform the replacement
          const newContent = content.replace(args.old_string, args.new_string)
          fs.writeFileSync(fullPath, newContent)
          return `Successfully edited ${args.file_path}`
        } catch (error) {
          return `Error: ${error instanceof Error ? error.message : String(error)}`
        }
      },
    },

    write: {
      description: "Write content to a file. If the file already exists, it will be overwritten.",
      parameters: z.object({
        file_path: z.string().describe("Path of the file to write"),
        content: z.string().describe("File content"),
      }),
      execute: async (args) => {
        try {
          const fullPath = path.resolve(workDir, args.file_path)
          // Ensure the directory exists
          fs.mkdirSync(path.dirname(fullPath), { recursive: true })
          fs.writeFileSync(fullPath, args.content)
          return `Successfully wrote to ${args.file_path}`
        } catch (error) {
          return `Error: ${error instanceof Error ? error.message : String(error)}`
        }
      },
    },

    bash: {
      description: "Execute a shell command. Used for running tests, installing dependencies, etc.",
      parameters: z.object({
        command: z.string().describe("The command to execute"),
      }),
      execute: async (args) => {
        // Safety check: prohibit dangerous commands
        const dangerous = ["rm -rf /", "git push --force", ":(){ :|:& };:"]
        if (dangerous.some((d) => args.command.includes(d))) {
          return "Error: This command is prohibited by the security policy"
        }

        try {
          const result = execSync(args.command, {
            cwd: workDir,
            encoding: "utf-8",
            timeout: 30000, // 30-second timeout
          })
          return result.slice(0, 10000) // Truncate overly long output
        } catch (error) {
          return `Command execution failed: ${error instanceof Error ? error.message : String(error)}`
        }
      },
    },
  }
}
```

### Step 6: Implement the Task Tool (Core)

Create `src/tools/task-tool.ts` -- this is the key to implementing Agent orchestration:

```typescript
import { z } from "zod"
import type { CoreTool } from "ai"
import type { SessionManager } from "../session/manager"

export function createTaskTool(
  sessionManager: SessionManager,
  executeAgent: (agentName: string, task: string, parentSessionId: string) => Promise<string>
): Record<string, CoreTool> {
  return {
    task: {
      description: `Delegate a task to a specialized sub-Agent for execution. Available Agents:
- researcher: Code search and information gathering specialist (low cost)
- coder: Code writing and modification specialist (high cost)

When to use: Delegate when the task requires specialized capabilities; answer simple questions directly without delegation.`,
      parameters: z.object({
        agent: z.enum(["researcher", "coder"]).describe("Target Agent name"),
        description: z.string().describe(
          "Detailed task description. Format: TASK: task | CONTEXT: context | EXPECTED_OUTCOME: expected output"
        ),
      }),
      execute: async (args) => {
        console.log(`\n📋 Commander delegating task to ${args.agent}:`)
        console.log(`   ${args.description.slice(0, 100)}...`)

        try {
          // Get the current Commander's session ID
          const commanderSession = [...sessionManager.list()]
            .filter((s) => s.agentName === "commander" && s.status === "active")
            .pop()

          const parentId = commanderSession?.id || "root"

          // Execute the sub-Agent
          const result = await executeAgent(args.agent, args.description, parentId)

          console.log(`✅ ${args.agent} completed the task`)
          return `[Result from ${args.agent}]\n\n${result}`
        } catch (error) {
          console.log(`❌ ${args.agent} execution failed`)
          return `[${args.agent} execution failed] ${error instanceof Error ? error.message : String(error)}`
        }
      },
    },
  }
}
```

The design of this `task` tool directly corresponds to the core idea of `tool/task.ts` in OpenCode (Section 5.3.5):

* **Creating a child session**: A separate session is created for the sub-Agent via `sessionManager.create()`
* **Agent permission filtering**: The available delegation targets are restricted via `z.enum(["researcher", "coder"])`
* **Result propagation**: The sub-Agent's execution result is returned as the `task` tool's return value, flowing back into Commander's context

### Step 7: Implement the Core Execution Engine

Create `src/index.ts` -- assembling all components together:

```typescript
import { streamText } from "ai"
import { openai } from "@ai-sdk/openai"
import { createInterface } from "readline"
import { SessionManager } from "./session/manager"
import { createCommander } from "./agents/commander"
import { createResearcher } from "./agents/researcher"
import { createCoder } from "./agents/coder"
import type { AgentDefinition, Session } from "./types"
import type { CoreMessage } from "ai"

// ===== Global State =====
const sessionManager = new SessionManager()
const workDir = process.cwd()

// ===== Agent Execution Engine =====
async function executeAgent(
  agentName: string,
  task: string,
  parentSessionId: string
): Promise<string> {
  // Find the Agent definition
  const agent = agents[agentName]
  if (!agent) {
    throw new Error(`Unknown Agent: ${agentName}`)
  }

  // Create a child session
  const session = sessionManager.create(agentName, parentSessionId)
  console.log(`\n🔄 [${agentName}] Starting execution (session: ${session.id})`)

  // Initialize messages
  session.messages = [
    { role: "user", content: task },
  ]

  // Agentic Loop: keep calling the LLM until there are no more tool calls
  let steps = 0
  let finalText = ""

  while (steps < agent.maxSteps) {
    steps++

    const result = await streamText({
      model: openai(agent.model),
      system: agent.systemPrompt,
      messages: session.messages,
      tools: agent.tools,
      maxSteps: 1, // Only one step at a time; we control the loop manually
    })

    // Collect the full response
    let text = ""
    const toolCalls: any[] = []
    const toolResults: any[] = []

    for await (const part of result.fullStream) {
      if (part.type === "text-delta") {
        text += part.textDelta
      }
      if (part.type === "tool-call") {
        toolCalls.push(part)
      }
      if (part.type === "tool-result") {
        toolResults.push(part)
      }
    }

    // Update session messages
    if (text) {
      session.messages.push({ role: "assistant", content: text })
      finalText = text
    }

    // If there are no tool calls, the Agent has completed its task
    if (toolCalls.length === 0) {
      break
    }

    // Add tool calls and results to the message history
    session.messages.push({
      role: "assistant",
      content: toolCalls.map((tc) => ({
        type: "tool-call" as const,
        toolCallId: tc.toolCallId,
        toolName: tc.toolName,
        args: tc.args,
      })),
    })

    session.messages.push({
      role: "tool",
      content: toolResults.map((tr) => ({
        type: "tool-result" as const,
        toolCallId: tr.toolCallId,
        toolName: tr.toolName,
        result: tr.result,
      })),
    })

    console.log(
      `   [${agentName}] Step ${steps}: called ${toolCalls.map((t) => t.toolName).join(", ")}`
    )
  }

  // Complete the session
  sessionManager.complete(session.id, finalText)
  console.log(`✅ [${agentName}] Completed (${steps} steps)`)
  return finalText
}

// ===== Agent Registry =====
const agents: Record<string, AgentDefinition> = {}

function registerAgents() {
  const researcher = createResearcher(workDir)
  const coder = createCoder(workDir)
  const commander = createCommander(workDir, sessionManager, executeAgent)

  agents[researcher.name] = researcher
  agents[coder.name] = coder
  agents[commander.name] = commander
}

// ===== Main Interaction Loop =====
async function main() {
  registerAgents()
  const commanderSession = sessionManager.create("commander")

  console.log("🤖 Multi-Agent Orchestration System started")
  console.log("   Commander (Chief Orchestrator) is ready")
  console.log("   Available sub-Agents: researcher, coder")
  console.log("   Type /sessions to view session status")
  console.log("   Type /quit to exit\n")

  const rl = createInterface({
    input: process.stdin,
    output: process.stdout,
  })

  const prompt = () => {
    rl.question("You> ", async (input) => {
      const trimmed = input.trim()

      if (!trimmed) {
        prompt()
        return
      }

      // Built-in commands
      if (trimmed === "/quit") {
        console.log("Goodbye!")
        rl.close()
        return
      }

      if (trimmed === "/sessions") {
        const sessions = sessionManager.list()
        console.log("\n📊 Session list:")
        for (const s of sessions) {
          console.log(
            `   ${s.id} | ${s.agentName} | ${s.status} | messages: ${s.messages.length} | parent: ${s.parentSessionId || "none"}`
          )
        }
        console.log()
        prompt()
        return
      }

      // Send to the Commander Agent
      try {
        commanderSession.messages.push({ role: "user", content: trimmed })

        const commander = agents["commander"]
        let steps = 0
        let lastText = ""

        // Commander's Agentic Loop
        while (steps < commander.maxSteps) {
          steps++

          const result = await streamText({
            model: openai(commander.model),
            system: commander.systemPrompt,
            messages: commanderSession.messages,
            tools: commander.tools,
            maxSteps: 1,
          })

          let text = ""
          const toolCalls: any[] = []
          const toolResults: any[] = []

          // Stream Commander's text response
          for await (const part of result.fullStream) {
            if (part.type === "text-delta") {
              process.stdout.write(part.textDelta)
              text += part.textDelta
            }
            if (part.type === "tool-call") {
              toolCalls.push(part)
            }
            if (part.type === "tool-result") {
              toolResults.push(part)
            }
          }

          if (text) {
            commanderSession.messages.push({
              role: "assistant",
              content: text,
            })
            lastText = text
          }

          if (toolCalls.length === 0) break

          // Add tool call history
          commanderSession.messages.push({
            role: "assistant",
            content: toolCalls.map((tc) => ({
              type: "tool-call" as const,
              toolCallId: tc.toolCallId,
              toolName: tc.toolName,
              args: tc.args,
            })),
          })

          commanderSession.messages.push({
            role: "tool",
            content: toolResults.map((tr) => ({
              type: "tool-result" as const,
              toolCallId: tr.toolCallId,
              toolName: tr.toolName,
              result: tr.result,
            })),
          })
        }

        console.log("\n")
      } catch (error) {
        console.error(
          "❌ Error:",
          error instanceof Error ? error.message : String(error)
        )
      }

      prompt()
    })
  }

  prompt()
}

main().catch(console.error)
```

### Step 8: Running and Testing

```bash
# Set the API Key
export OPENAI_API_KEY="your-key-here"

# Run
bun run src/index.ts
```

Test scenarios:

```
You> Show me the directory structure and main files of this project

🔄 [researcher] Starting execution (session: ses_a1b2c3)
   [researcher] Step 1: called glob
   [researcher] Step 2: called read
✅ [researcher] Completed (3 steps)

Commander: Based on Researcher's analysis, the project structure is as follows...
```

```
You> Create a format-date.ts file under src/utils/ that implements a date formatting function

🔄 [coder] Starting execution (session: ses_d4e5f6)
   [coder] Step 1: called write
✅ [coder] Completed (1 step)

Commander: Coder has created src/utils/format-date.ts...
```

```
You> /sessions
📊 Session list:
   ses_main01 | commander | active | messages: 8 | parent: none
   ses_a1b2c3 | researcher | completed | messages: 6 | parent: ses_main01
   ses_d4e5f6 | coder | completed | messages: 4 | parent: ses_main01
```

## 17.5.4 Advanced: Adding Parallel Task Execution

oh-my-opencode's background Agent system (Section 15.6.1) supports **parallel execution of multiple sub-Agents**. Let us add this capability to our system:

```typescript
// Add the parallel_tasks tool in src/tools/task-tool.ts

parallel_tasks: {
  description: "Execute multiple sub-Agent tasks in parallel. All tasks start simultaneously, and results are returned after all complete.",
  parameters: z.object({
    tasks: z.array(z.object({
      agent: z.enum(["researcher", "coder"]),
      description: z.string(),
    })).describe("List of tasks to execute in parallel"),
  }),
  execute: async (args) => {
    console.log(`\n🔀 Executing ${args.tasks.length} tasks in parallel...`)

    const commanderSession = [...sessionManager.list()]
      .filter((s) => s.agentName === "commander" && s.status === "active")
      .pop()
    const parentId = commanderSession?.id || "root"

    // Execute all tasks in parallel
    const results = await Promise.allSettled(
      args.tasks.map((task, i) =>
        executeAgent(task.agent, task.description, parentId)
          .then((result) => ({ index: i, agent: task.agent, result }))
      )
    )

    // Organize results
    const output = results.map((r, i) => {
      if (r.status === "fulfilled") {
        return `### Task ${i + 1} (${r.value.agent}) — Success\n${r.value.result}`
      } else {
        return `### Task ${i + 1} (${args.tasks[i].agent}) — Failed\n${r.reason}`
      }
    })

    return output.join("\n\n---\n\n")
  },
},
```

We use `Promise.allSettled` rather than `Promise.all` so that even if one sub-Agent fails, the other tasks can still complete normally -- this is precisely the **defensive programming** philosophy of oh-my-opencode.

## 17.5.5 Advanced: Doom Loop Detection

Recall the Doom Loop detection mechanism analyzed in Section 4.4.2 -- when an Agent repeatedly calls the same tool and gets the same result, it indicates a stuck loop. Let us add this protection:

```typescript
// Add Doom Loop detection in the executeAgent function

const DOOM_LOOP_THRESHOLD = 3
const recentToolCalls: string[] = []

// Check after each tool call
const callSignature = `${toolCall.toolName}:${JSON.stringify(toolCall.args)}`
recentToolCalls.push(callSignature)

// Check whether recent calls are repetitive
if (recentToolCalls.length >= DOOM_LOOP_THRESHOLD) {
  const recent = recentToolCalls.slice(-DOOM_LOOP_THRESHOLD)
  const allSame = recent.every((c) => c === recent[0])

  if (allSame) {
    console.log(`⚠️ [${agentName}] Doom Loop detected, forcing termination`)
    session.messages.push({
      role: "user",
      content:
        "You seem to be repeating the same operation. Please stop, summarize " +
        "what you have learned so far, and respond directly with text. " +
        "Do not call any more tools.",
    })
    // Don't break -- give the Agent a chance to respond
  }
}
```

## 17.5.6 Key Takeaways

Through this lab, we implemented a multi-Agent system containing the following core mechanisms:

| Concept                                  | Corresponding Chapter             | Implementation                                        |
| ---------------------------------------- | --------------------------------- | ----------------------------------------------------- |
| Agent definition and prompt engineering  | Chapter 6: Agent System           | `AgentDefinition` + carefully designed System Prompts |
| Session management and context isolation | Chapter 4: Session System         | `SessionManager` + parent-child session association   |
| Task tool and task delegation            | Section 5.3.5: task tool          | `task` tool + `executeAgent()`                        |
| Agentic Loop                             | Section 4.4: SessionProcessor     | `while` loop + tool call detection                    |
| Doom Loop detection                      | Section 4.4.2                     | Duplicate call signature checking                     |
| Parallel execution                       | Section 15.6.1: Background Agents | `Promise.allSettled()`                                |
| Defensive programming                    | Section 15.5: Hook System         | Error recovery, timeout protection, safety checks     |

**The gap between this lab and a production-grade product**:

While our simplified system demonstrates the core concepts, compared to the production-grade implementation of OpenCode + oh-my-opencode, it still lacks:

1. **Persistent storage**: Our sessions live in memory and are lost on exit. OpenCode uses file storage (Chapter 10)
2. **Streaming UI**: We only have simple console.log. OpenCode has a full TUI (Chapter 12)
3. **Permission system**: Our safety checks are hardcoded. OpenCode has a complete permission evaluation engine (Chapter 9)
4. **Snapshot rollback**: We have no file change snapshots. OpenCode can undo all modifications (Section 10.1)
5. **Context compression**: We have no compaction. Long conversations will exceed token limits (Section 4.5)
6. **53 Hooks**: oh-my-opencode's Hook system provides extremely fine-grained behavioral control

But the core idea is the same: **Through Agent division of labor + a tool system + session management, build an AI system capable of autonomously completing complex programming tasks**. Once you understand these core concepts, you have the foundation to build a similar system from scratch.
