Skip to main content

OpenCode

OpenCode is a coding agent for the terminal that can talk to many model providers. Routing it through Spanway gives it one provider, called spanway, that serves every model your key may use, from any vendor the gateway knows. Your requests then count against your team budget, pass the company guardrails and show up on the gateway's Logs page, and nobody has to hand out vendor keys. There are two ways to connect: spanwayctl opencode sets everything up for one run, or a provider entry in opencode.json connects it permanently.

A real-world scenario​

A developer likes OpenCode and wants to try three models from different vendors on the same refactoring task. Their admin has already given them a key that may call claude-sonnet-5-5, gpt-6.1-sol and gemini-3.8-flash. The developer adds one spanway provider to ~/.config/opencode/opencode.json, opens /models in OpenCode and sees all three. They switch between them during the session, and the admin sees the spend of each model under the developer's key alias on Usage.

Prerequisites​

  • OpenCode installed, see its own install guide at https://opencode.ai/docs. OpenCode V1 and V2 use different file formats for providers, and both are shown below. Check which one you have with opencode --version.
  • The gateway's address, for example https://gateway.example.com, reachable from your machine.
  • A virtual key for OpenCode, made as in the next section.
  • For the one-run option, spanwayctl on your machine, see the CLI reference. The gateway image does not contain OpenCode, so spanwayctl opencode has to run where OpenCode is installed.

Make a key for OpenCode​

  1. In the Admin UI open Virtual Keys (/ui/api-keys) and click + Create New Key.
  2. Set Key Name to who and which tool, for example jane-opencode. Leave Key Type on AI APIs.
  3. In Models, pick every model the developer may choose in /models. If the developer sets small_model in OpenCode's config, which sends short side tasks such as session titles to a smaller model, add that model too, or those side calls fail with 403 while the main chat works.
  4. Open Optional Settings. Set Max Budget (USD), for example 150, with Reset Budget on monthly, and a Requests per minute Limit (RPM) such as 60. Leave Tags empty unless the gateway has an Enterprise license, because key tags need one and without it the key is not created (Only premium users can add tags to keys). The key name already keeps this tool's spend apart in Usage.
  5. Click Create Key and copy the key. It is shown once.
curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "jane-opencode", "key_type": "llm_api", "models": ["claude-sonnet-5-5", "gpt-6.1-sol", "gemini-3.8-flash"], "max_budget": 150, "budget_duration": "30d", "rpm_limit": 60}'

Make a key for a tool explains every field.

Steps​

Option 1, one run with spanwayctl​

  1. Run OpenCode through spanwayctl. Everything after opencode is passed on to OpenCode.

    spanwayctl --base-url https://gateway.example.com --api-key sk-... opencode
  2. Open /models in OpenCode and pick a model under Spanway.

What spanwayctl opencode does, in order:

  1. Checks the key with GET /v1/models. A rejected key stops here with a clear message, see errors. --skip-verify skips this check.
  2. Sets OPENAI_BASE_URL to https://gateway.example.com/v1 and OPENAI_API_KEY to your key, for this run only.
  3. Reads the models your key may use from /v1/models, keeps the chat models, and passes OpenCode a provider called spanway (shown as Spanway) with one entry per model through the OPENCODE_CONFIG_CONTENT environment variable. A model whose gateway entry has max_input_tokens and max_output_tokens gets those as its context and output limits. The key is referenced as {env:OPENAI_API_KEY}, so it is never written into the config text. OpenCode merges this over your own config files and leaves your other providers alone.
  4. Starts OpenCode.

OPENCODE_CONFIG_CONTENT is skipped when it is already set in your environment, and the model list is skipped with --skip-verify or when /v1/models cannot be read. OpenCode then still starts with the OPENAI_* variables, and a line on the terminal says why the list was skipped. The provider format spanwayctl opencode writes is the OpenCode V1 format. On OpenCode V2, use option 2.

