> 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_06_agent_system/6.5_custom_agent_configuration.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 6.5 Custom Agent Configuration

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

***

OpenCode's Agent system not only provides built-in Agents but also supports users creating and customizing their own Agents through multiple methods. This section will analyze in detail three ways to define custom Agents: through the `opencode.json` configuration file, through the `.opencode/agents/` directory, and through Plugin injection.

## 6.5.1 Defining via the `agent` Field in `opencode.json`

The most straightforward customization method is adding an `agent` field in the project's `opencode.json` configuration file:

```json
{
  "agent": {
    "code-reviewer": {
      "model": "anthropic/claude-sonnet-4-20250514",
      "description": "Code review specialist that checks for bugs and best practices",
      "prompt": "You are a meticulous code reviewer...",
      "mode": "subagent",
      "temperature": 0.2,
      "color": "#4CAF50",
      "steps": 20,
      "permission": {
        "*": "deny",
        "read": "allow",
        "grep": "allow",
        "glob": "allow"
      }
    }
  }
}
```

### Config.Agent Schema

The Zod Schema for Agent configuration is defined in `config/config.ts`:

```typescript
export const Agent = z
  .object({
    model: ModelId.optional(),
    variant: z.string().optional(),
    temperature: z.number().optional(),
    top_p: z.number().optional(),
    prompt: z.string().optional(),
    tools: z.record(z.string(), z.boolean()).optional()
      .describe("@deprecated Use 'permission' field instead"),
    disable: z.boolean().optional(),
    description: z.string().optional(),
    mode: z.enum(["subagent", "primary", "all"]).optional(),
    hidden: z.boolean().optional(),
    options: z.record(z.string(), z.any()).optional(),
    color: z.union([
      z.string().regex(/^#[0-9a-fA-F]{6}$/, "Invalid hex color format"),
      z.enum(["primary", "secondary", "accent", "success",
              "warning", "error", "info"]),
    ]).optional(),
    steps: z.number().int().positive().optional(),
    maxSteps: z.number().int().positive().optional()
      .describe("@deprecated Use 'steps' field instead."),
    permission: Permission.optional(),
  })
  .catchall(z.any())
  .transform((agent, ctx) => {
    // Handle unknown properties -> options
    // Handle tools -> permission legacy compatibility
    // Handle maxSteps -> steps legacy compatibility
  })
```

This Schema definition has several clever design elements:

### Backward Compatibility Handling

```typescript
// Migrate legacy tools config to permission
const permission: Permission = {}
for (const [tool, enabled] of Object.entries(agent.tools ?? {})) {
  const action = enabled ? "allow" : "deny"
  if (tool === "write" || tool === "edit" || tool === "patch" || tool === "multiedit") {
    permission.edit = action   // Multiple edit tools are unified under the edit permission
  } else {
    permission[tool] = action
  }
}
Object.assign(permission, agent.permission)
```

OpenCode's permission system evolved from `tools` (simple boolean switches) to `permission` (fine-grained rule system). To avoid breaking existing user configurations, the Schema automatically converts the legacy `tools` format to the new `permission` format during parsing.

Similar compatibility handling also includes the `maxSteps` -> `steps` field rename.

### `.catchall(z.any())` and Options Extraction

```typescript
.catchall(z.any())
.transform((agent, ctx) => {
  const options: Record<string, unknown> = { ...agent.options }
  for (const [key, value] of Object.entries(agent)) {
    if (!knownKeys.has(key)) options[key] = value
  }
  return { ...agent, options, permission, steps }
})
```

`.catchall(z.any())` allows the configuration to contain any undefined keys, and `transform` automatically collects these unknown keys into the `options` field. This design enables users to pass Provider-specific parameters through the configuration file without OpenCode needing to know about these parameters in advance:

```json
{
  "agent": {
    "my-agent": {
      "model": "anthropic/claude-sonnet-4-20250514",
      "thinking": true,
      "budget_tokens": 10000
    }
  }
}
```

Here, `thinking` and `budget_tokens` are Anthropic Provider-specific parameters that are automatically collected into `options` and ultimately passed to the API via `providerOptions`.

### Agent Merging Logic

In the `state()` function of `agent.ts`, the merging logic between user configuration and built-in Agents is as follows:

```typescript
for (const [key, value] of Object.entries(cfg.agent ?? {})) {
  // Disable built-in Agent
  if (value.disable) {
    delete result[key]
    continue
  }

  // Get existing Agent or create new Agent
  let item = result[key]
  if (!item)
    item = result[key] = {
      name: key,
      mode: "all",
      permission: PermissionNext.merge(defaults, user),
      options: {},
      native: false,
    }

  // Override fields one by one (only override fields that are set)
  if (value.model) item.model = Provider.parseModel(value.model)
  item.variant = value.variant ?? item.variant
  item.prompt = value.prompt ?? item.prompt
  item.description = value.description ?? item.description
  item.temperature = value.temperature ?? item.temperature
  item.topP = value.top_p ?? item.topP
  item.mode = value.mode ?? item.mode
  item.color = value.color ?? item.color
  item.hidden = value.hidden ?? item.hidden
  item.name = value.name ?? item.name
  item.steps = value.steps ?? item.steps
  item.options = mergeDeep(item.options, value.options ?? {})
  item.permission = PermissionNext.merge(
    item.permission,
    PermissionNext.fromConfig(value.permission ?? {})
  )
}
```

