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

# 7.2 Provider Registration and Resolution

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

***

OpenCode's Provider system is not a simple "configure an API Key and you're done" affair — it needs to collect information from multiple sources (environment variables, configuration files, OAuth authentication, Plugin hooks), merge and validate them through multiple layers, and ultimately build a complete Provider registry. This section provides a detailed analysis of this process.

## 7.2.1 The `Provider.Info` Data Model

The metadata for each Provider is defined as follows:

```typescript
export const Info = z.object({
  id: z.string(),                              // Unique Provider identifier
  name: z.string(),                            // Display name
  source: z.enum(["env", "config", "custom", "api"]),  // Registration source
  env: z.string().array(),                     // List of available environment variable names
  key: z.string().optional(),                  // API Key
  options: z.record(z.string(), z.any()),       // Provider-specific options
  models: z.record(z.string(), Model),          // All models under this Provider
})
```

The `source` field records how the Provider was discovered:

| Source     | Description                                        |
| ---------- | -------------------------------------------------- |
| `"env"`    | Discovered via an API Key in environment variables |
| `"config"` | Defined in the `opencode.json` configuration file  |
| `"custom"` | Auto-discovered via Custom Loader or Plugin        |
| `"api"`    | API Key stored via the `opencode auth` command     |

## 7.2.2 The Complete Provider State Initialization Flow

Provider initialization uses the `Instance.state()` pattern. The complete flow is shown below:

```
   ┌──────────────────────────────────┐
   │  1. Load models.dev database     │
   │     (all known Providers/Models) │
   └──────────────┬───────────────────┘
                  │
   ┌──────────────▼───────────────────┐
   │  2. Merge user config providers  │
   │     (extend model lists, override│
   │      options)                    │
   └──────────────┬───────────────────┘
                  │
   ┌──────────────▼───────────────────┐
   │  3. Discover API Keys from       │
   │     environment variables        │
   │     (ANTHROPIC_API_KEY, etc.)    │
   └──────────────┬───────────────────┘
                  │
   ┌──────────────▼───────────────────┐
   │  4. Discover API Keys from       │
   │     Auth storage                 │
   │     (credentials from            │
   │      opencode auth)              │
   └──────────────┬───────────────────┘
                  │
   ┌──────────────▼───────────────────┐
   │  5. Plugin Auth loading          │
   │     (e.g., Copilot, Codex Auth)  │
   └──────────────┬───────────────────┘
                  │
   ┌──────────────▼───────────────────┐
   │  6. Custom Loader execution      │
   │     (Provider-specific init      │
   │      logic)                      │
   └──────────────┬───────────────────┘
                  │
   ┌──────────────▼───────────────────┐
   │  7. Final merge of config        │
   │     options                      │
   └──────────────┬───────────────────┘
                  │
   ┌──────────────▼───────────────────┐
   │  8. Filtering: disabled list,    │
   │     whitelist, deprecated models,│
   │     empty Providers              │
   └──────────────────────────────────┘
```

### Step 1: Load the models.dev Database

```typescript
const modelsDev = await ModelsDev.get()
const database = mapValues(modelsDev, fromModelsDevProvider)
```

