> 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_15_oh-my-opencode_deep_dive/15.3_multi-agent_system.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 15.3 Multi-Agent System

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

***

oh-my-opencode's most core innovation lies in its **multi-Agent orchestration system**. Rather than simply configuring a more powerful Agent, it defines a "team" composed of multiple role-based Agents. Through the main Agent's intent classification and delegation decisions, different types of tasks are assigned to the most suitable specialist Agents.

## 15.3.1 Agent Classification and Role Design

oh-my-opencode defines 11 built-in Agents, each with a clear role, operating mode, and cost level:

| Agent             | Role                                 | Mode     | Cost      | Category    |
| ----------------- | ------------------------------------ | -------- | --------- | ----------- |
| Sisyphus          | Main Agent / Orchestrator            | primary  | EXPENSIVE | utility     |
| Oracle            | Senior Technical Advisor (read-only) | subagent | EXPENSIVE | advisor     |
| Explore           | Codebase Search Expert               | subagent | FREE      | exploration |
| Librarian         | External Resource Researcher         | subagent | CHEAP     | exploration |
| Prometheus        | Task Planner                         | subagent | EXPENSIVE | specialist  |
| Metis             | Pre-planning Analyst                 | subagent | EXPENSIVE | advisor     |
| Momus             | Plan Review Expert                   | subagent | EXPENSIVE | advisor     |
| Hephaestus        | Autonomous Craftsman Executor        | primary  | EXPENSIVE | utility     |
| Atlas             | Project Navigator                    | primary  | EXPENSIVE | utility     |
| Sisyphus Junior   | Lightweight Task Execution           | subagent | CHEAP     | utility     |
| Multimodal Looker | Multimodal Analysis                  | subagent | CHEAP     | specialist  |

### Agent Type System

Each Agent defines its key attributes through the TypeScript type system:

```typescript
// oh-my-opencode/src/agents/types.ts

/**
 * Agent mode determines UI model selection behavior:
 * - "primary": Respects the model selected by the user in the UI (e.g., Sisyphus, Atlas)
 * - "subagent": Uses its own fallback chain, ignoring UI selection (e.g., Oracle, Explore)
 * - "all": Available in both contexts (OpenCode compatibility)
 */
export type AgentMode = "primary" | "subagent" | "all"

/**
 * Agent category, used for grouping display in the Sisyphus Prompt
 */
export type AgentCategory = "exploration" | "specialist" | "advisor" | "utility"

/**
 * Cost classification, used for tool selection tables
 */
export type AgentCost = "FREE" | "CHEAP" | "EXPENSIVE"
```

There is an important design decision here: **Mode** distinguishes how an Agent obtains its model. `primary` mode Agents (such as Sisyphus) use the model manually selected by the user in the UI -- meaning users can freely switch Sisyphus between Claude Opus and GPT-5. Meanwhile, `subagent` mode Agents (such as Oracle, Explore) use predefined models unaffected by UI selection -- ensuring that sub-Agents always use the model best suited to their role.

### Agent Factory Pattern

Agent creation follows the **factory function** pattern. Each Agent file exports a factory function that takes a model name as a parameter and returns an `AgentConfig` object:

```typescript
// oh-my-opencode/src/agents/types.ts
export type AgentFactory = ((model: string) => AgentConfig) & {
  mode: AgentMode  // Mode attached as a static property on the function
}
```

All built-in Agent factory functions are centrally registered in `builtin-agents.ts`:

```typescript
// oh-my-opencode/src/agents/builtin-agents.ts
const agentSources: Record<BuiltinAgentName, AgentSource> = {
  sisyphus: createSisyphusAgent,
  hephaestus: createHephaestusAgent,
  oracle: createOracleAgent,
  librarian: createLibrarianAgent,
  explore: createExploreAgent,
  "multimodal-looker": createMultimodalLookerAgent,
  metis: createMetisAgent,
  momus: createMomusAgent,
  atlas: createAtlasAgent,
}
```