Option 2, a permanent provider in opencode.json​

  1. Put the key in your shell profile (~/.zshrc or ~/.bashrc) and open a new terminal.

    export SPANWAY_API_KEY="sk-..."
  2. List the models the key may use. You copy their ids into the file in the next step.

    curl https://gateway.example.com/v1/models -H "Authorization: Bearer $SPANWAY_API_KEY"
  3. Open ~/.config/opencode/opencode.json for every project, or opencode.json in a project's root for one project. Add the provider. The base URL includes /v1, because OpenCode adds /chat/completions to it.

    For OpenCode V2:

    {
    "$schema": "https://opencode.ai/config.json",
    "providers": {
    "spanway": {
    "name": "Spanway",
    "env": ["SPANWAY_API_KEY"],
    "package": "@opencode/ai/providers/openai-compatible",
    "settings": { "baseURL": "https://gateway.example.com/v1" },
    "models": {
    "claude-sonnet-5-5": { "name": "Claude Sonnet 5.5", "limit": { "context": 1000000, "output": 128000 } },
    "gpt-6.1-sol": { "name": "GPT 6.1 Sol", "limit": { "context": 922000, "output": 128000 } }
    }
    }
    },
    "model": "spanway/claude-sonnet-5-5"
    }

    For OpenCode V1, the same provider uses provider, npm and options:

    {
    "$schema": "https://opencode.ai/config.json",
    "provider": {
    "spanway": {
    "npm": "@ai-sdk/openai-compatible",
    "name": "Spanway",
    "options": { "baseURL": "https://gateway.example.com/v1", "apiKey": "{env:SPANWAY_API_KEY}" },
    "models": {
    "claude-sonnet-5-5": { "name": "claude-sonnet-5-5", "limit": { "context": 1000000, "output": 128000 } },
    "gpt-6.1-sol": { "name": "gpt-6.1-sol", "limit": { "context": 922000, "output": 128000 } }
    }
    }
    },
    "model": "spanway/claude-sonnet-5-5"
    }
  4. Start OpenCode with opencode, open /models and pick a model under Spanway. For a one-off check without the interface, run opencode run "Say hello".

SettingWhat to putWhy
Provider id (spanway)Any id that is not a built-in providerModels are referred to as spanway/<model id>, for example in model and small_model.
env (V2) or apiKey (V1)["SPANWAY_API_KEY"], or "{env:SPANWAY_API_KEY}"Reads the key from your environment, so the file holds no secret. OpenCode sends it as Authorization: Bearer <key>.
baseURLhttps://gateway.example.com/v1, with /v1OpenCode adds /chat/completions.
Model keys under modelsThe exact public names from GET /v1/modelsThe key is the name sent to the gateway. In V2, modelID sends a different name than the key, which lets you give a model a short alias.
limit.context, limit.outputThe model's input and output token limitsOpenCode uses them to decide when to compact a long session. Copy them from GET /model_group/info (max_input_tokens, max_output_tokens).

OpenCode does not read the model list from the gateway on its own, so when the admin adds a model to your key, add it to models as well, or use spanwayctl opencode, which reads the list at every start.

Expected result​

The Spanway provider shows your gateway models in /models, and OpenCode answers through the one you picked.

On the gateway's Logs page (/ui/logs), open Filters, pick your Key Alias, for example jane-opencode, and click Apply Filters. Each OpenCode call is one row on /v1/chat/completions with the model, tokens and cost. Side calls on a small_model, such as titles, appear as their own short rows.

OpenCode does not show response headers. To read them, send one request with the same key:

curl -i https://gateway.example.com/v1/chat/completions \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "claude-sonnet-5-5", "messages": [{"role": "user", "content": "Say hello"}]}'

Look at x-spanway-call-id (the id to search for on Logs), x-spanway-model-group and x-spanway-routing-reason (which model group served the call and why, see routing decision headers), x-spanway-response-cost, and x-spanway-key-spend with x-spanway-key-max-budget for the budget left.

What works through the gateway​

FeatureWorksNotes
StreamingYesOver /v1/chat/completions with server-sent events.
Tool callsYes, when the model supports toolsOpenCode's file, shell and MCP tools run on your machine and travel as normal tool calls.
ImagesYes, when the model takes imagesA text-only model behind the name rejects images with a 400 from the provider. In V2, declare image input under the model's capabilities.
ReasoningModel dependentReasoning settings OpenCode sends reach the provider. A provider that does not take one answers 400, see drop params.
Prompt cachingProvider dependentThe cached tokens show in the cost on Logs.
Code traffic rulesOnly after the admin adds the prefixThe gateway recognises Claude Code and Codex by their user agent. For code traffic rules to apply to OpenCode, the admin adds opencode/ to code_traffic_user_agent_prefixes.

