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 withopencode --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,
spanwayctlon your machine, see the CLI reference. The gateway image does not contain OpenCode, sospanwayctl opencodehas to run where OpenCode is installed.
Make a key for OpenCode
- In the Admin UI open Virtual Keys (
/ui/api-keys) and click + Create New Key. - Set Key Name to who and which tool, for example
jane-opencode. Leave Key Type on AI APIs. - In Models, pick every model the developer may choose in
/models. If the developer setssmall_modelin 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. - Open Optional Settings. Set Max Budget (USD), for example
150, with Reset Budget on monthly, and a Requests per minute Limit (RPM) such as60. 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. - 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
-
Run OpenCode through
spanwayctl. Everything afteropencodeis passed on to OpenCode.spanwayctl --base-url https://gateway.example.com --api-key sk-... opencode -
Open
/modelsin OpenCode and pick a model under Spanway.
What spanwayctl opencode does, in order:
- Checks the key with
GET /v1/models. A rejected key stops here with a clear message, see errors.--skip-verifyskips this check. - Sets
OPENAI_BASE_URLtohttps://gateway.example.com/v1andOPENAI_API_KEYto your key, for this run only. - Reads the models your key may use from
/v1/models, keeps the chat models, and passes OpenCode a provider calledspanway(shown as Spanway) with one entry per model through theOPENCODE_CONFIG_CONTENTenvironment variable. A model whose gateway entry hasmax_input_tokensandmax_output_tokensgets 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. - 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
-
Put the key in your shell profile (
~/.zshrcor~/.bashrc) and open a new terminal.export SPANWAY_API_KEY="sk-..." -
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" -
Open
~/.config/opencode/opencode.jsonfor every project, oropencode.jsonin a project's root for one project. Add the provider. The base URL includes/v1, because OpenCode adds/chat/completionsto 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,npmandoptions:{"$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"} -
Start OpenCode with
opencode, open/modelsand pick a model under Spanway. For a one-off check without the interface, runopencode run "Say hello".
| Setting | What to put | Why |
|---|---|---|
Provider id (spanway) | Any id that is not a built-in provider | Models 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>. |
baseURL | https://gateway.example.com/v1, with /v1 | OpenCode adds /chat/completions. |
Model keys under models | The exact public names from GET /v1/models | The 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.output | The model's input and output token limits | OpenCode 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
| Feature | Works | Notes |
|---|---|---|
| Streaming | Yes | Over /v1/chat/completions with server-sent events. |
| Tool calls | Yes, when the model supports tools | OpenCode's file, shell and MCP tools run on your machine and travel as normal tool calls. |
| Images | Yes, when the model takes images | A text-only model behind the name rejects images with a 400 from the provider. In V2, declare image input under the model's capabilities. |
| Reasoning | Model dependent | Reasoning settings OpenCode sends reach the provider. A provider that does not take one answers 400, see drop params. |
| Prompt caching | Provider dependent | The cached tokens show in the cost on Logs. |
| Code traffic rules | Only after the admin adds the prefix | The 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.
| Case | Status | Gateway text | Fix |
|---|---|---|---|
spanwayctl opencode cannot reach the gateway | none | Could 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 key | 401 or 403 | Spanway 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 runs | none | Could not find `opencode` on your PATH. Install it first: https://opencode.ai/docs | Install OpenCode on that machine. From the gateway image use option 2 on your own machine instead. |
| The model list was skipped | none | spanway: 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 key | 401 | Authentication Error, Invalid proxy server token passed | Check SPANWAY_API_KEY in the terminal that started OpenCode. |
| Blocked key | 401 | Authentication 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 model | 403 | The 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 gateway | 400 | Invalid model name passed in model=<name> | Make the model key in opencode.json match a name from GET /v1/models exactly. |
| The budget is spent | 422 | Budget 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 reached | 429 | Rate limit exceeded for <scope>: <value>. Limit type: <type>. | Wait, or ask for a higher RPM or TPM limit. |
Wrong path, such as a doubled /v1 | 404 | Not Found | Set baseURL to https://gateway.example.com/v1 exactly once. |
| Connection refused, DNS or TLS errors | none | None, 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> | none | None, 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
- 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.
- If there is no row, OpenCode never reached the gateway. Check
baseURLand the key variable, then run the curl above with the same values. - Run OpenCode with its own logs on the terminal:
opencode --print-logs --log-level DEBUG. The log files live under~/.local/share/opencode/logon macOS and Linux, andopencode debug pathsprints the exact folder. - With
spanwayctl opencode, read the lines it prints before OpenCode starts.spanway: routing OpenCode through proxy at <url>confirms the address, and anot syncingline says why the model list is missing. - Read the routing headers from the curl above.
x-spanway-attemptshigher than1means the gateway retried or fell back, andx-spanway-routing-reasonsays 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.
Related
- CLI reference for every
spanwayctlagent command. - Connect any client for the base URL rules shared by every tool.
- Client error reference for every gateway error with its cause.
- Make a key for a tool for the admin side.
- Codex, pi and other CLI agents for the other terminal agents.