This merging logic supports three operations:

1. **Creating a new Agent**: When `key` is not among the built-in Agents, a new Agent is created (default `mode: "all"`, `native: false`).
2. **Modifying a built-in Agent**: When `key` matches a built-in Agent, the corresponding fields are overridden with configuration values. Only fields explicitly set by the user are overridden (using the `??` operator).
3. **Disabling a built-in Agent**: `disable: true` completely removes a built-in Agent.

The flexibility of this design is reflected in several ways:

* Users can change only the `build` Agent's model without affecting other properties.
* Users can add additional permissions to the `explore` Agent without overriding its original permissions.
* `options` uses `mergeDeep` for deep merging rather than simple overwriting.

## 6.5.2 Defining via the `.opencode/agents/` Directory

For more complex Agents (especially those requiring lengthy System Prompts), OpenCode supports definition through Markdown files:

```
project-directory/
+-- .opencode/
|   +-- agents/
|       +-- security-auditor.md
|       +-- test-writer.md
```

### Markdown Agent File Format

```markdown
---
model: anthropic/claude-sonnet-4-20250514
mode: subagent
description: Security audit specialist
temperature: 0.1
steps: 30
permission:
  "*": deny
  read: allow
  grep: allow
  glob: allow
  bash: allow
---

You are a security auditing specialist focused on identifying
vulnerabilities in web applications.

## Your Responsibilities

1. **Input Validation**: Check for SQL injection, XSS, and
   other injection attacks
2. **Authentication**: Review authentication flows for weaknesses
3. **Authorization**: Verify access control implementations
4. **Data Protection**: Ensure sensitive data is properly encrypted

## Guidelines

- Always provide severity ratings (Critical/High/Medium/Low)
- Include specific file paths and line numbers
- Suggest concrete fixes, not just identify problems
- Prioritize findings by potential impact
```

The file consists of two parts:

* **YAML Front Matter** (the section enclosed by `---`): Agent configuration properties corresponding to fields in the `Config.Agent` Schema.
* **Markdown body**: The Agent's System Prompt content.

### Loading Mechanism

```typescript
const AGENT_GLOB = new Bun.Glob("{agent,agents}/**/*.md")

async function loadAgent(dir: string) {
  const result: Record<string, Agent> = {}

  for await (const item of AGENT_GLOB.scan({
    absolute: true,
    followSymlinks: true,
    dot: true,
    cwd: dir,
  })) {
    const md = await ConfigMarkdown.parse(item).catch(async (err) => {
      // Publish error event on parse failure
      Bus.publish(Session.Event.Error, {
        error: new NamedError.Unknown({ message }).toObject()
      })
      return undefined
    })
    if (!md) continue

    // Extract Agent name from file path
    const patterns = [
      "/.opencode/agent/", "/.opencode/agents/",
      "/agent/", "/agents/"
    ]
    const file = rel(item, patterns) ?? path.basename(item)
    const agentName = trim(file)

    // Build and validate configuration
    const config = {
      name: agentName,
      ...md.data,              // YAML front matter
      prompt: md.content.trim(), // Markdown body
    }
    const parsed = Agent.safeParse(config)
    if (parsed.success) {
      result[config.name] = parsed.data
    }
  }
  return result
}
```

The loading process has several key details:

1. **Path searching**: The glob pattern `{agent,agents}/**/*.md` searches both singular and plural forms of the directory (`agent/` and `agents/`). This fault-tolerant design avoids issues users might face due to directory name spelling differences.
2. **Name extraction**: The Agent's name is extracted from the file path, not from the file content. For example, `.opencode/agents/security-auditor.md` yields the Agent name `security-auditor`. Nested directories are supported -- `.opencode/agents/review/code.md` yields the name `review/code`.
3. **Fault-tolerant parsing**: `ConfigMarkdown.parse()` uses `catch()` to handle parse failures, publishing error notifications through the event bus rather than throwing exceptions directly. This ensures that a syntax error in one Agent file does not prevent other Agents from loading.
4. **Zod validation**: `Agent.safeParse()` is used for safe validation. Invalid configurations are reported but do not crash the system.

### Search Paths

The search paths for Agent files include multiple levels:

```
~/.config/opencode/       # Global configuration directory
  +-- agents/*.md

<project>/.opencode/      # Project-level configuration directory
  +-- agents/*.md
```

