← Blog
A coral ceramic sphere beside branching cream channels leading to three sage-green blocks.
Published on
2026-11-16

OpenCode custom provider: connect Hivenet Router

An OpenCode custom provider defines how the coding agent connects to an API endpoint outside its built-in provider catalog. To connect OpenCode to Hivenet Router, define an OpenAI-compatible custom provider, point it at your Router URL ending in /v1, supply a Router client key, and select the model your deployment serves. Then verify a complete tool-use cycle: reading a file, proposing an edit, applying an approved change, and checking the result.

This guide is for developers configuring OpenCode against an existing self-hosted Router deployment. It covers custom provider configuration, API-key handling, model IDs, context limits, and a small coding task so you can identify connection or tool failures before opening a real project. OpenCode runs the coding agent and its tools; Router handles inference requests; the model server generates responses. Router does not execute your shell commands or edit your repository.

Configuration review: checked against the current OpenCode V2 documentation and JSON schema on November 16, 2026. The example passes schema validation. It has not been tested against a live OpenCode–Router deployment, so the workflow checks below are acceptance criteria to run in your environment.

Choose a custom provider or a direct connection

OpenCode supports built-in providers and local models as well as custom endpoints. A custom provider is useful when your gateway or model API is absent from the catalog. A developer using one model server can start with OpenCode's direct connection options. Add Router when the deployment needs a shared inference endpoint with centrally managed client credentials, model access, routing, and usage controls. Keep the decision tied to an operating requirement; another service also adds configuration and maintenance.

The LLM routing guide explains the routing layer. For a shared browser chat interface, use the Open WebUI guide. This article focuses on a coding agent that can act on a repository, where a successful chat response is only the first check.

Check your OpenCode version before copying configuration

The Router OpenCode integration reference currently shows the older configuration shape. OpenCode V2 has a native format with different names. That difference does not establish that the older example is broken: the OpenCode migration guide says supported V1 configuration continues to work in V2 and conversion is optional.

SettingOlder exampleNative V2 example below
Provider definitionprovider, npm, optionsproviders, package, settings
Tool permissionspermission with bash rulespermissions array with shell rules
Small title modelsmall_modelagents.title.model

Use one format consistently within each provider, model, or agent entry. Do not replace an entire existing configuration with this example: preserve unrelated settings and review configuration precedence. Native V2 fields are not a configuration for a V1 client.

Choose the config file OpenCode loads

Use opencode.json for JSON or opencode.jsonc for JSON with comments and trailing commas. Put the project config file in the repository root or its .opencode directory. Global configuration at ~/.config/opencode/opencode.json(c) supplies settings across projects; project settings override conflicting global settings. System and managed configuration can take precedence over both, and policies have their own ordering. Check the configuration locations and precedence before moving a provider block between files.

Keep the $schema entry so an editor with JSON Schema support can validate the config. Validation catches unsupported fields and invalid shapes; it does not test credentials, connectivity, or model behavior.

Prepare the OpenAI-compatible API, API key, and model

Before editing OpenCode, obtain the Router base URL, a client API key approved for this workload, and the exact served model identifier. The Router deployment needs a healthy, eligible agent and a working model backend. Use HTTPS for a remote connection and verify the certificate.

OpenCode needs more than text generation for the exercise below. Check that the deployed model and serving configuration support structured tool calls through Chat Completions. A model's name, an OpenAI-compatible label, or a capability flag in a client file does not prove that support. The OpenAI-compatible API buyer guide explains why compatibility needs to be checked by feature.

Give the credential to the process that runs the OpenCode server. An environment variable set in a new terminal does not update an already running background service. Follow the OpenCode configuration documentation for your installation and service environment, then reconnect or restart the relevant process as required. Keep the real key out of the project file, source control, screenshots, and support logs.

Configure an OpenCode custom provider for Router

For a V2 project, add the provider block under the providers object in opencode.json. Adapt the example below. Replace https://router.example.com/v1 and YOUR_SERVED_MODEL_ID before use. Supply the real credential through HIVENET_ROUTER_API_KEY in the server environment. The 32768 context and 4096 output limits are illustrative; replace them with limits supported by your deployed model server.