### Agent Prompt Metadata

A unique design in oh-my-opencode is **Agent Prompt Metadata (AgentPromptMetadata)**. Each Agent not only defines its own behavioral Prompt but also declares a set of structured metadata describing "under what circumstances it should be invoked":

```typescript
// oh-my-opencode/src/agents/types.ts
export interface AgentPromptMetadata {
  category: AgentCategory          // Grouping category
  cost: AgentCost                  // Cost level
  triggers: DelegationTrigger[]    // Delegation trigger conditions
  useWhen?: string[]               // Applicable scenarios
  avoidWhen?: string[]             // Inapplicable scenarios
  dedicatedSection?: string        // Dedicated Prompt section
  promptAlias?: string             // Alias used in Prompt
  keyTrigger?: string              // Phase 0 key trigger condition
}
```

For example, Oracle's metadata declares that it should be used for architecture decisions and difficult debugging:

```typescript
// oh-my-opencode/src/agents/oracle.ts
export const ORACLE_PROMPT_METADATA: AgentPromptMetadata = {
  category: "advisor",
  cost: "EXPENSIVE",
  promptAlias: "Oracle",
  triggers: [
    { domain: "Architecture decisions", trigger: "Multi-system tradeoffs, unfamiliar patterns" },
    { domain: "Self-review", trigger: "After completing significant implementation" },
    { domain: "Hard debugging", trigger: "After 2+ failed fix attempts" },
  ],
  useWhen: [
    "Complex architecture design",
    "After completing significant work",
    "2+ failed fix attempts",
    "Security/performance concerns",
  ],
  avoidWhen: [
    "Simple file operations (use direct tools)",
    "First attempt at any fix (try yourself first)",
    "Questions answerable from code you've read",
  ],
}
```

The **consumer** of this metadata is not human developers, but the Sisyphus main Agent. Sisyphus's Prompt dynamically incorporates this metadata, telling Sisyphus under what conditions it should delegate tasks to Oracle.

## 15.3.2 Agent Dynamic Prompt Builder

`dynamic-agent-prompt-builder.ts` is one of the most ingenious modules in oh-my-opencode. It takes all Agent metadata as input and **dynamically generates** the portion of the Sisyphus main Agent's Prompt that describes "how to use sub-Agents."

> **Extended Explanation: What is a Dynamic Prompt?**
>
> In traditional LLM applications, the System Prompt is typically static -- a hardcoded text string in the code. In oh-my-opencode, however, Sisyphus's Prompt is **dynamically generated at runtime**. It assembles the complete Prompt in real time based on the currently enabled Agent list, available Skills, Category configurations, and other information.
>
> This means: if a user disables the Oracle Agent through configuration, Sisyphus's Prompt will not contain any guidance about "when to use Oracle" -- fundamentally preventing Sisyphus from attempting to call a nonexistent Agent.

### Builder Function Overview

The dynamic Prompt builder provides 8 core building functions:

```typescript
// oh-my-opencode/src/agents/dynamic-agent-prompt-builder.ts

// 1. Key triggers section: triggers checked before intent classification
buildKeyTriggersSection(agents, skills)

// 2. Tool selection table: Agents and tools listed by cost
buildToolSelectionTable(agents, tools, skills)

// 3. Explore usage guide section
buildExploreSection(agents)

// 4. Librarian usage guide section
buildLibrarianSection(agents)

// 5. Delegation decision table: when to delegate what to whom
buildDelegationTable(agents)

// 6. Category + Skill delegation guide: how to choose Category and Skill
buildCategorySkillsDelegationGuide(categories, skills)

// 7. Oracle usage guide section
buildOracleSection(agents)

// 8. Tool classifier: groups tools by type
categorizeTools(toolNames)
```

### Key Triggers

`buildKeyTriggersSection()` extracts trigger conditions from each Agent's `keyTrigger` field and generates a checklist:

```typescript
export function buildKeyTriggersSection(agents, skills): string {
  const keyTriggers = agents
    .filter((a) => a.metadata.keyTrigger)
    .map((a) => `- ${a.metadata.keyTrigger}`)

  return `### Key Triggers (check BEFORE classification):

${keyTriggers.join("\n")}
- **"Look into" + "create PR"** → Not just research. Full implementation cycle expected.`
}
```

The resulting Prompt fragment looks like:

```markdown
### Key Triggers (check BEFORE classification):

- External library/source mentioned → fire `librarian` background
- 2+ modules involved → fire `explore` background
- **"Look into" + "create PR"** → Not just research.
```

### Tool Selection Table

`buildToolSelectionTable()` generates an Agent and tool recommendation table sorted by cost. It first lists free direct tools, then lists Agents in FREE -> CHEAP -> EXPENSIVE order:

```typescript
export function buildToolSelectionTable(agents, tools, skills): string {
  const rows = ["### Tool & Agent Selection:", ""]

  // List free direct tools first
  if (tools.length > 0) {
    const toolsDisplay = formatToolsForPrompt(tools)
    rows.push(`- ${toolsDisplay} — **FREE** — Not Complex, Scope Clear`)
  }

  // Then list Agents sorted by cost
  const costOrder = { FREE: 0, CHEAP: 1, EXPENSIVE: 2 }
  const sortedAgents = [...agents]
    .filter((a) => a.metadata.category !== "utility")
    .sort((a, b) => costOrder[a.metadata.cost] - costOrder[b.metadata.cost])

  for (const agent of sortedAgents) {
    rows.push(`- \`${agent.name}\` agent — **${agent.metadata.cost}** — ${shortDesc}`)
  }

  return rows.join("\n")
}
```

### Tool Classification

`categorizeTools()` automatically classifies tool names by prefix:

```typescript
export function categorizeTools(toolNames: string[]): AvailableTool[] {
  return toolNames.map((name) => {
    let category: "lsp" | "ast" | "search" | "session" | "command" | "other" = "other"
    if (name.startsWith("lsp_"))      category = "lsp"
    else if (name.startsWith("ast_grep")) category = "ast"
    else if (name === "grep" || name === "glob") category = "search"
    else if (name.startsWith("session_")) category = "session"
    else if (name === "slashcommand") category = "command"
    return { name, category }
  })
}
```

### Category + Skill Delegation Guide

`buildCategorySkillsDelegationGuide()` is the most complex builder function. It generates a **three-step protocol** that tells Sisyphus how to select the correct Category and Skill for subtasks:

```markdown
### MANDATORY: Category + Skill Selection Protocol

**STEP 1: Select Category**
- Read each category's description
- Match task requirements to category domain

**STEP 2: Evaluate ALL Skills (Built-in AND User-Installed)**
For EVERY skill listed above, ask yourself:
> "Does this skill's expertise domain overlap with my task?"
- If YES → INCLUDE in `load_skills=[...]`
- If NO → You MUST justify why