OpenCode uses [models.dev](https://models.dev) as its data source for model metadata. This is a centralized model information database containing capability descriptions, pricing information, context window sizes, and more for all mainstream LLMs.

The loading priority of `ModelsDev.get()` is:

1. Local cache file (`~/.cache/opencode/models.json`)
2. Build-time embedded snapshot (`models-snapshot`)
3. Online fetch from `https://models.dev/api.json`

### Step 3: Environment Variable Discovery

```typescript
const env = Env.all()
for (const [providerID, provider] of Object.entries(database)) {
  if (disabled.has(providerID)) continue
  const apiKey = provider.env.map((item) => env[item]).find(Boolean)
  if (!apiKey) continue
  mergeProvider(providerID, { source: "env", key: apiKey })
}
```

Each Provider has a set of associated environment variable names (e.g., Anthropic corresponds to `ANTHROPIC_API_KEY`). The system iterates over all known Providers and checks whether the corresponding environment variables exist. If an API Key is found, that Provider is automatically registered.

This **zero-configuration** discovery mechanism is quite elegant — users only need to set an environment variable to automatically enable the corresponding Provider, without having to explicitly declare it in a configuration file.

### Step 6: Custom Loader

Certain Providers require special initialization logic, which is implemented through `CUSTOM_LOADERS`:

```typescript
const CUSTOM_LOADERS: Record<string, CustomLoader> = {
  async anthropic() {
    return {
      autoload: false,
      options: {
        headers: {
          "anthropic-beta": "claude-code-20250219,interleaved-thinking-...",
        },
      },
    }
  },

  async "amazon-bedrock"() {
    // Complex AWS credential chain: Profile → Access Key → Bearer Token → Web Identity
    const { fromNodeProviderChain } = await import(
      await BunProc.install("@aws-sdk/credential-providers")
    )
    return {
      autoload: true,
      options: providerOptions,
      async getModel(sdk, modelID) {
        // Cross-region inference prefix handling (us., eu., global., etc.)
      },
    }
  },

  async gitlab(input) {
    // GitLab OAuth + AI Gateway configuration
    return {
      autoload: !!apiKey,
      options: { instanceUrl, apiKey, aiGatewayHeaders, featureFlags },
      async getModel(sdk, modelID) {
        return sdk.agenticChat(modelID, { /* ... */ })
      },
    }
  },
  // ...
}
```

The return value of a Custom Loader contains three key fields:

* **`autoload`**: Whether to automatically load this Provider (even without an explicit API Key). For example, AWS Bedrock auto-loads if IAM configuration is detected.
* **`options`**: Provider-specific initialization options. For example, Anthropic requires special beta headers.
* **`getModel`**: A custom model retrieval function. Different Providers obtain `LanguageModel` instances in different ways.

### Step 8: Filtering and Cleanup

```typescript
for (const [providerID, provider] of Object.entries(providers)) {
  // Check if allowed
  if (!isProviderAllowed(providerID)) { delete providers[providerID]; continue }

  for (const [modelID, model] of Object.entries(provider.models)) {
    // Remove deprecated models
    if (model.status === "deprecated") delete provider.models[modelID]
    // Remove experimental models (unless the experimental flag is enabled)
    if (model.status === "alpha" && !Flag.OPENCODE_ENABLE_EXPERIMENTAL_MODELS)
      delete provider.models[modelID]
    // Apply blacklist/whitelist
    if (configProvider?.blacklist?.includes(modelID) ||
        (configProvider?.whitelist && !configProvider.whitelist.includes(modelID)))
      delete provider.models[modelID]
  }

  // Remove Providers that have no models
  if (Object.keys(provider.models).length === 0) {
    delete providers[providerID]
  }
}
```

## 7.2.3 `Provider.getLanguage()`: From Configuration to a LanguageModel Instance

When an Agent needs to call an LLM, the system obtains an available `LanguageModelV2` instance through the following chain:

```typescript
export async function getLanguage(model: Model): Promise<LanguageModelV2> {
  const s = await state()
  const key = `${model.providerID}/${model.id}`

  // Cache check
  if (s.models.has(key)) return s.models.get(key)!

  const provider = s.providers[model.providerID]
  const sdk = await getSDK(model)      // Get the Provider SDK instance

  // Use the Custom Loader's getModel or the default method
  const language = s.modelLoaders[model.providerID]
    ? await s.modelLoaders[model.providerID](sdk, model.api.id, provider.options)
    : sdk.languageModel(model.api.id)

  s.models.set(key, language)     // Cache the result
  return language
}
```

The implementation of `getSDK()` features an elegant caching mechanism — it uses `xxHash32` to hash the Provider configuration, ensuring that SDK instances with identical configurations are reused:

```typescript
const key = Bun.hash.xxHash32(JSON.stringify({
  providerID: model.providerID,
  npm: model.api.npm,
  options
}))
const existing = s.sdk.get(key)
if (existing) return existing
```

## 7.2.4 Custom Provider Registration

Users can register custom Providers in `opencode.json`:

```json
{
  "provider": {
    "my-llm": {
      "name": "My Custom LLM",
      "npm": "@ai-sdk/openai-compatible",
      "api": "https://my-llm-api.example.com/v1",
      "env": ["MY_LLM_API_KEY"],
      "models": {
        "my-model-v1": {
          "name": "My Model v1",
          "limit": { "context": 128000, "output": 4096 },
          "cost": { "input": 1.0, "output": 3.0 }
        }
      }
    }
  }
}
```

Through the "universal adapter" `@ai-sdk/openai-compatible`, any LLM service compatible with the OpenAI API format (such as Ollama, LM Studio, vLLM, etc.) can be seamlessly integrated into OpenCode.

## 7.2.5 Model Search and Default Model Selection

OpenCode provides fuzzy search and intelligent default selection:

```typescript
// Fuzzy search: when the user-entered model name is incorrect, provide suggestions
export async function getModel(providerID: string, modelID: string) {
  const provider = s.providers[providerID]
  if (!provider) {
    const matches = fuzzysort.go(providerID, availableProviders, {
      limit: 3, threshold: -10000
    })
    throw new ModelNotFoundError({ providerID, modelID,
      suggestions: matches.map((m) => m.target) })
  }
  // ...similarly perform fuzzy matching on modelID
}

// Default model selection
export async function defaultModel() {
  const cfg = await Config.get()
  if (cfg.model) return parseModel(cfg.model)

  // Automatically select the highest-priority model from the first available Provider
  const provider = await list()
    .then((val) => Object.values(val))
    .then((x) => x.find((p) => !cfg.provider ||
      Object.keys(cfg.provider).includes(p.id)))

  const [model] = sort(Object.values(provider.models))
  return { providerID: provider.id, modelID: model.id }
}
```

Model sorting priority:

```typescript
const priority = ["gpt-5", "claude-sonnet-4", "big-pickle", "gemini-3-pro"]
```

If the user has not specified a default model, the system automatically selects the best available model according to the priority list above.

***

The next section will analyze the model metadata system — how OpenCode manages capability descriptions, pricing information, and context window limits for each model.
