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

# 3.4 Layered Configuration System Design

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

***

The configuration system is one of the most carefully designed pieces of infrastructure in OpenCode. It needs to simultaneously satisfy individual users' flexible customization and enterprise environments' centralized control -- two seemingly contradictory requirements that are elegantly resolved through a layered design.

## 3.4.1 Configuration Priority Chain

OpenCode defines 7 layers of configuration, in order from lowest to highest priority:

```
Priority (low -> high)

1. Remote .well-known/opencode    <- Organization default config (discovered via domain)
   |
2. Global ~/.config/opencode/opencode.json   <- User global config
   |
3. Custom config (OPENCODE_CONFIG env)        <- Config file specified by environment variable
   |
4. Project opencode.json                      <- Config in the project root directory
   |
5. .opencode/ directory                       <- Config under the .opencode/ directory
   |  +-- .opencode/agents/     Agent definitions
   |  +-- .opencode/commands/   Custom commands
   |  +-- .opencode/plugins/    Plugins
   |  +-- .opencode/opencode.json Config file
   |
6. Inline config (OPENCODE_CONFIG_CONTENT)    <- Config content injected directly via env var
   |
7. Managed config (/Library/Application Support/opencode)  <- Enterprise managed (highest priority)
```

The loading logic in the source code (`config/config.ts`):

```typescript
export const state = Instance.state(async () => {
  // Config loading order (from lowest to highest priority)
  let result: Info = {}

  // 1. Remote .well-known/opencode
  for (const [key, value] of Object.entries(auth)) {
    if (value.type === "wellknown") { /* merge remote config */ }
  }

  // 2. Global config
  // 3. Custom config (OPENCODE_CONFIG)
  // 4. Project config
  // 5. .opencode directories
  // 6. Inline config (OPENCODE_CONFIG_CONTENT)
  // 7. Managed config (enterprise)

  return result
})
```

**Design intent**:

* **Layer 1** (Remote): A company can deploy a `.well-known/opencode` file under its domain to provide default configuration for the entire organization
* **Layers 2-3** (Global + Custom): Personal preference settings
* **Layers 4-5** (Project): Project-level customization that can be version-controlled with the code
* **Layer 6** (Inline): Injecting configuration via environment variables in CI/CD scenarios
* **Layer 7** (Managed): Configuration forcibly overridden by enterprise IT administrators (e.g., disabling certain features, restricting available models)

## 3.4.2 JSONC Parsing and Configuration Merge Strategy

OpenCode supports the **JSONC** (JSON with Comments) format for configuration files, meaning users can add comments in JSON:

```jsonc
{
  // Use Claude as the default model
  "model": "claude-sonnet-4-20250514",

  /* MCP server configuration */
  "mcpServers": {
    "github": {
      "command": "mcp-server-github"
    }
  }
}
```

> **Extended Explanation: JSONC**
>
> JSON (JavaScript Object Notation) is a lightweight data interchange format, but standard JSON does not support comments. JSONC is a superset of JSON that allows `//` single-line comments and `/* */` multi-line comments. All of VSCode's configuration files (settings.json, etc.) use the JSONC format. OpenCode uses the `jsonc-parser` library to parse JSONC.

**Configuration merge strategy**:

Multiple layers of configuration ultimately need to be merged into a single configuration object. OpenCode uses deep merge, but with special handling for array fields:

```typescript
function mergeConfigConcatArrays(target: Info, source: Info): Info {
  const merged = mergeDeep(target, source)

  // Array fields use concatenation rather than replacement
  if (target.plugin && source.plugin) {
    merged.plugin = Array.from(new Set([...target.plugin, ...source.plugin]))
  }
  if (target.instructions && source.instructions) {
    merged.instructions = Array.from(new Set([
      ...target.instructions,
      ...source.instructions
    ]))
  }
  return merged
}
```

This design choice is worth noting:

* **Object fields** (such as `mcpServers`): Deep merge, with higher priority overriding lower priority
* **Array fields** (such as `plugin`, `instructions`): Concatenate and deduplicate, rather than overwrite