Errors​

The text in the third column is what the gateway sends, and OpenCode shows it in the session. The client error reference lists the same errors for every tool.

CaseStatusGateway textFix
spanwayctl opencode cannot reach the gatewaynoneCould not reach the Spanway proxy at <url>: <error>. Is it running, and is --base-url (or SPANWAY_PROXY_URL) correct?Check --base-url and that the gateway runs.
spanwayctl opencode gets a rejected key401 or 403Spanway rejected your key (HTTP <status>). Run `spanwayctl login` to refresh it, or pass a valid --api-key.Run spanwayctl login, or pass a valid --api-key.
OpenCode is not installed where spanwayctl runsnoneCould not find `opencode` on your PATH. Install it first: https://opencode.ai/docsInstall OpenCode on that machine. From the gateway image use option 2 on your own machine instead.
The model list was skippednonespanway: not syncing <name> models from the proxy: <reason>The name is OpenCode. Read the reason. OpenCode still starts, but the Spanway provider has no models.
Wrong or deleted key401Authentication Error, Invalid proxy server token passedCheck SPANWAY_API_KEY in the terminal that started OpenCode.
Blocked key401Authentication Error, Key is blocked. Update via `/key/unblock` if you're an admin.Ask the admin to open the key in Virtual Keys and click Unblock Key.
The key may not use the model403The requested model '<model>' is not available for this API key, or the model name is invalid.Pick another model in /models, or ask the admin to add it to the key. Check small_model too.
The model name does not exist on the gateway400Invalid model name passed in model=<name>Make the model key in opencode.json match a name from GET /v1/models exactly.
The budget is spent422Budget has been exceeded! Key=<key alias> Current cost: <spend>, Max budget: <max>Wait for the reset, or ask the admin to raise the budget.
The key's rate limit is reached429Rate limit exceeded for <scope>: <value>. Limit type: <type>.Wait, or ask for a higher RPM or TPM limit.
Wrong path, such as a doubled /v1404Not FoundSet baseURL to https://gateway.example.com/v1 exactly once.
Connection refused, DNS or TLS errorsnoneNone, the gateway never answered.See connection problems. OpenCode is a Node program, so a company root certificate goes in NODE_EXTRA_CA_CERTS.
OpenCode says Model unavailable: spanway/<model>noneNone, OpenCode decides this itself.The model id is not under models in the file, or the provider is not active. Check the provider id and the model key.

Troubleshooting​

  1. Find the request on Logs by your key alias and the time. If a row is there, the drawer shows the status, the message, the model group the router picked and the provider's answer.
  2. If there is no row, OpenCode never reached the gateway. Check baseURL and the key variable, then run the curl above with the same values.
  3. Run OpenCode with its own logs on the terminal: opencode --print-logs --log-level DEBUG. The log files live under ~/.local/share/opencode/log on macOS and Linux, and opencode debug paths prints the exact folder.
  4. With spanwayctl opencode, read the lines it prints before OpenCode starts. spanway: routing OpenCode through proxy at <url> confirms the address, and a not syncing line says why the model list is missing.
  5. Read the routing headers from the curl above. x-spanway-attempts higher than 1 means the gateway retried or fell back, and x-spanway-routing-reason says why.

Rotate or remove the key​

To rotate, open the key on Virtual Keys, click Regenerate Key and set a Grace Period such as 24h. Put the new key in SPANWAY_API_KEY (or pass it to spanwayctl --api-key) and open a new terminal. opencode.json does not change, because it only names the variable. POST /key/{key}/regenerate does the same from the API and needs an Enterprise license. Without one, create a new key, switch to it and delete the old one.

To stop using the gateway, delete the spanway provider from opencode.json, or stop starting OpenCode through spanwayctl. To cut the key off, use Block Key in the key's actions menu, which can be undone, or delete the key. From the API, POST /key/block with {"key": "sk-..."} blocks it and POST /key/delete with {"keys": ["sk-..."]} deletes it.