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

# 6.1 Agent Data Model

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

***

In the previous chapter, we thoroughly dissected the Tool system -- the "hands" through which Agents interact with the outside world. In this chapter, we turn our focus to the Agent itself -- the core abstraction through which OpenCode gives an LLM its "personality" and "capability boundaries."

If Tools define "what an Agent can do," then the Agent defines "who the Agent is" -- which model it uses, what permissions it has, what behavioral guidelines it follows, and how many steps it can execute. Understanding the Agent data model is the foundation for understanding OpenCode's entire multi-Agent orchestration system.

## 6.1.1 The Zod Schema Definition of `Agent.Info`

The Agent data model is defined in `packages/opencode/src/agent/agent.ts`, declared using a Zod Schema:

```typescript
// agent/agent.ts
export namespace Agent {
  export const Info = z
    .object({
      name: z.string(),
      description: z.string().optional(),
      mode: z.enum(["subagent", "primary", "all"]),
      native: z.boolean().optional(),
      hidden: z.boolean().optional(),
      topP: z.number().optional(),
      temperature: z.number().optional(),
      color: z.string().optional(),
      permission: PermissionNext.Ruleset,
      model: z
        .object({
          modelID: z.string(),
          providerID: z.string(),
        })
        .optional(),
      variant: z.string().optional(),
      prompt: z.string().optional(),
      options: z.record(z.string(), z.any()),
      steps: z.number().int().positive().optional(),
    })
    .meta({ ref: "Agent" })
  export type Info = z.infer<typeof Info>
}
```

This code demonstrates OpenCode's consistent "Zod-first" design style -- define the data Schema first, then derive TypeScript types from it. Let us examine the meaning and design intent of each field one by one.

### Core Identity Fields

| Field         | Type      | Required | Description                                                                                    |
| ------------- | --------- | -------- | ---------------------------------------------------------------------------------------------- |
| `name`        | `string`  | Yes      | The Agent's unique identifier, e.g., `"build"`, `"explore"`                                    |
| `description` | `string`  | No       | A description of the Agent's purpose, used for UI display and as a reference for LLM selection |
| `native`      | `boolean` | No       | Whether this is an OpenCode built-in Agent (as opposed to a user-defined Agent)                |
| `hidden`      | `boolean` | No       | Whether to hide in the UI (auxiliary Agents like `title` and `summary` are typically `true`)   |

`name` serves as the index key for the Agent throughout the entire system. When users reference a specific Agent via `@agent-name` syntax or delegate subtasks through the Task tool, they do so by `name`.

### Execution Mode: `mode`

```typescript
mode: z.enum(["subagent", "primary", "all"])
```

The `mode` field determines the scenarios in which an Agent can be used:

* **`primary`**: A primary Agent that can only be used as the top-level Agent of a session. Users interact with it directly. Examples include the `build` Agent and the `plan` Agent.
* **`subagent`**: A sub-Agent that can only be invoked by other Agents through the Task tool. It cannot serve as the main Agent of a session. Examples include the `explore` Agent and the `general` Agent.
* **`all`**: Can operate in either mode. This is suitable for user-defined Agents -- they can serve as the primary Agent or be delegated to by other Agents.

This classification reflects an important architectural constraint: **not all Agents should be directly controllable by users**. Auxiliary Agents (such as `compaction`, `title`, `summary`) are marked as `hidden` and have strictly limited permissions -- they serve only internal system functions and are not exposed to users.

### Model Binding

```typescript
model: z
  .object({
    modelID: z.string(),
    providerID: z.string(),
  })
  .optional()
```

An Agent can specify the model it uses. If unspecified (`optional`), the system's default model is used. The `model` field consists of two parts: `providerID` (e.g., `"anthropic"`, `"openai"`) and `modelID` (e.g., `"claude-sonnet-4-20250514"`).

This design allows different Agents to use different models. For example, in a plugin like oh-my-opencode, the primary Agent (Sisyphus) might use a high-end model like Claude Opus for complex reasoning, while the exploration Agent (Explore) might use a cheaper model to reduce costs.

### Generation Parameters

```typescript
temperature: z.number().optional(),
topP: z.number().optional(),
variant: z.string().optional(),
```

> **Extended Explanation: Temperature and Top-P**
>
> These two parameters control the "randomness" of text generation by an LLM:
>
> * **Temperature**: Higher values (e.g., 1.0) produce more diverse and creative text; lower values (e.g., 0.1) produce more deterministic and conservative text. In Agent scenarios, code generation typically uses a lower temperature to ensure output determinism.
> * **Top-P** (nucleus sampling): Selects from the highest-probability tokens such that their cumulative probability does not exceed the P value. Top-P = 0.9 means sampling only from the candidate tokens whose probabilities sum to 90%.
>
> These two parameters are typically used as alternatives to each other. OpenCode's `title` Agent sets temperature to 0.5, striking a balance between determinism and diversity -- it neither always generates the exact same title nor produces overly absurd ones.

The `variant` field represents the concept of model variants. Some models offer different variants (e.g., thinking depth, response style, etc.), and `variant` allows an Agent to specify its preferred variant.

### Permission Ruleset

```typescript
permission: PermissionNext.Ruleset,
```

This is one of the most critical fields of an Agent. Each Agent carries a set of permission rules (`Ruleset`) that define which tools it can use and which file paths it can access. The detailed design of the permission system will be covered in Chapter 9; for now, it suffices to understand that **an Agent's permission rules directly determine its behavioral boundaries**.

### Dedicated Prompt

