opencode-ccgo-provider/README.md

27 KiB
Raw Blame History

opencode-commandcode-provider

A native AI SDK provider that connects opencode 2 to the CommandCode /alpha/generate API.

This package implements the LanguageModelV3 interface directly, so opencode talks to CommandCode with no local proxy in the middle. opencode loads it through its aisdk: bridge, which imports the package, picks up the create* factory, and wraps the V3 model in its native route system.

opencode 2  ──►  aisdk: bridge (LanguageModelV3)
                      │
                      ▼
            opencode-commandcode-provider
              transform → POST /alpha/generate
              NDJSON events → V3 stream parts
                      │
                      ▼
               api.commandcode.ai

Requirements

  • Node.js >= 18 (uses global fetch, ReadableStream, TextDecoder, structuredClone).
  • opencode 2 (verified against 2.2.5, which still ships @ai-sdk/provider@3.0.8).
  • A CommandCode account and API key with access to the /alpha/generate endpoint.

Install and wire into opencode

The provider is consumed directly from its build output via an aisdk:file:// spec. This bypasses npm install and is the intended development workflow.

# 1. build the provider
npm install
npm run build
// 2. ~/.config/opencode/opencode.json  (or a project opencode.json)
{
  "$schema": "https://opencode.ai/config.json",
  "disabled_providers": ["commandcode"],
  "providers": {
    "commandcode-go": {
      "name": "Command Code",
      "package": "aisdk:file:///C:/dev/opencode-commandcode-provider/dist/index.js",
      "settings": {
        "apiKey": "{env:COMMANDCODE_API_KEY}"
      },
      "models": {
        "deepseek/deepseek-v4.1-flash": {
          "name": "DeepSeek V4.1 Flash",
          "limit": { "context": 1048576, "output": 256000 },
          "capabilities": { "tools": true, "input": ["text", "image"], "output": ["text"] }
        }
      }
    }
  }
}

The aisdk: prefix is required. A bare file:// package is loaded as an opencode 2 native provider and must export model(modelID, settings); this package exports the AI SDK create* factory instead, which only the aisdk: bridge understands.

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 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 (the field is still accepted and normalized into policies in opencode 2).

Then set the key and restart opencode:

$env:COMMANDCODE_API_KEY = "user_..."
opencode models commandcode-go

opencode loads configuration once at startup. After changing opencode.json or cli.json, quit and relaunch opencode for the change to take effect. A rebuilt provider is re-imported the same way.

The models map is required — opencode silently drops a custom provider whose model list is empty. The provider itself only needs languageModel(id), which it implements for any id passed to it, but opencode builds /models and the TUI picker from this map and never asks a custom aisdk:file:// provider to discover models. Use the sync script below to fill it in.

Listing all CommandCode models

opencode reads the model list from providers.commandcode-go.models; a custom provider cannot 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). Only the selected models are vision-probed and written into your global opencode config — deselected ids are removed from it.

npm run build            # the script imports the compiled provider
npm run sync-models      # fetch catalog, pick models, probe vision, write ~/.config/opencode/opencode.json

Keys: ↑/↓ move (one model per step), space toggles, Ctrl-A selects all, Ctrl-U clears, typing filters, Esc clears the filter (empty filter aborts), enter confirms, Ctrl-C aborts without writing. Each row shows the model id and name plus a second line with its context window (ctx 1M (1000000)); the catalog carries no pricing fields, so no cost is shown. Needs an interactive terminal.