{
  "$schema": "https://opencode.ai/config.json",
  "model": "hivenet-router/coder",
  "providers": {
    "hivenet-router": {
      "name": "Hivenet Router",
      "env": [
        "HIVENET_ROUTER_API_KEY"
      ],
      "package": "@opencode/ai/providers/openai-compatible",
      "settings": {
        "baseURL": "https://router.example.com/v1"
      },
      "models": {
        "coder": {
          "modelID": "YOUR_SERVED_MODEL_ID",
          "name": "Team coding model",
          "capabilities": {
            "tools": true,
            "input": [
              "text"
            ],
            "output": [
              "text"
            ]
          },
          "limit": {
            "context": 32768,
            "output": 4096
          }
        }
      }
    }
  },
  "agents": {
    "title": {
      "model": "hivenet-router/coder"
    }
  },
  "permissions": [
    {
      "action": "read",
      "resource": "*",
      "effect": "ask"
    },
    {
      "action": "edit",
      "resource": "*",
      "effect": "ask"
    },
    {
      "action": "shell",
      "resource": "*",
      "effect": "ask"
    },
    {
      "action": "external_directory",
      "resource": "*",
      "effect": "ask"
    }
  ],
  "policies": [
    {
      "action": "provider.use",
      "resource": "*",
      "effect": "deny"
    },
    {
      "action": "provider.use",
      "resource": "hivenet-router",
      "effect": "allow"
    }
  ]
}

The runtime package and credential fields follow the current OpenCode custom-provider documentation. The OpenAI-compatible runtime uses the Chat Completions interface needed here. Router exposes /v1/chat/completions, not /v1/responses; changing only a URL does not make a Responses-based integration compatible.

Read the provider settings and model IDs

The provider key hivenet-router is the provider ID used in model references, not a secret API key. The name field is a display name. In this example, env identifies the credential variable, package selects the runtime, settings.baseURL gives the base URL, and models lists the models exposed to OpenCode. Keep these roles distinct when diagnosing a missing entry.

hivenet-router/coder is OpenCode's provider/model selection. coder is a local name, while modelID must contain the exact model ID expected by the upstream API. Select the intended entry through /models; an existing session selection can override the default in the file. These behaviors are documented in OpenCode's model configuration.

This local mapping is separate from a Router routing alias. If you use a Router alias, review its destination and access behavior in the existing rules and model aliases guide. A convenient client name does not create a Router rule.

Set context limits and tool capabilities explicitly

The capability declaration describes the model OpenCode should expect. Setting tools: true does not teach a backend to call tools. The text-only input and output declarations do not enable image input. Match these fields to verified capabilities and leave room in the context budget for instructions, repository content, tool results, and generated output.

For an unknown model, OpenCode's documented defaults assume a 200,000-token context window, 32,000-token output limit, and certain media and tool capabilities. These are fallback assumptions, not measurements of your backend. Set accurate limits rather than relying on them. Review model or variant overrides when the effective settings differ from the provider definition.

Review tool permissions and provider restrictions

The example asks before file reads, edits, shell actions, and access outside the project directory. OpenCode combines permission rules, with the last matching rule taking effect; agent-specific settings and saved approvals can change what prompts you see. Inspect the effective behavior before trusting the example as your policy. The permissions documentation explains the matching rules.

Tools run on the machine hosting the OpenCode server. Approving a shell command gives that command access according to the host user's privileges. Permission prompts are not an operating-system sandbox. Start with a disposable repository and an account that has only the access needed for the exercise.

The two provider.use statements deny other provider IDs and allow hivenet-router. Review higher-priority policies and check the server log for rejected policy statements, as described in OpenCode policies. This provider restriction does not block every outbound connection from shell tools, plugins, MCP servers, or other integrations.

It also does not control destinations behind Router. If repository content must stay within an approved boundary, review Router's fallback policy and the host's network access. Use the self-hosted endpoint security guide for those controls rather than treating a local provider name as proof of privacy.

Start OpenCode and test tool calls in a small project

