rename provider to commandcode-go to avoid collision with opencode built-in commandcode provider

This commit is contained in:
nhat.nguyenhong 2026-10-18 11:51:40 +07:00
parent e63be86ba5
commit 3a8412f28d
11 changed files with 100 additions and 61 deletions

1
.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
* text=auto eol=lf

View File

@ -27,7 +27,7 @@ npm run typecheck # tsc --noEmit (provider) + tsc -p tsconfig.tui.json (TUI plu
npm run build # tsc -> dist/ (provider only; the TUI plugin is loaded from source) npm run build # tsc -> dist/ (provider only; the TUI plugin is loaded from source)
npm run smoke # live request against CommandCode (needs a key) npm run smoke # live request against CommandCode (needs a key)
npm run quota # live 5-hour/weekly/monthly quota (needs a key) npm run quota # live 5-hour/weekly/monthly quota (needs a key)
npm run sync-models # regenerate provider.commandcode.models from the live catalog npm run sync-models # regenerate provider.commandcode-go.models from the live catalog
``` ```
There is no unit-test suite. `scripts/smoke.mjs` is the end-to-end check. `scripts/sync-models.mjs` There is no unit-test suite. `scripts/smoke.mjs` is the end-to-end check. `scripts/sync-models.mjs`
@ -54,7 +54,7 @@ tsconfig.tui.json Typechecks src/tui.tsx (+ quota/toggles) against the shim (no
src/constants.ts Defaults, paths, headers, passthrough params, static config block. src/constants.ts Defaults, paths, headers, passthrough params, static config block.
scripts/smoke.mjs Live end-to-end check. scripts/smoke.mjs Live end-to-end check.
scripts/quota.mjs Print the live quota headlessly (reads the same config as smoke). scripts/quota.mjs Print the live quota headlessly (reads the same config as smoke).
scripts/sync-models.mjs Catalog -> provider.commandcode.models generator (with vision probing). scripts/sync-models.mjs Catalog -> provider.commandcode-go.models generator (with vision probing).
server.py Reference Python proxy (do not modify unless explicitly asked). server.py Reference Python proxy (do not modify unless explicitly asked).
``` ```
@ -119,7 +119,8 @@ These are load-bearing. Breaking one causes silent failures in opencode.
10. **Upstream cost never appears on `finish`.** Per-request USD arrives on `finish-step` 10. **Upstream cost never appears on `finish`.** Per-request USD arrives on `finish-step`
(`usage.raw.cost/market_cost/gateway_cost`, numbers) and `provider-metadata` (`usage.raw.cost/market_cost/gateway_cost`, numbers) and `provider-metadata`
(`providerMetadata.gateway.cost/marketCost`, strings). `finish.totalUsage` carries tokens (`providerMetadata.gateway.cost/marketCost`, strings). `finish.totalUsage` carries tokens
only. Capture both into `providerMetadata: { commandcode: { cost, marketCost } }` on the only. Capture both into `providerMetadata` keyed by the resolved provider id
(`options.name`; `commandcode-go` under opencode and as the factory default) on the
terminal V3 `finish` part (and `doGenerate` result), and stash into `usage.raw`. A reported terminal V3 `finish` part (and `doGenerate` result), and stash into `usage.raw`. A reported
`0` is meaningful; only `undefined` means absent. The built-in sidebar still shows `$0.00` `0` is meaningful; only `undefined` means absent. The built-in sidebar still shows `$0.00`
until the fork consumes this field (anomalyco/opencode#43818); `/cc-usage` is the accurate until the fork consumes this field (anomalyco/opencode#43818); `/cc-usage` is the accurate
@ -127,7 +128,7 @@ These are load-bearing. Breaking one causes silent failures in opencode.
11. **`file://` npm specs bypass install.** opencode imports `dist/index.js` directly, so the repo 11. **`file://` npm specs bypass install.** opencode imports `dist/index.js` directly, so the repo
must be rebuilt for opencode to see source changes. must be rebuilt for opencode to see source changes.
12. **`/models` is config-driven, not provider-driven.** opencode builds the model list from 12. **`/models` is config-driven, not provider-driven.** opencode builds the model list from
`provider.commandcode.models` in `opencode.json` and never asks a custom `file://` provider to `provider.commandcode-go.models` in `opencode.json` and never asks a custom `file://` provider to
discover models (only internal providers can register `discoverModels`). Refresh the map with discover models (only internal providers can register `discoverModels`). Refresh the map with
`npm run sync-models`; do not expect a discovery hook in `src/` to populate it. `npm run sync-models`; do not expect a discovery hook in `src/` to populate it.
13. **The TUI plugin lives outside the provider entrypoint.** `src/tui.tsx` is loaded from 13. **The TUI plugin lives outside the provider entrypoint.** `src/tui.tsx` is loaded from
@ -171,7 +172,7 @@ These are load-bearing. Breaking one causes silent failures in opencode.
A slash-only entry is not expressible; registering `/cc-*` also adds them to `Ctrl+P`. A slash-only entry is not expressible; registering `/cc-*` also adds them to `Ctrl+P`.
15. **Toggles are resolved per request, never at load.** `zdr` and `debug` are read in 15. **Toggles are resolved per request, never at load.** `zdr` and `debug` are read in
`model.ts`/`log.ts` on every call from the toggle file, so `/cc-*` changes take effect `model.ts`/`log.ts` on every call from the toggle file, so `/cc-*` changes take effect
without restarting opencode. Precedence for `zdr`: `providerOptions.commandcode.zdr` > without restarting opencode. Precedence for `zdr`: `providerOptions.commandcode-go.zdr` >
`x-cmd-zdr` header > toggle file. Do not reintroduce load-time consts. `x-cmd-zdr` header > toggle file. Do not reintroduce load-time consts.
16. **Quota is live from the alpha billing API, not `server.py`.** `src/quota.ts` reads 16. **Quota is live from the alpha billing API, not `server.py`.** `src/quota.ts` reads
`/alpha/whoami`, `/alpha/billing/credits`, `/alpha/billing/subscriptions`, and `/alpha/whoami`, `/alpha/billing/credits`, `/alpha/billing/subscriptions`, and
@ -179,7 +180,7 @@ These are load-bearing. Breaking one causes silent failures in opencode.
these and is not the guide here. `resetAt` has shipped as both seconds and epoch ms — normalize these and is not the guide here. `resetAt` has shipped as both seconds and epoch ms — normalize
(>= 1e12 = ms). The monthly meter is **derived** (spend + remaining credits), so it works on any (>= 1e12 = ms). The monthly meter is **derived** (spend + remaining credits), so it works on any
plan; never hardcode a plan→cap table. The TUI resolves the key from `api.state` (provider plan; never hardcode a plan→cap table. The TUI resolves the key from `api.state` (provider
entry, then `config.provider.commandcode.options`, then `COMMANDCODE_API_KEY`), expanding entry, then `config.provider.commandcode-go.options`, then `COMMANDCODE_API_KEY`), expanding
`{env:VAR}` itself, and must never log the key — quota errors go through `redact()`. `{env:VAR}` itself, and must never log the key — quota errors go through `redact()`.
17. **Retryable upstream failures can arrive inside an HTTP 200 stream.** CommandCode's gateway 17. **Retryable upstream failures can arrive inside an HTTP 200 stream.** CommandCode's gateway
answers `200` and then emits an SSE `error` event carrying `statusCode`/`isRetryable` (e.g. answers `200` and then emits an SSE `error` event carrying `statusCode`/`isRetryable` (e.g.
@ -189,6 +190,20 @@ These are load-bearing. Breaking one causes silent failures in opencode.
body and retries with backoff. Once any content event is seen the error is surfaced, not body and retries with backoff. Once any content event is seen the error is surfaced, not
retried (retrying mid-stream would duplicate output). Non-retryable in-stream errors (400s) retried (retrying mid-stream would duplicate output). Non-retryable in-stream errors (400s)
surface immediately. Keep the preamble set in sync if upstream adds new pre-content events. surface immediately. Keep the preamble set in sync if upstream adds new pre-content events.
18. **The provider id is `commandcode-go` (`PROVIDER_ID` in `constants.ts`) and must never be
`commandcode`.** opencode 1.18+ ships a models.dev catalog entry for `commandcode`
(OpenAI-compatible, `api: https://api.commandcode.ai/provider/v1`). For a config-defined
provider whose id matches a catalog id, opencode sets each model's `api.url` from the catalog
entry and `resolveSDK` forwards it as `options.baseURL` into the factory
(`packages/opencode/src/provider/provider.ts`, models-dev merge + `options["baseURL"] =
model.api.url`), so a `commandcode`-id provider posts to `/provider/v1/alpha/generate` and
gets `404 not a registered API route`. A non-catalog id has `api.url === ""` → no injected
baseURL → `DEFAULT_BASE_URL` applies; `commandcode-go` is absent from the catalog (unlike
`commandcode` and `opencode-go`), so it is safe. The official catalog provider is neutralized
with `"disabled_providers": ["commandcode"]`; `disabled_providers` filters the final merged
provider map, so it would also kill a config provider sharing the id — never re-register
under `commandcode`. `PROVIDER_ID` lives in `src/constants.ts`; scripts import it from
`dist/constants.js`; `providerOptions` is read only under `commandcode-go`.
## Change workflow ## Change workflow
@ -220,9 +235,9 @@ npm run quota
Inside opencode (restart it first if config changed): Inside opencode (restart it first if config changed):
```powershell ```powershell
opencode models commandcode opencode models commandcode-go
opencode run "Reply with exactly: pong" -m commandcode/deepseek/deepseek-v4-flash-vision-exp opencode run "Reply with exactly: pong" -m commandcode-go/deepseek/deepseek-v4-flash-vision-exp
opencode run "Use the glob tool to list *.mjs in this directory and report the filenames." -m commandcode/deepseek/deepseek-v4-flash-vision-exp opencode run "Use the glob tool to list *.mjs in this directory and report the filenames." -m commandcode-go/deepseek/deepseek-v4-flash-vision-exp
``` ```
The third command confirms the full tool-call round trip (tool-call emitted, executed, result The third command confirms the full tool-call round trip (tool-call emitted, executed, result

View File

@ -45,8 +45,9 @@ npm run build
// 2. ~/.config/opencode/opencode.json (or a project opencode.json) // 2. ~/.config/opencode/opencode.json (or a project opencode.json)
{ {
"$schema": "https://opencode.ai/config.json", "$schema": "https://opencode.ai/config.json",
"disabled_providers": ["commandcode"],
"provider": { "provider": {
"commandcode": { "commandcode-go": {
"name": "Command Code", "name": "Command Code",
"npm": "file:///C:/dev/opencode-commandcode-provider/dist/index.js", "npm": "file:///C:/dev/opencode-commandcode-provider/dist/index.js",
"options": { "options": {
@ -65,11 +66,20 @@ npm run build
} }
``` ```
> The provider id is **`commandcode-go`**, deliberately not `commandcode`. opencode's models.dev
> catalog defines an official `commandcode` provider (OpenAI-compatible,
> `api.commandcode.ai/provider/v1`); opencode merges any config-defined provider with the catalog
> entry of the same id and forwards the catalog `api` URL as `options.baseURL`, which breaks this
> provider's `/alpha/generate` path with a `404 not a registered API route`. Using a non-catalog id
> avoids the merge; list the official provider under `disabled_providers` so it stays out of the
> model picker. If you previously used `provider.commandcode` or `provider.opencc`, rename the key
> to `commandcode-go` (the `models` map is unchanged).
Then set the key and restart opencode: Then set the key and restart opencode:
```powershell ```powershell
$env:COMMANDCODE_API_KEY = "user_..." $env:COMMANDCODE_API_KEY = "user_..."
opencode models commandcode opencode models commandcode-go
``` ```
> opencode loads configuration **once at startup**. After changing `opencode.json`, a plugin, or > opencode loads configuration **once at startup**. After changing `opencode.json`, a plugin, or
@ -82,7 +92,7 @@ to it, but opencode builds `/models` and the TUI picker from this map and never
## Listing all CommandCode models ## Listing all CommandCode models
opencode reads the model list from `provider.commandcode.models`; a custom provider cannot opencode reads the model list from `provider.commandcode-go.models`; a custom provider cannot
register dynamic discovery. `scripts/sync-models.mjs` fetches the live catalog from register dynamic discovery. `scripts/sync-models.mjs` fetches the live catalog from
`GET /provider/v1/models` and opens an interactive checkbox picker (nothing pre-checked). `GET /provider/v1/models` and opens an interactive checkbox picker (nothing pre-checked).
Only the selected models are vision-probed and written into your global opencode config — Only the selected models are vision-probed and written into your global opencode config —
@ -100,14 +110,14 @@ without writing. Each row shows the model id and name plus a second line with it
interactive terminal. interactive terminal.
Before anything else the script requires a CommandCode API key (from Before anything else the script requires a CommandCode API key (from
`provider.commandcode.options.apiKey` or `COMMANDCODE_API_KEY`). If neither is present — including `provider.commandcode-go.options.apiKey` or `COMMANDCODE_API_KEY`). If neither is present — including
when `opencode.json` does not exist yet — it exits and points you at the CommandCode Console when `opencode.json` does not exist yet — it exits and points you at the CommandCode Console
(<https://commandcode.ai/studio/provider>) to generate one. It never writes without a key. (<https://commandcode.ai/studio/provider>) to generate one. It never writes without a key.
Then restart opencode and confirm: Then restart opencode and confirm:
```powershell ```powershell
opencode models commandcode opencode models commandcode-go
``` ```
Mapping and behaviour: Mapping and behaviour:
@ -124,23 +134,23 @@ Mapping and behaviour:
values. Other fields (`variants`, `options`, `cost`, …) on selected ids are preserved. values. Other fields (`variants`, `options`, `cost`, …) on selected ids are preserved.
Unselected ids are removed from the map. Unselected ids are removed from the map.
The API key is read from `COMMANDCODE_API_KEY`, then `provider.commandcode.options.apiKey` in the The API key is read from `COMMANDCODE_API_KEY`, then `provider.commandcode-go.options.apiKey` in the
global config (`baseURL`/`ccVersion` are read from there too). global config (`baseURL`/`ccVersion` are read from there too).
## Configuration options ## Configuration options
`provider.commandcode.options` is forwarded to `createCommandCode(options)`. `provider.commandcode-go.options` is forwarded to `createCommandCode(options)`.
| Option | Type | Default | Description | | Option | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `apiKey` | `string` | — | CommandCode API key. A bare token or `Bearer <token>` both work. | | `apiKey` | `string` | — | CommandCode API key. A bare token or `Bearer <token>` both work. |
| `headers` | `Record<string,string>` | `{}` | Extra request headers, merged over the built-in ones. An `Authorization` header is accepted as an alternative auth source. | | `headers` | `Record<string,string>` | `{}` | Extra request headers, merged over the built-in ones. An `Authorization` header is accepted as an alternative auth source. |
| `baseURL` | `string` | `https://api.commandcode.ai` | Upstream origin. Trailing slashes are stripped. | | `baseURL` | `string` | `https://api.commandcode.ai` | Upstream origin. Trailing slashes are stripped. |
| `ccVersion` | `string` | `1.15.1` | Value of the `x-command-code-version` header. | | `ccVersion` | `string` | `1.84.0` | Value of the `x-command-code-version` header. |
| `maxRetries` | `number` | `2` | Retry attempts for retryable failures (429/5xx/network). | | `maxRetries` | `number` | `2` | Retry attempts for retryable failures (429/5xx/network). |
| `retryMaxDelaySeconds` | `number` | `60` | Longest wait honoured from `Retry-After`; longer values are not retried. | | `retryMaxDelaySeconds` | `number` | `60` | Longest wait honoured from `Retry-After`; longer values are not retried. |
| `name` | `string` | `commandcode` | Provider id reported to the AI SDK. opencode sets this automatically. | | `name` | `string` | `commandcode-go` | Provider id reported to the AI SDK. opencode sets this automatically. |
**Auth precedence:** `options.apiKey` wins; otherwise the value of an `Authorization` header in **Auth precedence:** `options.apiKey` wins; otherwise the value of an `Authorization` header in
`options.headers` (with a leading `Bearer ` stripped). If neither is present, requests are sent `options.headers` (with a leading `Bearer ` stripped). If neither is present, requests are sent
@ -182,12 +192,12 @@ useful for diagnosing model selection, retry, tool-call, and finish-reason issue
The `x-cmd-zdr: 1` request header is **omitted by default** because it is rejected by some The `x-cmd-zdr: 1` request header is **omitted by default** because it is rejected by some
models. It can be enabled with the `/cc-zdr` slash command or models. It can be enabled with the `/cc-zdr` slash command or
`providerOptions.commandcode.zdr`. The value is resolved per request, so toggling it `providerOptions.commandcode-go.zdr`. The value is resolved per request, so toggling it
does not require restarting opencode. does not require restarting opencode.
Precedence, highest first: Precedence, highest first:
1. `providerOptions.commandcode.zdr` (`true`/`false`), e.g. a model variant or agent option. 1. `providerOptions.commandcode-go.zdr` (`true`/`false`), e.g. a model variant or agent option.
2. An explicit `x-cmd-zdr` header in `opencode.json` `options.headers` or the call's `headers`. 2. An explicit `x-cmd-zdr` header in `opencode.json` `options.headers` or the call's `headers`.
3. The toggle file (`zdr` key — see [Runtime toggles](#runtime-toggles)). 3. The toggle file (`zdr` key — see [Runtime toggles](#runtime-toggles)).
@ -244,7 +254,7 @@ usage alone; it is omitted when no descendant sessions were found.
## Quota tracking ## Quota tracking
`/cc-usage` and the sidebar show CommandCode's **5-hour**, **weekly** and **monthly** usage for the `/cc-usage` and the sidebar show CommandCode's **5-hour**, **weekly** and **monthly** usage for the
account behind `provider.commandcode.options.apiKey`. The numbers come live from the same alpha account behind `provider.commandcode-go.options.apiKey`. The numbers come live from the same alpha
billing endpoints the `cmd` CLI `/usage` command uses: billing endpoints the `cmd` CLI `/usage` command uses:
| Endpoint | Used for | | Endpoint | Used for |
@ -295,10 +305,10 @@ The API key is never logged; quota errors pass through `redact()` like every oth
| Tool results | Yes — paired results are replayed; unpaired ids are dropped | | Tool results | Yes — paired results are replayed; unpaired ids are dropped |
| Multiple images (vision) | Yes — `data:` URIs, raw base64, `Uint8Array`, and remote URLs | | Multiple images (vision) | Yes — `data:` URIs, raw base64, `Uint8Array`, and remote URLs |
| Token usage | Yes — input/output totals, cache read, reasoning tokens | | Token usage | Yes — input/output totals, cache read, reasoning tokens |
| Provider-reported cost | Yes — per-request USD from `finish-step`/`provider-metadata` is forwarded as `providerMetadata.commandcode.cost` (plus `marketCost`); also stashed in `usage.raw`. The built-in sidebar still shows `$0.00` until opencode itself consumes this field (upstream `anomalyco/opencode#43818`); `/cc-usage` remains the accurate dollar source | | Provider-reported cost | Yes — per-request USD from `finish-step`/`provider-metadata` is forwarded as `providerMetadata.commandcode-go.cost` (plus `marketCost`); also stashed in `usage.raw`. The built-in sidebar still shows `$0.00` until opencode itself consumes this field (upstream `anomalyco/opencode#43818`); `/cc-usage` remains the accurate dollar source |
| Finish reasons | Yes — unified (`stop`, `length`, `tool-calls`, `content-filter`, `error`, `other`) plus raw | | Finish reasons | Yes — unified (`stop`, `length`, `tool-calls`, `content-filter`, `error`, `other`) plus raw |
| Sampling parameters | Yes — `temperature`, `topP`, `topK`, `stopSequences`, `seed`, presence/frequency penalties | | Sampling parameters | Yes — `temperature`, `topP`, `topK`, `stopSequences`, `seed`, presence/frequency penalties |
| `reasoning_effort` | Yes — via `providerOptions.commandcode` | | `reasoning_effort` | Yes — via `providerOptions.commandcode-go` |
| Retry with backoff | Yes — 429/5xx and network errors, honouring `Retry-After`; also retryable `error` events that arrive inside an HTTP 200 stream before any content (gateway 520s) | | Retry with backoff | Yes — 429/5xx and network errors, honouring `Retry-After`; also retryable `error` events that arrive inside an HTTP 200 stream before any content (gateway 520s) |
| Credential redaction | Yes — error bodies are scrubbed before surfacing | | Credential redaction | Yes — error bodies are scrubbed before surfacing |
| Runtime toggles | Yes — `/cc-zdr` and `/cc-debug` flip the shared toggle file without a restart | | Runtime toggles | Yes — `/cc-zdr` and `/cc-debug` flip the shared toggle file without a restart |
@ -321,7 +331,7 @@ Set the per-request reasoning effort through provider options:
```jsonc ```jsonc
// opencode model options / variant // opencode model options / variant
"options": { "providerOptions": { "commandcode": { "reasoningEffort": "high" } } } "options": { "providerOptions": { "commandcode-go": { "reasoningEffort": "high" } } }
``` ```
Both `reasoning_effort` and `reasoningEffort` keys are recognised and forwarded as Both `reasoning_effort` and `reasoningEffort` keys are recognised and forwarded as
@ -343,7 +353,7 @@ src/tui.tsx opencode TUI plugin: /cc-zdr, /cc-debug, /cc-status, /cc-usage
src/constants.ts Defaults, header names, passthrough params, static config block. src/constants.ts Defaults, header names, passthrough params, static config block.
scripts/smoke.mjs Live end-to-end check against api.commandcode.ai. scripts/smoke.mjs Live end-to-end check against api.commandcode.ai.
scripts/quota.mjs Print the live quota headlessly. scripts/quota.mjs Print the live quota headlessly.
scripts/sync-models.mjs Pick models interactively and write provider.commandcode.models. scripts/sync-models.mjs Pick models interactively and write provider.commandcode-go.models.
``` ```
### Request lifecycle ### Request lifecycle
@ -372,11 +382,11 @@ npm run typecheck # tsc --noEmit (provider) + tsc -p tsconfig.tui.json (TUI plu
npm run build # tsc -> dist/ (provider only; the TUI plugin loads from source) npm run build # tsc -> dist/ (provider only; the TUI plugin loads from source)
npm run smoke # live request against CommandCode npm run smoke # live request against CommandCode
npm run quota # live 5-hour/weekly/monthly quota npm run quota # live 5-hour/weekly/monthly quota
npm run sync-models # regenerate provider.commandcode.models from the catalog npm run sync-models # regenerate provider.commandcode-go.models from the catalog
``` ```
`scripts/smoke.mjs` reads the key from `COMMANDCODE_API_KEY`, falling back to `scripts/smoke.mjs` reads the key from `COMMANDCODE_API_KEY`, falling back to
`provider.commandcode.options.apiKey` in `~/.config/opencode/opencode.json`. It exercises both `provider.commandcode-go.options.apiKey` in `~/.config/opencode/opencode.json`. It exercises both
`doGenerate` and `doStream` and prints content, finish reason, and usage. `doGenerate` and `doStream` and prints content, finish reason, and usage.
To smoke-test a specific model: To smoke-test a specific model:
@ -388,16 +398,16 @@ node scripts/smoke.mjs deepseek/deepseek-v4.1-flash
### Verifying inside opencode ### Verifying inside opencode
```powershell ```powershell
opencode models commandcode opencode models commandcode-go
opencode run "Reply with exactly: pong" -m commandcode/deepseek/deepseek-v4.1-flash opencode run "Reply with exactly: pong" -m commandcode-go/deepseek/deepseek-v4.1-flash
opencode run "Use the glob tool to list *.mjs and report the filenames." -m commandcode/deepseek/deepseek-v4.1-flash opencode run "Use the glob tool to list *.mjs and report the filenames." -m commandcode-go/deepseek/deepseek-v4.1-flash
``` ```
## Troubleshooting ## Troubleshooting
| Symptom | Likely cause / fix | | Symptom | Likely cause / fix |
| --- | --- | | --- | --- |
| `Provider not found: commandcode` | Provider was dropped because `models` is empty, or the `npm` path is wrong. Confirm `dist/index.js` exists (`npm run build`) and that the `file://` path is absolute. | | `Provider not found: commandcode-go` | Provider was dropped because `models` is empty, or the `npm` path is wrong. Confirm `dist/index.js` exists (`npm run build`) and that the `file://` path is absolute. |
| Models appear but every call fails auth | `options.apiKey` missing/expired, or `{env:COMMANDCODE_API_KEY}` not set in the environment opencode was launched with. | | Models appear but every call fails auth | `options.apiKey` missing/expired, or `{env:COMMANDCODE_API_KEY}` not set in the environment opencode was launched with. |
| `stream ended ... no finish` / truncated output | Upstream closed the connection early. The provider emits a synthetic `finish`, but the response is incomplete; retry the turn. | | `stream ended ... no finish` / truncated output | Upstream closed the connection early. The provider emits a synthetic `finish`, but the response is incomplete; retry the turn. |
| Images are ignored by the model | The selected model is not vision-capable. Mark it with `"attachment": true` and `modalities.input: ["text","image"]` in `models`, and pick a vision model id. | | Images are ignored by the model | The selected model is not vision-capable. Mark it with `"attachment": true` and `modalities.input: ["text","image"]` in `models`, and pick a vision model id. |

View File

@ -2,7 +2,8 @@
"$schema": "https://opencode.ai/config.json", "$schema": "https://opencode.ai/config.json",
"disabled_providers": [ "disabled_providers": [
"opencode", "opencode",
"opencode-go" "opencode-go",
"commandcode"
], ],
"mcp": { "mcp": {
"parallel": { "parallel": {
@ -32,7 +33,7 @@
}, },
"default_agent": "plan", "default_agent": "plan",
"provider": { "provider": {
"commandcode": { "commandcode-go": {
"name": "Command Code", "name": "Command Code",
"npm": "path/to/opencode-ccgo-provider/dist/index.js", "npm": "path/to/opencode-ccgo-provider/dist/index.js",
"options": { "options": {

View File

@ -7,6 +7,7 @@ import { readFileSync } from "node:fs";
import { homedir } from "node:os"; import { homedir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { fetchQuota, formatQuota } from "../dist/quota.js"; import { fetchQuota, formatQuota } from "../dist/quota.js";
import { PROVIDER_ID } from "../dist/constants.js";
function parseArgs(argv) { function parseArgs(argv) {
const opts = { const opts = {
@ -63,7 +64,7 @@ function readConfig(path) {
function resolveKey(config, env) { function resolveKey(config, env) {
const fromEnv = env.COMMANDCODE_API_KEY; const fromEnv = env.COMMANDCODE_API_KEY;
if (fromEnv && fromEnv.trim()) return fromEnv.trim(); if (fromEnv && fromEnv.trim()) return fromEnv.trim();
const options = config?.provider?.commandcode?.options ?? {}; const options = config?.provider?.[PROVIDER_ID]?.options ?? {};
const fromConfig = options.apiKey; const fromConfig = options.apiKey;
if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim(); if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim();
const auth = options.headers?.Authorization ?? options.headers?.authorization; const auth = options.headers?.Authorization ?? options.headers?.authorization;
@ -76,12 +77,12 @@ const config = readConfig(opts.config);
const apiKey = resolveKey(config, process.env); const apiKey = resolveKey(config, process.env);
if (!apiKey) { if (!apiKey) {
console.error( console.error(
`No CommandCode API key found. Set COMMANDCODE_API_KEY or provider.commandcode.options.apiKey in ${opts.config}.`, `No CommandCode API key found. Set COMMANDCODE_API_KEY or provider.${PROVIDER_ID}.options.apiKey in ${opts.config}.`,
); );
process.exit(1); process.exit(1);
} }
const baseURL = opts.baseURL ?? config?.provider?.commandcode?.options?.baseURL; const baseURL = opts.baseURL ?? config?.provider?.[PROVIDER_ID]?.options?.baseURL;
const result = await fetchQuota({ apiKey, baseURL: typeof baseURL === "string" ? baseURL : undefined }); const result = await fetchQuota({ apiKey, baseURL: typeof baseURL === "string" ? baseURL : undefined });
if (!result.ok) { if (!result.ok) {
console.error(result.error.message); console.error(result.error.message);

View File

@ -3,13 +3,14 @@ import { readFileSync } from "node:fs";
import { homedir } from "node:os"; import { homedir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { createCommandCode } from "../dist/index.js"; import { createCommandCode } from "../dist/index.js";
import { PROVIDER_ID } from "../dist/constants.js";
function apiKey() { function apiKey() {
if (process.env.COMMANDCODE_API_KEY) return process.env.COMMANDCODE_API_KEY; if (process.env.COMMANDCODE_API_KEY) return process.env.COMMANDCODE_API_KEY;
const configPath = join(homedir(), ".config", "opencode", "opencode.json"); const configPath = join(homedir(), ".config", "opencode", "opencode.json");
try { try {
const cfg = JSON.parse(readFileSync(configPath, "utf8")); const cfg = JSON.parse(readFileSync(configPath, "utf8"));
return cfg.provider?.commandcode?.options?.apiKey; return cfg.provider?.[PROVIDER_ID]?.options?.apiKey;
} catch { } catch {
return undefined; return undefined;
} }
@ -18,11 +19,11 @@ function apiKey() {
const modelId = process.argv[2] ?? "deepseek/deepseek-v4-flash-vision-exp"; const modelId = process.argv[2] ?? "deepseek/deepseek-v4-flash-vision-exp";
const key = apiKey(); const key = apiKey();
if (!key) { if (!key) {
console.error("No API key: set COMMANDCODE_API_KEY or configure provider.commandcode.options.apiKey"); console.error(`No API key: set COMMANDCODE_API_KEY or configure provider.${PROVIDER_ID}.options.apiKey`);
process.exit(1); process.exit(1);
} }
const provider = createCommandCode({ name: "commandcode", apiKey: key }); const provider = createCommandCode({ name: PROVIDER_ID, apiKey: key });
const model = provider.languageModel(modelId); const model = provider.languageModel(modelId);
console.log(`== doGenerate: ${modelId} ==`); console.log(`== doGenerate: ${modelId} ==`);

View File

@ -1,4 +1,4 @@
// Interactive model picker for opencode `provider.commandcode.models`. // Interactive model picker for opencode `provider.commandcode-go.models`.
// //
// opencode builds `/models` from the configured model map; a custom `file://` provider is only // opencode builds `/models` from the configured model map; a custom `file://` provider is only
// ever asked for `languageModel(id)`, never queried for discovery. So the catalog has to be baked // ever asked for `languageModel(id)`, never queried for discovery. So the catalog has to be baked
@ -13,7 +13,7 @@ import { dirname, join } from "node:path";
import readline from "node:readline"; import readline from "node:readline";
import { createCommandCode } from "../dist/index.js"; import { createCommandCode } from "../dist/index.js";
import { redact } from "../dist/redact.js"; import { redact } from "../dist/redact.js";
import { DEFAULT_BASE_URL, DEFAULT_CC_VERSION, DEFAULT_MAX_TOKENS, MODELS_PATH } from "../dist/constants.js"; import { DEFAULT_BASE_URL, DEFAULT_CC_VERSION, DEFAULT_MAX_TOKENS, MODELS_PATH, PROVIDER_ID } from "../dist/constants.js";
const CONFIG_PATH = join(homedir(), ".config", "opencode", "opencode.json"); const CONFIG_PATH = join(homedir(), ".config", "opencode", "opencode.json");
const CONSOLE_URL = "https://commandcode.ai/studio/provider"; const CONSOLE_URL = "https://commandcode.ai/studio/provider";
@ -59,7 +59,7 @@ function detectIndent(text) {
function resolveKey(config, env) { function resolveKey(config, env) {
const fromEnv = env.COMMANDCODE_API_KEY; const fromEnv = env.COMMANDCODE_API_KEY;
if (fromEnv) return fromEnv.trim(); if (fromEnv) return fromEnv.trim();
const options = config?.provider?.commandcode?.options ?? {}; const options = config?.provider?.[PROVIDER_ID]?.options ?? {};
const fromConfig = options.apiKey; const fromConfig = options.apiKey;
if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim(); if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim();
const auth = options.headers?.Authorization ?? options.headers?.authorization; const auth = options.headers?.Authorization ?? options.headers?.authorization;
@ -395,8 +395,8 @@ async function main() {
`${where}\n` + `${where}\n` +
`Generate an API key in the CommandCode Console: ${CONSOLE_URL}\n` + `Generate an API key in the CommandCode Console: ${CONSOLE_URL}\n` +
(exists (exists
? `Add it as provider.commandcode.options.apiKey, or export COMMANDCODE_API_KEY.` ? `Add it as provider.${PROVIDER_ID}.options.apiKey, or export COMMANDCODE_API_KEY.`
: `Create that file with provider.commandcode.options.apiKey, or export COMMANDCODE_API_KEY.`) + : `Create that file with provider.${PROVIDER_ID}.options.apiKey, or export COMMANDCODE_API_KEY.`) +
`\nNothing was written.`, `\nNothing was written.`,
); );
process.exit(1); process.exit(1);
@ -407,8 +407,8 @@ async function main() {
process.exit(1); process.exit(1);
} }
const baseURL = (config?.provider?.commandcode?.options?.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ""); const baseURL = (config?.provider?.[PROVIDER_ID]?.options?.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
const ccVersion = config?.provider?.commandcode?.options?.ccVersion ?? DEFAULT_CC_VERSION; const ccVersion = config?.provider?.[PROVIDER_ID]?.options?.ccVersion ?? DEFAULT_CC_VERSION;
console.log(`Fetching catalog: ${baseURL}${MODELS_PATH}`); console.log(`Fetching catalog: ${baseURL}${MODELS_PATH}`);
let catalog; let catalog;
@ -424,7 +424,7 @@ async function main() {
} }
console.log(`Catalog: ${catalog.length} models`); console.log(`Catalog: ${catalog.length} models`);
const existing = config?.provider?.commandcode?.models ?? {}; const existing = config?.provider?.[PROVIDER_ID]?.models ?? {};
const existingIds = new Set(Object.keys(existing)); const existingIds = new Set(Object.keys(existing));
const picked = await pickModels(catalog, existingIds); const picked = await pickModels(catalog, existingIds);
@ -439,7 +439,7 @@ async function main() {
const selected = picked.map((index) => catalog[index]).filter(Boolean); const selected = picked.map((index) => catalog[index]).filter(Boolean);
console.log(`Probing vision (${selected.length} models, concurrency ${CONCURRENCY})...`); console.log(`Probing vision (${selected.length} models, concurrency ${CONCURRENCY})...`);
const provider = createCommandCode({ name: "commandcode", apiKey: key, baseURL, ccVersion, maxRetries: 1 }); const provider = createCommandCode({ name: PROVIDER_ID, apiKey: key, baseURL, ccVersion, maxRetries: 1 });
const probeResults = await mapPool(selected, CONCURRENCY, async (model, index) => { const probeResults = await mapPool(selected, CONCURRENCY, async (model, index) => {
const outcome = await probeVisionConfirmed(provider, model.id); const outcome = await probeVisionConfirmed(provider, model.id);
const tag = outcome.vision === true ? "vision" : outcome.vision === false ? "no-vision" : "unknown"; const tag = outcome.vision === true ? "vision" : outcome.vision === false ? "no-vision" : "unknown";
@ -470,8 +470,8 @@ async function main() {
const removed = [...existingIds].filter((id) => !(id in merged)).length; const removed = [...existingIds].filter((id) => !(id in merged)).length;
config.provider ??= {}; config.provider ??= {};
config.provider.commandcode ??= {}; config.provider[PROVIDER_ID] ??= {};
config.provider.commandcode.models = merged; config.provider[PROVIDER_ID].models = merged;
const indent = detectIndent(text); const indent = detectIndent(text);
const trailing = text === "" || text.endsWith("\n") ? "\n" : ""; const trailing = text === "" || text.endsWith("\n") ? "\n" : "";
@ -484,7 +484,7 @@ async function main() {
` selected=${selected.length} removed=${removed}\n` + ` selected=${selected.length} removed=${removed}\n` +
` probed=${stats.probed} vision=${stats.vision} no-vision=${stats.noVision} ` + ` probed=${stats.probed} vision=${stats.vision} no-vision=${stats.noVision} ` +
`unknown=${stats.unknown} heuristic-vision=${stats.heuristic}\n` + `unknown=${stats.unknown} heuristic-vision=${stats.heuristic}\n` +
`Restart opencode, then run: opencode models commandcode`, `Restart opencode, then run: opencode models ${PROVIDER_ID}`,
); );
} }

View File

@ -1,10 +1,18 @@
// Shared constants. Ported from server.py so the wire shape stays identical. // Shared constants. Ported from server.py so the wire shape stays identical.
// The provider id must not collide with a models.dev catalog id: opencode merges the
// catalog entry for a config-defined provider with the same id and forwards its `api`
// (the OpenAI-compatible base, e.g. `…/provider/v1`) as `options.baseURL`, which breaks
// the `/alpha/generate` path. `commandcode` is taken by the official catalog entry, so
// this provider registers as `commandcode-go` (disable the built-in via
// `disabled_providers`).
export const PROVIDER_ID = "commandcode-go";
export const DEFAULT_BASE_URL = "https://api.commandcode.ai"; export const DEFAULT_BASE_URL = "https://api.commandcode.ai";
export const GENERATE_PATH = "/alpha/generate"; export const GENERATE_PATH = "/alpha/generate";
export const MODELS_PATH = "/provider/v1/models"; export const MODELS_PATH = "/provider/v1/models";
export const DEFAULT_CC_VERSION = "1.15.1"; export const DEFAULT_CC_VERSION = "1.84.0";
export const DEFAULT_MAX_TOKENS = 32000; export const DEFAULT_MAX_TOKENS = 32000;
export const DEFAULT_MAX_RETRIES = 2; export const DEFAULT_MAX_RETRIES = 2;
export const BASE_RETRY_DELAY = 0.5; export const BASE_RETRY_DELAY = 0.5;

View File

@ -17,6 +17,7 @@ import {
DEFAULT_MAX_RETRIES, DEFAULT_MAX_RETRIES,
DEFAULT_RETRY_MAX_DELAY, DEFAULT_RETRY_MAX_DELAY,
GENERATE_PATH, GENERATE_PATH,
PROVIDER_ID,
} from "./constants.js"; } from "./constants.js";
import { iterateEvents } from "./events.js"; import { iterateEvents } from "./events.js";
import { debugWhen, isDebugEnabled } from "./log.js"; import { debugWhen, isDebugEnabled } from "./log.js";
@ -26,10 +27,10 @@ import { transform } from "./transform.js";
import { finishReasonFrom, usageFromFinish, costFromFinishStep, costFromProviderMetadata, type FinishEvent, type FinishStepEvent, type ProviderMetadataEvent } from "./usage.js"; import { finishReasonFrom, usageFromFinish, costFromFinishStep, costFromProviderMetadata, type FinishEvent, type FinishStepEvent, type ProviderMetadataEvent } from "./usage.js";
// x-cmd-zdr breaks some models; off by default (server.py never sends it). // x-cmd-zdr breaks some models; off by default (server.py never sends it).
// Precedence: providerOptions.commandcode.zdr > x-cmd-zdr header > toggle file. // Precedence: providerOptions["commandcode-go"].zdr > x-cmd-zdr header > toggle file.
// "undefined" means the header is omitted entirely. // "undefined" means the header is omitted entirely.
function providerScoped(options: LanguageModelV3CallOptions): Record<string, unknown> | undefined { function providerScoped(options: LanguageModelV3CallOptions): Record<string, unknown> | undefined {
return options.providerOptions?.["commandcode"] as Record<string, unknown> | undefined; return options.providerOptions?.[PROVIDER_ID] as Record<string, unknown> | undefined;
} }
function truthyHeader(value: string): boolean { function truthyHeader(value: string): boolean {
@ -88,7 +89,7 @@ function resolve(options: CommandCodeOptions): ResolvedOptions {
const fromHeader = headerValue(headers, "authorization"); const fromHeader = headerValue(headers, "authorization");
const apiKey = options.apiKey ?? fromHeader?.replace(/^Bearer\s+/i, ""); const apiKey = options.apiKey ?? fromHeader?.replace(/^Bearer\s+/i, "");
return { return {
providerId: options.name ?? "commandcode", providerId: options.name ?? PROVIDER_ID,
apiKey, apiKey,
headers, headers,
baseURL: (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ""), baseURL: (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ""),
@ -592,7 +593,7 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
}; };
const hasCost = cost !== undefined || marketCost !== undefined; const hasCost = cost !== undefined || marketCost !== undefined;
if (hasCost) finalUsage.raw = { ...(finalUsage.raw ?? {}), ...reported }; if (hasCost) finalUsage.raw = { ...(finalUsage.raw ?? {}), ...reported };
const finishMetadata: SharedV3ProviderMetadata | undefined = hasCost ? { commandcode: reported } : undefined; const finishMetadata: SharedV3ProviderMetadata | undefined = hasCost ? { [this.opts.providerId]: reported } : undefined;
debugWhen(dbg, "stream", "terminal", `finish=${finishReason ? (finishReason.unified ?? "?") : "synthesized"}`, `usage=${JSON.stringify(finalUsage)}`, `providerMetadata=${JSON.stringify(finishMetadata ?? {})}`); debugWhen(dbg, "stream", "terminal", `finish=${finishReason ? (finishReason.unified ?? "?") : "synthesized"}`, `usage=${JSON.stringify(finalUsage)}`, `providerMetadata=${JSON.stringify(finishMetadata ?? {})}`);
yield { yield {
type: "finish", type: "finish",

View File

@ -4,7 +4,7 @@ import type {
LanguageModelV3ToolResultOutput, LanguageModelV3ToolResultOutput,
LanguageModelV3ToolResultPart, LanguageModelV3ToolResultPart,
} from "@ai-sdk/provider"; } from "@ai-sdk/provider";
import { DEFAULT_MAX_TOKENS, PASSTHROUGH_PARAMS, STATIC_CONFIG } from "./constants.js"; import { DEFAULT_MAX_TOKENS, PASSTHROUGH_PARAMS, PROVIDER_ID, STATIC_CONFIG } from "./constants.js";
type ContentPart = Record<string, unknown>; type ContentPart = Record<string, unknown>;
@ -152,7 +152,7 @@ function applyToolChoice(
} }
function reasoningEffort(options: LanguageModelV3CallOptions): unknown { function reasoningEffort(options: LanguageModelV3CallOptions): unknown {
const scoped = options.providerOptions?.["commandcode"] as Record<string, unknown> | undefined; const scoped = options.providerOptions?.[PROVIDER_ID] as Record<string, unknown> | undefined;
return scoped?.["reasoning_effort"] ?? scoped?.["reasoningEffort"]; return scoped?.["reasoning_effort"] ?? scoped?.["reasoningEffort"];
} }

View File

@ -20,6 +20,7 @@ import { join } from "node:path";
import { createSignal } from "solid-js"; import { createSignal } from "solid-js";
import { fetchQuota, formatQuota, formatReset, percent, quotaBar, type QuotaResult, type QuotaWindow } from "./quota.js"; import { fetchQuota, formatQuota, formatReset, percent, quotaBar, type QuotaResult, type QuotaWindow } from "./quota.js";
import { PROVIDER_ID } from "./constants.js";
import { redact } from "./redact.js"; import { redact } from "./redact.js";
import { debugEnabled, readToggles, toggle, type ToggleName, type Toggles } from "./toggles.js"; import { debugEnabled, readToggles, toggle, type ToggleName, type Toggles } from "./toggles.js";
@ -163,7 +164,7 @@ function resolveRef(value: unknown): string | undefined {
function commandCodeOptions(api: TuiApi): Record<string, unknown> | undefined { function commandCodeOptions(api: TuiApi): Record<string, unknown> | undefined {
try { try {
return api.state?.config?.provider?.["commandcode"]?.options; return api.state?.config?.provider?.[PROVIDER_ID]?.options;
} catch { } catch {
return undefined; return undefined;
} }
@ -182,7 +183,7 @@ function providersOf(api: TuiApi): TuiProvider[] {
} }
function resolveApiKeySource(api: TuiApi): { key?: string; source: string } { function resolveApiKeySource(api: TuiApi): { key?: string; source: string } {
const provider = providersOf(api).find((entry) => entry?.id === "commandcode"); const provider = providersOf(api).find((entry) => entry?.id === PROVIDER_ID);
const options = commandCodeOptions(api); const options = commandCodeOptions(api);
const headers = options?.["headers"] as Record<string, unknown> | undefined; const headers = options?.["headers"] as Record<string, unknown> | undefined;
const named: Array<[string, unknown]> = [ const named: Array<[string, unknown]> = [
@ -589,7 +590,7 @@ export const tui = async (api: TuiApi): Promise<void> => {
if (!apiKey) { if (!apiKey) {
api.ui.toast({ api.ui.toast({
title: CATEGORY, title: CATEGORY,
message: "No API key found. Set provider.commandcode.options.apiKey or COMMANDCODE_API_KEY.", message: `No API key found. Set provider.${PROVIDER_ID}.options.apiKey or COMMANDCODE_API_KEY.`,
variant: "warning", variant: "warning",
}); });
return; return;