Before anything else the script requires a CommandCode API key (from providers.commandcode-go.settings.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 (https://commandcode.ai/studio/provider) to generate one. It never writes without a key.

Then restart opencode and confirm:

opencode models commandcode-go

Mapping and behaviour (opencode 2 native shape):

  • Every catalog entry gets limit.context from its context_length, limit.output from DEFAULT_MAX_TOKENS, and capabilities.tools: true.
  • Vision (capabilities.input with image) is probed per model: a 64×64 image is sent and the reply is inspected. Models that answer a color are marked vision; models that reply NO_IMAGE (retried once) or reject the image are not. Probes that cannot run — plan-gated, temporarily unavailable — fall back to a family heuristic (claude, gpt-5, gemini, grok, qwen…vl, …). Probing is best-effort: upstream is nondeterministic and a re-run may flip a borderline model.
  • Reasoning effort (variants) is probed per model: a tiny request is sent for each candidate tier (low, medium, high, xhigh, max) carrying reasoningEffort, and a tier counts as supported when the request completes (an unsupported tier fails the request, which is the signal). Verified tiers are written as opencode 2 variants — [{ "id": "high", "settings": { "reasoningEffort": "high" } }] — so the #high model suffix and /variants switcher work. If every tier is rejected, a no-effort baseline probe decides: a reachable model gets no variants at all; an unreachable or plan-gated model falls back to a static guess (low/medium/high, plus max for deepseek-v4). Probing is skipped for ids that already carry user-defined variants — those are preserved as-is.
  • Generated fields (name, limit, capabilities) overwrite existing values. variants are written only when the entry has none; other fields (settings, cost, …) on selected ids are preserved. Unselected ids are removed from the map.

The API key is read from COMMANDCODE_API_KEY, then providers.commandcode-go.settings.apiKey in the global config (baseURL/ccVersion are read from there too; the pre-2 provider.<id>.options shape is still accepted when reading).

Configuration options

providers.commandcode-go.settings is forwarded to createCommandCode(options). Per-model and per-variant settings merge over it (provider ← model ← variant).

Setting Type Default Description
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.
baseURL string https://api.commandcode.ai Upstream origin. Trailing slashes are stripped.
ccVersion string 1.84.0 Value of the x-command-code-version header.
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.
reasoningEffort string — Provider-level default reasoning effort, sent as params.reasoning_effort (reasoning_effort is an accepted alias). Model/variant settings override it — see Reasoning effort.
name string commandcode-go Provider id reported to the AI SDK. opencode sets this automatically.

opencode's own provider fields (headers, body) are separate overlays in opencode 2 and reach the factory merged in. Timeouts (timeout, headerTimeout, chunkTimeout) and encoding are read by opencode itself and are not forwarded to the provider.

Auth precedence: settings.apiKey wins; otherwise the value of an Authorization header in the provider's headers overlay (with a leading Bearer stripped). If neither is present, requests are sent unauthenticated and CommandCode will reject them.

Environment variables

All environment variables read by the provider, its scripts, and its TUI plugin. String values in settings also accept {env:NAME}, which opencode/the TUI expand generically (not a fixed set).

CommandCode-specific:

Name Purpose Default
COMMANDCODE_API_KEY CommandCode API key for smoke/quota/sync-models and the TUI's key resolution; referenced from config as {env:COMMANDCODE_API_KEY}. —
COMMANDCODE_TOGGLES_FILE Overrides the shared toggle-file path. $XDG_CONFIG_HOME/opencode/commandcode-toggles.json
COMMANDCODE_QUOTA_INTERVAL_MS Sidebar fallback quota refresh interval in ms. 300000 (floor 120000)

Standard:

Name Purpose Default
XDG_CONFIG_HOME Base config dir for the toggle file. ~/.config
NO_COLOR Disables ANSI colors in the sync-models picker (any value). unset
TERM dumb disables ANSI colors in the sync-models picker. —

Debug tracing

Flip the debug key in the shared toggle file (via /cc-debug) to write a trace of every request and stream event to a log file. Silent (and no file is created) unless enabled; the log path is <os tempdir>/commandcode-debug.log. Every line is passed through redact() so credentials never reach disk.

The log captures the request (model id, body byte length), each HTTP attempt (status, retry wait, elapsed ms), every stream event payload, and the terminal finish reason + usage. It is useful for diagnosing model selection, retry, tool-call, and finish-reason issues.

ZDR header toggle

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 providerOptions.commandcode-go.zdr. The value is resolved per request, so toggling it does not require restarting opencode.

Precedence, highest first:

  1. providerOptions.commandcode-go.zdr (true/false), e.g. a model variant or agent option.
  2. An explicit x-cmd-zdr header in the provider's headers overlay or the call's headers.
  3. The toggle file (zdr key — see Runtime toggles).

With tracing enabled, the trace logs a zdr on|off line per request so the toggle state is observable.

Runtime toggles

/cc-zdr and /cc-debug flip the zdr and debug values in a small JSON file the provider reads on every request, so both settings change without restarting opencode. /cc-status shows the current state. The file is ~/.config/opencode/commandcode-toggles.json (overridable with COMMANDCODE_TOGGLES_FILE — see Environment variables).

These commands come from a small TUI plugin shipped in this package (plugin/tui.tsx). It is an opencode 2 TUI-only plugin (Plugin.define from @opencode/plugin/tui), loaded from source — opencode compiles the TSX and provides the Solid runtime itself — so there is no build step and no runtime dependency for it. Register it once by adding the plugin directory to the plugins list in the terminal client config, ~/.config/opencode/cli.json:

// ~/.config/opencode/cli.json
{
  "plugins": ["file:///C:/dev/opencode-commandcode-provider/plugin"]
}

Use an absolute path with forward slashes (file:///C:/... on Windows, file:///home/... on Linux/macOS); a plain absolute path works too. The directory uses opencode 2's file-name convention (no package.json inside): plugin/tui.tsx is the TUI part, and there is no server part. A TUI-only package belongs in cli.json, not in opencode.json plugins.

Restart opencode after registering the plugin; then type /cc- for autocomplete. The plugin also renders a CommandCode panel in the session sidebar (sidebar.content slot): zdr / debug, combined main + sub-agent token totals (in / out / cache hit, plus $ spent when the session reports cost), and live quota. The slash commands and the Ctrl+P palette share one registry, so these entries appear in both. If you run opencode against a remote server, register the plugin in the terminal's own cli.json; the provider-side toggle file must live on the server host — use the env vars or providerOptions there.

Sub-agent tokens are included in the same totals: task-tool subagents run in child sessions, so their usage is not in the current session's store. The panel reads opencode's reactive family index (data.session.family) and sums each descendant session's aggregate tokens (bounded to 50 sessions), adding them to the combined in / out / hit. The parenthetical delta in in and out is sub-agent usage alone; it is omitted when no descendant sessions were found.

Quota tracking

/cc-usage and the sidebar show CommandCode's 5-hour, weekly and monthly usage for the account behind providers.commandcode-go.settings.apiKey. The numbers come live from the same alpha billing endpoints the cmd CLI /usage command uses:

Endpoint Used for
GET /alpha/whoami account identity and org id
GET /alpha/billing/credits 5-hour/weekly windows (used, cap, resetAt) and credit balances
GET /alpha/billing/subscriptions plan id, status, billing period
GET /alpha/usage/summary requests/tokens/cost for the current billing period

The 5-hour and weekly windows show used / cap and a live reset countdown. The monthly meter is derived: usage/summary cost vs. that cost plus all remaining credits, so it works on any plan (including org and pay-as-you-go) without a maintained price table. Free and pay-as-you-go accounts can return no windowLimits; those rows stay hidden and the missing section is reported instead of being shown as zero.

The sidebar refreshes after each completed turn (session.usage.updated, session.execution.succeeded, session.execution.failed, session.idle and session.status — all debounced) and when the active session changes, but never more than once every 2 minutes; every 5 minutes as a fallback (COMMANDCODE_QUOTA_INTERVAL_MS overrides the fallback interval — see Environment variables) and the countdown ticks every 30 seconds. Token totals and the spent line read opencode's reactive session store, so they update live without polling. Key resolution and fetch failures are redacted and shown inline; the panel never stays on loading… and never blocks the provider. Extra trace lines (tui-quota) are appended to the debug log only when debug tracing is on.

Headless check (no TUI), reading the key from COMMANDCODE_API_KEY or the opencode config:

npm run build
npm run quota            # formatted
npm run quota -- --json  # raw quota object

The API key is never logged; quota errors pass through redact() like every other surface.

Features

Capability Status
Streaming (doStream) Yes — CommandCode is always streamed upstream, then re-emitted as V3 stream parts
Non-streaming (doGenerate) Yes — buffers the stream internally
Text deltas Yes
Reasoning deltas Yes — emitted as reasoning-start / reasoning-delta / reasoning-end
Reasoning replay Yes — assistant reasoning parts are sent back as {type:"reasoning"} content parts (required by DeepSeek thinking mode when tools are present); signature is forwarded when present
Tool calls Yes — tool-input-start / tool-input-delta / tool-input-end / tool-call
Tool results Yes — paired results are replayed; unpaired ids are dropped
Multiple images (vision) Yes — data: URIs, raw base64, Uint8Array, and remote URLs
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-go.cost (plus marketCost); also stashed in usage.raw. opencode 2 records provider-reported session costs, and the sidebar shows the recorded session spent line when it is non-zero
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
reasoning_effort Yes — provider default via settings.reasoningEffort; per request via variant settings or providerOptions.commandcode-go.reasoningEffort; switchable per message through #variant / /variants (variants generated by sync-models)
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
Runtime toggles Yes — /cc-zdr and /cc-debug flip the shared toggle file without a restart
Sidebar status panel Yes — a sidebar.content panel shows zdr/debug, combined main + sub-agent token totals (in/out with a sub-agent-only delta, plus cache hit and $ spent), and live quota
Quota tracking Yes — 5-hour/weekly/monthly meters via /cc-usage, the sidebar, and npm run quota

tool_choice handling

CommandCode accepts exactly one upstream value, {"type":"auto"}. The provider maps the AI SDK values accordingly:

  • auto — forwarded as {"type":"auto"}.
  • none — emulated by sending no tools at all.
  • { type: "tool", toolName } — emulated by sending only that tool.
  • required — not expressible upstream; tools are sent and the model decides.

Reasoning effort

The effort reaches CommandCode as params.reasoning_effort. Config layers, most specific wins:

Layer opencode.json location Notes
Selected variant providers.<id>.models.<model>.variants[] entry Switched per message via #variant refs, /variants, or opencode run --model commandcode-go/<model>#high — no restart needed
Model default providers.<id>.models.<model>.settings.reasoningEffort Every request for that model
Provider default providers.<id>.settings.reasoningEffort Fallback when nothing more specific is set
// opencode.json
{
  "providers": {
    "commandcode-go": {
      "settings": { "reasoningEffort": "medium" },
      "models": {
        "deepseek/deepseek-v4.1-flash": {
          "settings": { "reasoningEffort": "low" },
          "variants": [
            { "id": "low", "settings": { "reasoningEffort": "low" } },
            { "id": "high", "settings": { "reasoningEffort": "high" } }
          ]
        }
      }
    }
  }
}

Notes:

  • reasoning_effort is accepted as a key alias at every layer (request options and the provider default).
  • Variant settings (and model/provider settings) are merged into the options the aisdk: bridge passes to createCommandCode; the selected variant wins because opencode instantiates the SDK per merged settings.
  • Request-level providerOptions.commandcode-go.reasoningEffort still overrides everything — opencode keys request options by the provider id for custom aisdk: packages.
  • Values are forwarded unvalidated: an effort the upstream model does not support fails the request. Run npm run sync-models to probe which tiers each model actually accepts and write the verified ones as variants.
  • Variants must exist in config for /variants to appear — opencode ships no built-in variants for custom aisdk: providers, and a custom provider cannot register variants itself (see Listing all CommandCode models).
  • Config edits need a restart; selecting a different variant does not (it is resolved per message). With /cc-debug enabled, each request logs an effort=<value|default> line.

How it works

dist/index.js      Built entrypoint opencode imports (create* factory, LanguageModelV3).
src/index.ts      Public exports: createCommandCode + default.
src/model.ts      CommandCodeLanguageModel (LanguageModelV3): HTTP, retries, stream/generate.
src/transform.ts  LanguageModelV3CallOptions -> /alpha/generate envelope (JSON string).
src/events.ts     NDJSON/SSE line iterator over the upstream response body.
src/usage.ts      finish event -> V3 usage; finish-reason unification.
src/redact.ts     Credential scrubbing for error surfaces.
src/log.ts        Opt-in tracing (toggle file) to a log file.
src/toggles.ts    Shared toggle file read by the provider and written by the TUI plugin.
src/quota.ts      Live 5-hour/weekly/monthly quota from the alpha billing endpoints.
src/constants.ts  Defaults, header names, static config block.
plugin/tui.tsx    opencode 2 TUI plugin: /cc-zdr, /cc-debug, /cc-status, /cc-usage + sidebar panel.
scripts/smoke.mjs Live end-to-end check against api.commandcode.ai.
scripts/quota.mjs Print the live quota headlessly.
scripts/sync-models.mjs Pick models interactively and write providers.commandcode-go.models.
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.

Request lifecycle

  1. opencode's aisdk: bridge imports dist/index.js, calls createCommandCode({ name, ...settings }), then sdk.languageModel(id) and model.doStream(options).
  2. transform() converts the AI SDK prompt into the CommandCode envelope:
    • system text is joined into params.system.
    • user/assistant/tool messages become params.messages content parts.
    • assistant tool-call parts and tool results are only included when their ids are paired; unmatched ids (common after history truncation) are dropped because upstream rejects them.
    • image file parts become { type: "image", image, mimeType }.
    • function tools become { type: "function", name, description, input_schema }.
    • stream is forced to true — the endpoint answers stream:false with "Proxy use detected. This endpoint only serves CLI."
  3. model.ts POSTs the envelope with the CommandCode headers and retries 429/5xx.
  4. events.ts parses the NDJSON body (tolerating data: prefixes and [DONE]).
  5. model.ts maps each upstream event to a LanguageModelV3StreamPart and always terminates with a finish part.
  6. doGenerate drains the same stream and assembles a LanguageModelV3GenerateResult.

Development

npm install        # installs typescript, @types/node, @ai-sdk/provider, @opencode/plugin, solid-js
npm run typecheck  # tsc --noEmit (provider) + tsc -p tsconfig.tui.json (TUI plugin)
npm run build      # tsc -> dist/ (provider only; the TUI plugin loads from source)
npm run smoke      # live request against CommandCode
npm run quota      # live 5-hour/weekly/monthly quota
npm run sync-models # regenerate providers.commandcode-go.models from the catalog

@opencode/plugin, solid-js, @opencode/theme, and @opentui/* are type-only dev dependencies for plugin/tui.tsx; opencode resolves those imports from its own runtime when it loads the plugin, so the built provider keeps zero runtime dependencies.

scripts/smoke.mjs reads the key from COMMANDCODE_API_KEY, falling back to providers.commandcode-go.settings.apiKey in ~/.config/opencode/opencode.json. It exercises both doGenerate and doStream and prints content, finish reason, and usage.

To smoke-test a specific model:

node scripts/smoke.mjs deepseek/deepseek-v4.1-flash

Verifying inside opencode

opencode models commandcode-go
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-go/deepseek/deepseek-v4.1-flash
opencode run "Reply with exactly: pong" -m commandcode-go/deepseek/deepseek-v4.1-flash#high

Troubleshooting

Symptom Likely cause / fix
Provider not found: commandcode-go Provider was dropped because models is empty, or the package path is wrong. Confirm dist/index.js exists (npm run build) and that the aisdk:file:// path is absolute.
Provider package … does not export model(modelID, settings) The aisdk: prefix is missing from package. A bare file:// spec is loaded as a native opencode 2 provider and needs a different export shape.
Models appear but every call fails auth settings.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.
Images are ignored by the model The selected model is not vision-capable. Set capabilities.input: ["text","image"] in models, and pick a vision model id.
Upstream 400 about tool calls A tool-call or tool-result without a matching pair slipped through. Pairing is enforced in src/transform.ts; report a repro if it still occurs.
Need to see what the provider sends/receives Flip /cc-debug and read the appended log file (see Debug tracing).
tool_choice seemingly ignored Expected for required; upstream cannot force a call. none and named-tool are emulated via the tool list.
Config change had no effect opencode reads config once at startup. Restart it.
/variants missing or only shows "Default" The model has no variants in config. Run npm run sync-models (probes tiers live) or add variants manually, then restart opencode.
Reasoning-effort change has no effect Check the selected variant and the config key spelling (reasoningEffort), then look for the effort= line in the debug log. Config edits need a restart; variant switches do not. An effort the upstream model rejects fails the request by design.
/cc-* commands and the sidebar panel are missing TUI plugin not registered: add the plugin/ directory to plugins in ~/.config/opencode/cli.json (see Runtime toggles). A bare .tsx file path or the repo root (whose package.json exports the provider as .) does not load as a TUI-only plugin.
Config warnings about attachment/modalities/reasoning fields Those are pre-2 model fields that opencode 2 ignores. Rewrite model entries with capabilities (the sync script writes the native shape).

Security

  • Prefer {env:COMMANDCODE_API_KEY} (or opencode's /connect credential store) over an inline key in opencode.json.
  • Upstream error bodies can echo credentials. src/redact.ts scrubs Bearer tokens, user_/cc_ keys, sk-…-style keys, JWTs, and key=value secrets from any error surfaced to the client. Do not add logging of raw request/response bodies without passing them through redact().
  • Never commit real keys. dist/, node_modules/, dump/, and *.log are gitignored.