Start OpenCode in a disposable repository containing a short README with one deliberate typo. Record the OpenCode version, Router and backend versions, selected model, and configuration used. Keep credentials and sensitive code out of the test evidence.

  1. Confirm the selected model. Open /models and select hivenet-router/coder. Ask a harmless question and verify that the intended Router deployment receives the inference request.
  2. Read one file. Ask OpenCode to read the README and describe the typo without changing anything. Inspect the proposed tool action and approve only the expected file access.
  3. Make one bounded edit. Ask it to correct that typo. Review the proposed change and permission request, then inspect the resulting diff yourself. Confirm that no unrelated file changed.
  4. Check one known command. Ask for a simple inspection such as git diff --check. Review the exact shell command before approval and compare the reported result with the command output.
  5. Exercise a refusal. Request another harmless edit and reject its permission prompt. Confirm that the rejected action does not modify the file. Do not use a destructive command to test denial.
  6. Review the request path. Check model, destination, failures, and request counts without exporting prompt content. Investigate any unexpected provider or tool activity before expanding the test.

A passing exercise should show a structured tool request, the intended permission decision, the actual tool result, and a model response that uses that result. Text saying “I changed the file” is insufficient evidence. Keep this first task small enough that a person can verify every change.

Troubleshoot the failed stage

SymptomFirst check
Configured model is missingCheck the loaded project configuration, server credential environment, provider policy, and local model name.
Authentication failsA missing or incorrect API key can cause authentication to fail. Check which layer rejected the request and whether the OpenCode server process has the intended credential. Do not print the key.
Request targets /v1/responsesInspect the selected runtime and model overrides. Use the documented Chat Completions-compatible path for Router.
Chat works but file actions failSeparate tool-call parsing from permission denial and host filesystem access. Verify the backend's tool support and the selected agent's rules.
Output arrives in a burstCompare the client, proxy, Router, and backend path for buffering. Do not infer a model-speed problem from the display alone.
A longer task exceeds contextCompare configured limits with the actual backend and inspect how repository content and tool results accumulate.

For request correlation, backend health, and error evidence, continue with the Router monitoring and troubleshooting guide. Preserve the smallest harmless reproduction that reaches the failed stage.

Check headers, timeouts, and the server environment

Provider configuration can include additional headers and request timeouts. Use only options the endpoint accepts. OpenCode documents up to three retries after a timed-out request; account for client retries when diagnosing repeated Router traffic. Review the provider timeout settings before increasing a timeout or adding another retry layer.

If the key changed in your shell but the running service still uses an older environment, restart OpenCode's server with the intended environment and reconnect the client. Restarting a terminal client alone may leave the shared server unchanged. Verify the selected provider and model again after reconnecting.

Common custom provider questions

Can I use local models from LM Studio or vLLM?

Yes. OpenCode documents direct connections for LM Studio, vLLM, and Ollama. Use their built-in integrations when connecting directly, or the custom provider in this guide when the application-facing endpoint is Router. Choose according to the API you actually reach, and verify tool support for the deployed model. The local provider documentation covers direct setup.

Do I need /connect as well as this environment variable?

OpenCode uses /connect to connect provider accounts. This example supplies the Router credential through the server environment using env. Keep one deliberate credential path for the first test, and confirm which connection is active before adding another.

Why do older examples use @ai-sdk/openai-compatible?

The older Router example uses the AI SDK package through the V1 npm field. When preserving that adapter in native V2 syntax, OpenCode's migration guide maps it to package: "aisdk:@ai-sdk/openai-compatible". This guide instead uses the native OpenCode runtime shown in current provider docs. Keep the chosen runtime and its settings together; do not combine fields from different examples.

Set a usage budget before sharing the setup

A coding task can make several model requests as it reads, edits, checks, and retries. OpenCode also has maintenance agents, including title, summary, and compaction behavior. The example explicitly assigns the title agent to the same provider/model; it does not eliminate background work. Review agent configuration and observe the requests produced by your actual workflow.

Use the Router rate limiting and quotas guide to set the intended usage controls. A developer's local OpenCode profile does not automatically create a separate Router quota owner. Check credential ownership before promising individual budgets.

Expand to a real repository only after the selected model, tool cycle, rejected action, and destination checks behave as intended. Keep the working configuration and version record with the project, excluding secrets. Repeat the relevant checks when changing the client runtime, model, tool permissions, or Router policy.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.