```typescript
prompt: z.string().optional(),
```

An Agent can have its own dedicated System Prompt. When the `prompt` field is set, that Prompt **replaces** the default Provider Prompt (e.g., `anthropic.txt`) rather than being appended to it. This design allows Agents to have entirely different "personalities."

For example, the `explore` Agent's Prompt is `prompt/explore.txt`, which defines it as a "file search specialist" -- a behavioral profile distinctly different from the default `build` Agent (an "all-purpose coding assistant").

### Step Limit

```typescript
steps: z.number().int().positive().optional(),
```

`steps` limits the maximum number of iteration steps an Agent can execute in a single interaction. In the Agentic Loop, each cycle of "tool call -> execution -> return result -> continue conversation" counts as one step. When the step limit is reached, the system injects a mandatory prompt (`max-steps.txt`) requiring the Agent to stop using tools and summarize its current progress in plain text.

This is a **safeguard mechanism** -- preventing Agents from entering infinite loops or consuming excessive resources. Unlike Doom Loop detection (repeated failure detection), `steps` is an absolute upper bound, regardless of whether the Agent is doing "meaningful" work.

### Provider-Specific Options

```typescript
options: z.record(z.string(), z.any()),
```

`options` is an open-ended key-value map for passing Provider-specific options. For example, some Providers may support special reasoning modes or safety settings that cannot be expressed through standard fields -- these are passed via `options`. During LLM invocation, these options are merged layer by layer:

```typescript
// Options merge chain in llm.ts
const options = pipe(
  base,                    // Provider-level defaults
  mergeDeep(input.model.options),   // Model-level options
  mergeDeep(input.agent.options),   // Agent-level options
  mergeDeep(variant),               // Variant-level options
)
```

### Visual Properties

```typescript
color: z.string().optional(),
```

The `color` field is used for visual differentiation in the TUI. When users switch between different Agents, the interface uses the corresponding color to identify the currently active Agent. It supports HEX color codes (e.g., `#FF5733`) or theme color names (e.g., `"primary"`, `"accent"`).

## 6.1.2 Agent Initialization via the `Instance.state()` Pattern

Agent instantiation uses the `Instance.state()` pattern introduced in Chapter 3:

```typescript
const state = Instance.state(async () => {
  const cfg = await Config.get()

  // ... Build Agent registry
  const result: Record<string, Info> = {
    build: { /* ... */ },
    plan: { /* ... */ },
    general: { /* ... */ },
    explore: { /* ... */ },
    compaction: { /* ... */ },
    title: { /* ... */ },
    summary: { /* ... */ },
  }

  // Merge user configuration
  for (const [key, value] of Object.entries(cfg.agent ?? {})) {
    // ...
  }

  return result
})
```

The key characteristics of this code are:

1. **Lazy initialization**: `Instance.state()` accepts an asynchronous factory function that is only executed on the first call to `state()`.
2. **Project isolation**: Each project instance has its own independent Agent registry, allowing different projects to have different Agent configurations.
3. **Caching semantics**: The initialization result is cached; subsequent calls return the cached value directly, avoiding redundant computation.

## 6.1.3 The Agent Public API

The Agent module exposes three core functions:

```typescript
// Get a specific Agent by name
export async function get(agent: string) {
  return state().then((x) => x[agent])
}

// List all Agents (with the default Agent sorted first)
export async function list() {
  const cfg = await Config.get()
  return pipe(
    await state(),
    values(),
    sortBy([(x) => (cfg.default_agent ? x.name === cfg.default_agent : x.name === "build"), "desc"]),
  )
}

// Get the default Agent name
export async function defaultAgent() {
  const cfg = await Config.get()
  const agents = await state()

  if (cfg.default_agent) {
    const agent = agents[cfg.default_agent]
    if (!agent) throw new Error(`default agent "${cfg.default_agent}" not found`)
    if (agent.mode === "subagent") throw new Error(`default agent "${cfg.default_agent}" is a subagent`)
    if (agent.hidden === true) throw new Error(`default agent "${cfg.default_agent}" is hidden`)
    return agent.name
  }

  const primaryVisible = Object.values(agents).find((a) => a.mode !== "subagent" && a.hidden !== true)
  if (!primaryVisible) throw new Error("no primary visible agent found")
  return primaryVisible.name
}
```

The implementation of `defaultAgent()` reveals several important constraints:

* The default Agent cannot be an Agent with `subagent` mode.
* The default Agent cannot be a `hidden` Agent.
* If the user has not specified a `default_agent`, the system selects the first non-subagent, non-hidden Agent (typically `build`).

These constraints ensure that when users launch OpenCode, there is always a suitable primary Agent available.

## 6.1.4 The Relationship Between Agents and Sessions

Understanding the Agent data model also requires understanding its relationship with Sessions. In OpenCode:

* **A Session can only be bound to one Agent** -- specified at Session creation time.
* **Child sessions inherit the parent session's Agent configuration** -- when the Task tool creates a child session, a different Agent can be specified.
* **The Agent determines the Session's behavioral characteristics** -- including which System Prompt to use, what permissions to have, and which model to use.

This "Agent-Session binding" design makes multi-Agent collaboration possible: the main Session uses the `build` Agent, while child Sessions spawned via the Task tool can use sub-Agents like `explore` and `general`, each with their own independent behavioral boundaries and capability scope.

***

This section established a comprehensive understanding of the Agent data model. In the next section, we will focus on OpenCode's most important built-in Agent -- `build` -- and analyze its permission configuration and behavioral design in depth.