**STEP 3: Justify Omissions**
If you choose NOT to include a skill that MIGHT be relevant, provide:
```

SKILL EVALUATION for "\[skill-name]":

* Skill domain: \[what the skill description says]
* Task domain: \[what your task is about]
* Decision: OMIT
* Reason: \[specific explanation]

```
```

This design places particular emphasis on **user-installed Skills**. It distinguishes between `plugin`-type built-in Skills (provided by oh-my-opencode) and `user`/`project`-type custom Skills (installed by users). For user-installed Skills, the Prompt includes emphasized warnings requiring Sisyphus to prioritize these Skills.

## 15.3.3 Sisyphus Main Agent Deep Dive

Sisyphus is the "commander" of the entire system. Its Prompt is the most complex of all Agents -- assembled from multiple dynamically built sections.

### Prompt Assembly

```typescript
// oh-my-opencode/src/agents/sisyphus.ts
function buildDynamicSisyphusPrompt(
  availableAgents, availableTools, availableSkills,
  availableCategories, useTaskSystem
): string {
  const keyTriggers = buildKeyTriggersSection(availableAgents, availableSkills)
  const toolSelection = buildToolSelectionTable(availableAgents, availableTools, availableSkills)
  const exploreSection = buildExploreSection(availableAgents)
  const librarianSection = buildLibrarianSection(availableAgents)
  const categorySkillsGuide = buildCategorySkillsDelegationGuide(availableCategories, availableSkills)
  const delegationTable = buildDelegationTable(availableAgents)
  const oracleSection = buildOracleSection(availableAgents)
  const hardBlocks = buildHardBlocksSection()
  const antiPatterns = buildAntiPatternsSection()
  const taskManagementSection = buildTaskManagementSection(useTaskSystem)

  return `<Role>
You are "Sisyphus" - Powerful AI Agent with orchestration capabilities...
</Role>
<Behavior_Instructions>
## Phase 0 - Intent Gate (EVERY message)
${keyTriggers}
...
## Phase 2A - Exploration & Research
${toolSelection}
${exploreSection}
${librarianSection}
...
## Phase 2B - Implementation
${categorySkillsGuide}
${delegationTable}
...
</Behavior_Instructions>
${oracleSection}
${taskManagementSection}
<Constraints>
${hardBlocks}
${antiPatterns}
</Constraints>`
}
```

### The Four Behavioral Phases

Sisyphus's behavior is organized into four phases:

**Phase 0 -- Intent Gate**: A classification step that every message must pass through.

```
1. Classify request type: Trivial / Explicit / Exploratory / Open-ended / Ambiguous
2. Check for ambiguity: If multiple interpretations differ by more than 2x in effort, must ask
3. Pre-execution validation: Check assumptions, confirm delegation decisions
```

**Phase 1 -- Codebase Assessment**: For open-ended tasks, first assess the codebase's maturity.

```
Quick Assessment:
1. Check config files: linter, formatter, type config
2. Sample 2-3 similar files to check consistency
3. Judge project age signals

State Classification:
- Disciplined → Strictly follow existing style
- Transitional → Ask the user which pattern to follow
- Legacy/Chaotic → Suggest new patterns
- Greenfield → Apply modern best practices
```

**Phase 2 -- Execution**: Split into 2A (Exploration & Research), 2B (Implementation), and 2C (Failure Recovery).

**Phase 3 -- Completion**: Verification checklist and delivery.

### Delegation Protocol

Sisyphus's Prompt defines a strict **6-section delegation protocol** requiring complete context for every subtask delegation:

```
1. TASK: An atomic, specific goal (one action per delegation)
2. EXPECTED OUTCOME: Concrete deliverables and success criteria
3. REQUIRED TOOLS: Explicit tool whitelist
4. MUST DO: Exhaustive mandatory requirements
5. MUST NOT DO: Prohibited behaviors
6. CONTEXT: File paths, existing patterns, constraints
```

The philosophy behind this protocol is: sub-Agents are **stateless** -- they have no knowledge of what the main Agent did previously. Therefore, each delegation must provide sufficient context for the sub-Agent to complete the task independently.

## 15.3.4 Oracle Advisory Agent

Oracle is a **read-only advisor** -- it only analyzes and provides recommendations without directly modifying code.

```typescript
// oh-my-opencode/src/agents/oracle.ts
export function createOracleAgent(model: string): AgentConfig {
  const restrictions = createAgentToolRestrictions([
    "write", "edit", "task", "call_omo_agent",  // Prohibit writing and delegation
  ])

  return {
    description: 'Read-only technical advisor...',
    mode: "subagent",
    model,
    temperature: 0.3,
    ...restrictions,
    prompt: ORACLE_SYSTEM_PROMPT,
  }
}
```

Oracle's Prompt defines three key frameworks:

### Decision Framework (Pragmatic Minimalism)

```markdown
Apply pragmatic minimalism in all recommendations:
- **Bias toward simplicity**: The right solution is typically the least complex one.
- **Leverage what exists**: Favor modifications to current code over new components.
- **Prioritize developer experience**: Optimize for readability and maintainability.
- **One clear path**: Present a single primary recommendation.
- **Match depth to complexity**: Quick questions get quick answers.
- **Signal the investment**: Tag recommendations with effort estimates.
- **Know when to stop**: "Working well" beats "theoretically optimal."
```

### Output Verbosity Control

Oracle has strict limits on output length:

```markdown
Verbosity constraints (strictly enforced):
- **Bottom line**: 2-3 sentences maximum. No preamble.
- **Action plan**: ≤7 numbered steps. Each step ≤2 sentences.
- **Why this approach**: ≤4 bullets.
- **Watch out for**: ≤3 bullets.
```

### Three-Tier Response Structure

```markdown
**Essential** (always include):
- Bottom line: 2-3 sentences
- Action plan: Numbered steps
- Effort estimate: Quick/Short/Medium/Large