Why concatenate arrays? Because the global configuration may define some base plugins, and the project configuration may add additional plugins. If the project configuration directly overwrote the global configuration's `plugin` array, the global plugins would be lost. The concatenation strategy avoids this problem.

## 3.4.3 Zod Schema-Driven Configuration Validation

OpenCode uses the **Zod** library to define configuration schemas, ensuring type safety:

> **Extended Explanation: Zod**
>
> Zod is a TypeScript-first data validation library. It allows you to define data structures using TypeScript code, then validate data against those structures at runtime.
>
> ```typescript
> const UserSchema = z.object({
>   name: z.string(),
>   age: z.number().min(0),
>   email: z.string().email()
> })
>
> // Runtime validation
> UserSchema.parse({ name: "Alice", age: 25, email: "a@b.com" }) // OK
> UserSchema.parse({ name: "Alice", age: -1 })                   // Throws error
> ```
>
> Zod is used extensively throughout OpenCode -- nearly all data models are defined with Zod. This brings two benefits:
>
> 1. **Runtime type safety**: All external inputs (user configuration, API requests, LLM responses) are validated through Zod
> 2. **Type inference**: TypeScript types are automatically derived via `z.infer<typeof Schema>`, avoiding redundant definitions

A partial schema definition for the configuration:

```typescript
// Simplified version showing the core structure
const ConfigSchema = z.object({
  model: z.string().optional(),
  provider: z.record(z.string(), ProviderConfig).optional(),
  mcpServers: z.record(z.string(), McpServerConfig).optional(),
  permission: PermissionConfig.optional(),
  plugin: z.array(z.string()).optional(),
  instructions: z.array(z.string()).optional(),
  agent: z.record(z.string(), AgentConfig).optional(),
  snapshot: z.boolean().optional(),
  compaction: CompactionConfig.optional(),
  experimental: ExperimentalConfig.optional(),
})
```

## 3.4.4 Markdown Format Configuration Support

In addition to the JSON format, OpenCode also supports Markdown format configuration (`config/markdown.ts`). This is primarily used for `AGENTS.md` and `CLAUDE.md` instruction files -- which are essentially system prompts (System Prompt) stored in Markdown format.

This design allows instruction files to:

* Be written using Markdown syntax for better readability
* Be version-controlled alongside the project
* Include code blocks, lists, and other rich text formatting

## 3.4.5 The `Flag` Module: Environment Variables and Feature Toggles

The `flag/flag.ts` module manages all feature toggles controlled via environment variables:

```typescript
export namespace Flag {
  export const OPENCODE_CONFIG = process.env.OPENCODE_CONFIG
  export const OPENCODE_CONFIG_DIR = process.env.OPENCODE_CONFIG_DIR
  export const OPENCODE_CONFIG_CONTENT = process.env.OPENCODE_CONFIG_CONTENT
  export const OPENCODE_DISABLE_PROJECT_CONFIG = /* ... */
  export const OPENCODE_DISABLE_CLAUDE_CODE_PROMPT = /* ... */
  export const OPENCODE_DISABLE_DEFAULT_PLUGINS = /* ... */
  export const OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX = /* ... */
  // ... more toggles
}
```

The `OPENCODE_` environment variable prefix ensures namespace uniqueness. The main uses of these toggles are:

1. **Test isolation**: e.g., `OPENCODE_TEST_HOME`, `OPENCODE_TEST_MANAGED_CONFIG_DIR`
2. **Feature disabling**: e.g., `OPENCODE_DISABLE_PROJECT_CONFIG` (for enterprise security scenarios)
3. **Experimental features**: e.g., `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX`

**Design principle**: Flags are a lower-level control mechanism than configuration files, used for options that need to be determined before the configuration system is initialized. For example, `OPENCODE_CONFIG` specifies the configuration file path -- this information is needed before configuration loading begins.

***

With this, the three chapters of Part One (Fundamentals) have fully covered OpenCode's background, project structure, and overall architecture. Starting from the next chapter, we will enter Part Two (Core Architecture), providing source-code-level in-depth analysis of the five core modules: Session, Tool, Agent, Provider, and MCP.