Agents defined in the global directory are available across all projects, while Agents defined in the project-level directory are only available in the current project. If an Agent with the same name exists at both levels, according to the configuration merging strategy (`mergeConfigConcatArrays`), the project-level configuration overrides the global configuration.

## 6.5.3 Agent Injection via Plugins

Plugins are the third way to inject Agents. Through the `config` hook, Plugins can dynamically add Agent definitions to the configuration:

```typescript
// Plugin's config hook
hooks: {
  config: async () => ({
    agent: {
      "my-plugin-agent": {
        model: "anthropic/claude-sonnet-4-20250514",
        mode: "subagent",
        description: "Agent provided by my-plugin",
        prompt: "You are a specialized agent...",
        permission: { /* ... */ }
      }
    }
  })
}
```

Agent configurations injected by Plugins are merged together with configurations from other sources. Since Plugin configurations hold a higher position in the merge chain, Plugins can not only add new Agents but also modify or enhance existing built-in Agents.

### Agent Injection by oh-my-opencode

As the most complex Plugin in the OpenCode ecosystem, oh-my-opencode uses this mechanism to inject 11 Agents (Sisyphus, Oracle, Explore, Librarian, Prometheus, etc.), each with carefully designed Prompts and permission configurations. Detailed analysis of these Agents will be covered in Chapter 15.

## 6.5.4 Comparison of the Three Methods

| Feature             | `opencode.json`                                 | `.opencode/agents/*.md`    | Plugin                                            |
| ------------------- | ----------------------------------------------- | -------------------------- | ------------------------------------------------- |
| Use case            | Simple configuration, modifying built-in Agents | Complex custom Agents      | Cross-project reuse, dynamic configuration        |
| Prompt length       | Suitable for short Prompts                      | Suitable for long Prompts  | Suitable for programmatic generation              |
| Distribution method | Project configuration file                      | Project directory          | npm package                                       |
| Dynamism            | Static                                          | Static                     | Can be dynamically generated based on environment |
| Version control     | Managed with project configuration              | Managed with project files | Managed through npm versioning                    |

### Recommendations

* **Modifying built-in Agent behavior** (e.g., changing model, adjusting permissions) -> `opencode.json`
* **Creating project-specific specialist Agents** (e.g., security audit, code review) -> `.opencode/agents/`
* **Developing reusable Agent ecosystems** (e.g., multi-Agent orchestration systems) -> Plugin

## 6.5.5 Agent Lifecycle Summary

Combining the analysis from previous sections, the complete lifecycle of an Agent from definition to usage is as follows:

```
                    Configuration Phase
+--------------------------------------------+
|  1. Built-in Agent definitions (agent.ts)   |
|  2. Read agent config from opencode.json    |
|  3. Scan .opencode/agents/*.md files        |
|  4. Plugin injection via config hook        |
|  5. Merge configurations from all sources   |
|  6. Zod Schema validation                   |
|  7. Permission rule merging                 |
|  8. Truncate.GLOB global patching           |
+--------------------+-----------------------+
                     |
                    Runtime Phase
+--------------------v-----------------------+
|  1. Agent is bound when Session is created  |
|  2. User sends a message                    |
|  3. Determine System Prompt based on Agent  |
|  4. Plugin transforms System Prompt         |
|  5. Filter available tools by Agent         |
|     permissions                             |
|  6. Set temperature/topP based on Agent     |
|     parameters                              |
|  7. Call LLM.stream()                       |
|  8. Agent begins work (Agentic Loop)        |
|  9. Inject max-steps prompt when steps      |
|     limit is reached                        |
+--------------------------------------------+
```

This lifecycle clearly shows how an Agent transforms from a static configuration definition, through layers of processing and merging, into runtime guidance for LLM behavior.

***

## Chapter Summary

This chapter provided a thorough dissection of OpenCode's Agent system:

* **6.1** analyzed the Agent's data model (`Agent.Info`), understanding the meaning and design intent of each field.
* **6.2** dove deep into the configuration and permission design of 7 built-in Agents, with particular focus on the contrast between `build` (the all-purpose primary Agent) and `explore` (the read-only search specialist).
* **6.3** analyzed the Prompt designs of auxiliary Agents -- title generation, summary generation, context compaction, and codebase exploration each employ their own sophisticated Prompt Engineering techniques.
* **6.4** revealed the layered architecture of System Prompts -- the complete flow from selecting templates by LLM Provider, Plugin transformation, cache optimization, to parameter injection.
* **6.5** demonstrated three methods of custom Agent definition and their applicable scenarios.

The design philosophy of the Agent system can be summarized as: **Define an Agent's "personality" and "capabilities" through declarative configuration, ensure security boundaries through the dual mechanisms of permission systems and Prompts, and achieve maximum flexibility and extensibility through layered assembly and Plugin hooks.**

In the next chapter, we will enter the Provider layer -- understanding how OpenCode uniformly interfaces with 20+ LLM Providers to achieve "write once, run on any model" capability.