**Expanded** (include when relevant):
- Why this approach
- Watch out for
- Edge cases

**Deep** (only on request):
- Alternative analysis
- Full trade-off matrix
```

## 15.3.5 Prometheus Planning Agent

Prometheus is a specialized **task planner**. Its Prompt is split into 6 independent modules, embodying the principle of separation of concerns:

```typescript
// oh-my-opencode/src/agents/prometheus/system-prompt.ts
export const PROMETHEUS_SYSTEM_PROMPT = `
  ${PROMETHEUS_IDENTITY_CONSTRAINTS}    // Identity constraints
  ${PROMETHEUS_INTERVIEW_MODE}          // Interview mode
  ${PROMETHEUS_PLAN_GENERATION}         // Plan generation
  ${PROMETHEUS_HIGH_ACCURACY_MODE}      // High accuracy mode
  ${PROMETHEUS_PLAN_TEMPLATE}           // Plan template
  ${PROMETHEUS_BEHAVIORAL_SUMMARY}      // Behavioral summary
`
```

Each module's responsibilities:

| Module                    | Function                                                                             |
| ------------------------- | ------------------------------------------------------------------------------------ |
| `identity-constraints.ts` | Defines Prometheus's role boundaries -- it can only plan, not execute                |
| `interview-mode.ts`       | "Interviews" the user to clarify requirements, resolving ambiguity through questions |
| `plan-generation.ts`      | Converts requirements into structured execution plans                                |
| `high-accuracy-mode.ts`   | Self-validates plans, checking for omissions and contradictions                      |
| `plan-template.ts`        | Defines the standard format for plan documents                                       |
| `behavioral-summary.ts`   | Concise summary of behavioral norms                                                  |

Prometheus's permissions are strictly limited:

```typescript
export const PROMETHEUS_PERMISSION = {
  edit: "allow",      // Allow editing (writing plan files)
  bash: "allow",      // Allow running bash (exploring the project)
  webfetch: "allow",  // Allow web requests (looking up references)
  question: "allow",  // Allow asking questions (interviewing the user)
}
```

Note that it has edit permission but not execution permission -- Prometheus can write plan documents but will not execute the plans. A dedicated `prometheus-md-only` hook ensures that Prometheus can only edit `.md` files.

## 15.3.6 Agent Builder -- Unified Agent Construction Factory

`agent-builder.ts` provides a unified Agent construction function that handles Category inheritance and Skill injection:

```typescript
// oh-my-opencode/src/agents/agent-builder.ts
export function buildAgent(
  source: AgentSource,
  model: string,
  categories?: CategoriesConfig,
  gitMasterConfig?: GitMasterConfig,
  browserProvider?: BrowserAutomationProvider,
  disabledSkills?: Set<string>
): AgentConfig {
  // 1. Call the factory function or use static configuration
  const base = isFactory(source) ? source(model) : { ...source }

  // 2. Category inheritance: if the Agent specifies a category, inherit model, temperature, etc.
  const categoryConfigs = mergeCategories(categories)
  if (agentWithCategory.category) {
    const categoryConfig = categoryConfigs[agentWithCategory.category]
    if (categoryConfig) {
      if (!base.model) base.model = categoryConfig.model
      if (base.temperature === undefined) base.temperature = categoryConfig.temperature
      if (base.variant === undefined) base.variant = categoryConfig.variant
    }
  }

  // 3. Skill injection: resolve Skill content and prepend to Prompt
  if (agentWithCategory.skills?.length) {
    const { resolved } = resolveMultipleSkills(agentWithCategory.skills, { ... })
    if (resolved.size > 0) {
      const skillContent = Array.from(resolved.values()).join("\n\n")
      base.prompt = skillContent + (base.prompt ? "\n\n" + base.prompt : "")
    }
  }

  return base
}
```

This builder embodies the **composition over inheritance** design principle:

1. **Category mechanism**: Agents do not specify models directly but declare which Category they belong to. Categories define models and parameters, and multiple Agents can share the same Category. This allows users to simultaneously affect multiple Agents by modifying a single Category configuration.
2. **Skill injection**: Agents declare which Skills they need, and the builder automatically parses the Skill Markdown content and injects it before the Agent's Prompt. This achieves "composability of knowledge" -- a `git-master` Skill can be injected into any Agent that needs Git operation expertise.

## 15.3.7 Environment Context Injection

`env-context.ts` injects runtime environment information into Agents:

```typescript
// oh-my-opencode/src/agents/env-context.ts
export function createEnvContext(): string {
  const now = new Date()
  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
  const locale = Intl.DateTimeFormat().resolvedOptions().locale

  return `
<omo-env>
  Current date: ${dateStr}
  Current time: ${timeStr}
  Timezone: ${timezone}
  Locale: ${locale}
</omo-env>`
}
```

This seemingly simple function addresses a fundamental limitation of LLMs: **LLMs have no intrinsic concept of time**. A model's training data has a cutoff date, and it doesn't know what "now" is. By injecting real-time date, time, and timezone information, Agents can make time-aware correct decisions -- for example, the Librarian Agent should search for documentation from the current year.

It is worth noting that `env-context.ts` only injects information that OpenCode itself **does not provide** (time, timezone, locale), avoiding duplication with OpenCode's `system.ts`.

> **Extended Explanation: What is "Role Prompting" in Prompt Engineering?**
>
> In LLM applications, "Role Prompting" is a common prompt engineering technique. By assigning the model a specific role identity in the System Prompt (e.g., "You are a code review expert"), the model can be guided to produce more professional and focused responses.
>
> oh-my-opencode takes this technique to the extreme: rather than simply saying "you are an expert," it defines complete behavioral specifications for each role -- including when to intervene, when to step back, output format constraints, decision frameworks, and more. This depth of role definition makes each Agent's behavior more predictable and controllable.
>
> From an engineering perspective, this approach transforms Prompts from "magic incantations" into "maintainable code" -- each Agent's behavioral specification is modularly defined, tested, and maintained.

## Section Summary

The core innovations of oh-my-opencode's multi-Agent system are:

1. **Metadata-driven dynamic Prompts**: Each Agent declares its metadata (applicable scenarios, cost, trigger conditions), which is consumed by the dynamic Prompt builder to automatically generate Sisyphus main Agent's delegation decision guide. Adding or removing Agents does not require manually modifying Sisyphus's Prompt.
2. **Category + Skill composition pattern**: Agents inherit model configuration through Categories and inject professional knowledge through Skills, achieving "composability of knowledge."
3. **Tiered role design**: From the free Explore (code search) to the expensive Oracle (architecture advisor), Agents at different cost levels correspond to tasks of different complexity, balancing quality and cost.
4. **Strict delegation protocol**: The 6-section structured delegation protocol ensures sub-Agents receive sufficient context, compensating for their inherently stateless nature.
