19 KiB
AGENTS.md
Instructions for LLM coding agents working in this repository.
Project overview
opencode-commandcode-provider is a native AI SDK provider that connects opencode 2 to the
CommandCode /alpha/generate API. It implements LanguageModelV3 from @ai-sdk/provider@3.0.8
and is loaded by opencode 2 from dist/index.js through its aisdk: bridge (config
package: "aisdk:file://…/dist/index.js"): opencode imports the file, picks the first create*
export, calls it with { name: providerID, ...settings, headers, body, fetch }, and then calls
sdk.languageModel(id). The same @ai-sdk/provider version ships inside opencode 2, so the V3
implementation is shared verbatim.
- Language/tooling: TypeScript, ESM,
tsc. - Runtime target: opencode 2's
aisdk:provider bridge,@ai-sdk/provider@3.0.8(V3 specification). - No runtime dependencies.
@ai-sdk/provider,@opencode/plugin,solid-js,@opencode/theme, and@opentui/*are type-only dev dependencies; opencode resolves the plugin's imports from its own runtime at load, and the built output has no imports of its own.
Commands
Run from the repository root.
npm install # dev deps: typescript, @types/node, @ai-sdk/provider, @opencode/plugin, solid-js, @opencode/theme, @opentui/*
npm run typecheck # tsc --noEmit (provider) + tsc -p tsconfig.tui.json (TUI plugin)
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 quota # live 5-hour/weekly/monthly quota (needs a key)
npm run sync-models # regenerate providers.commandcode-go.models (models + reasoning-effort variants)
There is no unit-test suite. scripts/smoke.mjs is the end-to-end check. scripts/sync-models.mjs
is the interactive model picker (needs dist/ first; needs a TTY; writes the global opencode config).
After any change under src/ or plugin/, run npm run typecheck, then npm run build, then
npm run smoke. A change is not done until it typechecks and the smoke test passes.
Layout
src/index.ts Public exports: createCommandCode (named) and default.
src/model.ts CommandCodeLanguageModel: HTTP, retries, doStream/doGenerate, event->part mapping.
src/transform.ts LanguageModelV3CallOptions -> /alpha/generate envelope (returns a JSON string).
src/events.ts Async iterator over the NDJSON/SSE response body.
src/usage.ts finish event -> LanguageModelV3Usage; 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 (~/.config/opencode/commandcode-toggles.json).
src/quota.ts Live 5-hour/weekly/monthly quota from the CommandCode alpha billing API.
src/constants.ts Defaults, paths, headers, static config block.
plugin/tui.tsx opencode 2 TUI plugin: /cc-zdr, /cc-debug, /cc-status, /cc-usage + sidebar.
tsconfig.tui.json Typechecks plugin/tui.tsx (+ quota/toggles/log/redact/constants) with
jsxImportSource @opentui/solid (no build step for the plugin).
scripts/smoke.mjs Live end-to-end check.
scripts/quota.mjs Print the live quota headlessly (reads the same config as smoke).
scripts/sync-models.mjs Catalog -> providers.commandcode-go.models generator (vision + effort probing).
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.
Architecture / data flow
opencode 2 (aisdk: bridge)
└─ createCommandCode({name, ...settings}).languageModel(id).doStream(options)
├─ transform(options, id) ──► JSON envelope
├─ fetch POST {baseURL}/alpha/generate (retry 429/5xx)
├─ iterateEvents(response.body) (NDJSON lines)
└─ map each event ──► LanguageModelV3StreamPart*
... always ending with a `finish` part
doGenerate calls doStream and drains the resulting stream into a
LanguageModelV3GenerateResult.
Conventions
- ESM only. Imports of local files must end in
.js(NodeNext resolution), e.g.import { transform } from "./transform.js";. The TUI plugin imports shared modules as../src/*.js— opencode's Bun transform resolves those to the TS sources. strictTypeScript is on, includingnoUncheckedIndexedAccessandverbatimModuleSyntax. Type-only imports must useimport type.- Do not add comments unless they explain a non-obvious decision. Existing comments document upstream quirks and are intentional; match that spirit, not volume.
- Keep the
transform.tsenvelope stable. If you change it, document the upstream behavior that motivated the change. - Preserve the single public factory
createCommandCode.index.tsre-exports it as both a named and the default export; theaisdk:bridge picks the first export whose name starts withcreate, so nothing else indist/index.jsmay export such a name. - The package must stay runtime-dependency-free. Do not add a runtime
importof a package that would neednode_modulesat load time; opencode importsdist/index.jsandplugin/tui.tsxdirectly and resolves their third-party imports itself.
Invariants and gotchas
These are load-bearing. Breaking one causes silent failures in opencode.
- Exactly one
create*export reachable from the entrypoint. opencode 2'sopencode.provider.dynamicplugin loads anaisdk:package, chooses the first export whose name starts withcreate, and calls it asfn({ name: providerID, ...settings, headers, body, fetch }). The result must exposelanguageModel(id). A barefile://package instead needs a nativemodel(modelID, settings)export — never switch to that shape here. params.streamis alwaystrue. Sendingstream: falsemakes upstream answer "Proxy use detected. This endpoint only serves CLI." Non-streaming clients are served by buffering the V3 stream indoGenerate.tool-callstream parts carryinputas a stringified JSON string, not an object (LanguageModelV3ToolCall.input: string). Serialize withJSON.stringify. Passing an object breaks opencode's tool execution with errors likeK.input.trim is not a function.- Always emit a terminal
finishpart. If upstream ends without afinishevent, synthesize one from the accumulated state. A missing finish surfaces as a truncated-response error. - Drop unpaired tool ids. Any
tool-callwithout a matchingtool-result(or vice versa) must be omitted from the envelope; upstream rejects the whole request otherwise. - Usage is nested in V3. Fill
inputTokens.{total,noCache,cacheRead,cacheWrite}andoutputTokens.{total,text,reasoning}— not flatpromptTokens/completionTokens.inputTokens.totalis input-only;totalTokensis input+output. opencode 2 folds these into itsTokenUsage(inputnon-cached +cache.read/cache.write,reasoninginside output) and sums per-step deltas intoSessionInfo.tokens. supportedUrlsis{}and stays empty. CommandCode URLs are not fetched by the SDK.- Redact before surfacing errors. Any upstream error text passed to the client must go through
redact(). - Replay assistant reasoning as a
{type:"reasoning"}content part. DeepSeek thinking mode rejects any request carryingtoolswhose prior assistant turns omit their reasoning. Intransform.ts, forward each assistantreasoningpart as{type:"reasoning", text, signature?}; do not drop it and do not fabricate empty reasoning. - Upstream cost never appears on
finish. Per-request USD arrives onfinish-step(usage.raw.cost/market_cost/gateway_cost, numbers) andprovider-metadata(providerMetadata.gateway.cost/marketCost, strings).finish.totalUsagecarries tokens only. Capture both intoproviderMetadatakeyed by the resolved provider id (options.name;commandcode-go— opencode 2 passescanonical ?? providerIDasname, and a config provider has no canonical unless one is configured) on the terminal V3finishpart (anddoGenerateresult), and stash intousage.raw. A reported0is meaningful; onlyundefinedmeans absent. opencode 2 records provider-reported session costs (session.usage.updated→SessionInfo.cost), and the sidebar shows aspentline fromdata.session.cost(sessionID);/cc-usageremains the CommandCode dollar source. aisdk:file://specs bypass install. opencode 2 imports the file directly (itsloadSDKFactoryspecial-casesfile://), so the repo must be rebuilt for opencode to see source changes. Theaisdk:prefix is required — a barefile://provider package must export the nativemodel(modelID, settings), which this package deliberately does not. The background service keeps the previously imported module alive, so after rebuilding runopencode service restart(or verify withopencode run --standalone) or the old code serves every request./modelsis config-driven, not provider-driven. opencode 2 builds the model list fromproviders.commandcode-go.modelsinopencode.jsonand never asks a customaisdk:provider to discover models. Refresh the map withnpm run sync-models; do not expect a discovery hook insrc/to populate it. Model entries use the opencode 2 shape:name,limit,capabilities.{tools,input,output},variantsas an array of{ id, settings }. The pre-2 model fields (reasoning,attachment,modalities) are accepted but ignored with a warning.- The TUI plugin is an opencode 2 TUI-only plugin directory.
plugin/tui.tsxis loaded from source (notdist/) by registering the directory in the terminal client config~/.config/opencode/cli.json:{ "plugins": ["file:///abs/path/plugin"] }(a plain absolute path also works). The directory uses opencode 2's file-name convention and intentionally has nopackage.json:tui.tsxat its root is the TUI part and there is no server part. Do not register the repo root — itspackage.jsonhasname+exports, so opencode would load.(dist/index.js, the provider) as a server plugin. TUI-only packages belong incli.json, not inopencode.jsonplugins. opencode compiles the.tsxwith its Bun/Solid transform (@opentui/solidruntime support) and mapssolid-jsand@opencode/plugin/tuito its internal modules. Verified on opencode 2.2.5: the module default-exportsPlugin.define({ id, setup(context) })from@opencode/plugin/tui;setupregisters everything and returns a cleanup function (there is nolifecycle.onDispose). Commands register viacontext.keymap.layer(() => ({ mode: "global", commands: [...] }))with{ id, title, description, group, palette: true, slash: { name }, run }. The sidebar panel registers viacontext.ui.slot({ append: "sidebar.content", render }); the slot render receives{ sessionID }reactively and relies oncontext.theme(tokens:theme.text.base,theme.text.muted,theme.text.feedback.{error,warning,success}.base). Solid reactivity gotcha: read signals and store getters inside the returned JSX/memos, never hoist a.valueread into a plainconstabove thereturn— a hoisted read subscribes once under a non-tracking owner and the panel freezes after first paint. Session token accounting:context.data.session.get(sessionID).tokensis the server-summed per-step deltas (inputnon-cached,outputincludesreasoning; total prompt = input+cache.read+cache.write) andcontext.data.session.family(sessionID)lists descendant sub-agent sessions — sum each member'sget(id).tokens(bounded), never the parent's list.context.data.session.cost(id)is the recorded session cost. - Slash commands and
Ctrl+Pshare one registry. A V2 keymap command with bothpalette: trueandslash: { name }appears in both menus; there is no slash-only entry. Do not addbindto these commands — they are meant to be invoked, not keybound. - Toggles are resolved per request, never at load.
zdranddebugare read inmodel.ts/log.tson every call from the toggle file, so/cc-*changes take effect without restarting opencode. Precedence forzdr:providerOptions.commandcode-go.zdr>x-cmd-zdrheader > toggle file. Do not reintroduce load-time consts. - Quota is live from the alpha billing API.
src/quota.tsreads/alpha/whoami,/alpha/billing/credits,/alpha/billing/subscriptions, and/alpha/usage/summary(the same endpoints thecmdCLI/usageuses).resetAthas shipped as both seconds and epoch ms — normalize (>= 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 fromcontext.data.location.provider.list()(thecommandcode-goentry'ssettings.apiKey, then itsheaders.Authorization), then the globalopencode.json(providers.<id>.settings, then the pre-2provider.<id>.options), thenCOMMANDCODE_API_KEY, expanding{env:VAR}itself, and must never log the key — quota errors go throughredact(). The provider collection is not synced by the host: callcontext.data.location.provider.sync(location)once before reading it, or the list is empty. - Retryable upstream failures can arrive inside an HTTP 200 stream. CommandCode's gateway
answers
200and then emits an SSEerrorevent carryingstatusCode/isRetryable(e.g.{"type":"server_error","message":"Invalid error response format: Gateway request failed", "statusCode":520,"isRetryable":true}).fetchWithRetrybuffers only thestart/start-steppreamble and, if the first real event is such a retryable error and attempts remain, cancels the 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) surface immediately. Keep the preamble set in sync if upstream adds new pre-content events. - The provider id is
commandcode-go(PROVIDER_IDinconstants.ts) and must never becommandcode. opencode 2 still ships a models.dev catalog entry forcommandcode(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 endpoint from the catalog entry, so acommandcode-id provider posts to/provider/v1/alpha/generateand gets404 not a registered API route.commandcode-gois absent from the catalog (unlikecommandcodeandopencode-go), so it is safe. The official catalog provider is neutralized with"disabled_providers": ["commandcode"](opencode 2 normalizes it into deny policies); the filter applies to the final merged provider map, so it would also kill a config provider sharing the id — never re-register undercommandcode.PROVIDER_IDlives insrc/constants.ts; scripts import it fromdist/constants.js;providerOptionsis read only undercommandcode-go. - Reasoning effort: settings beat the provider default; request options beat both. opencode 2
merges
providers.<id>.settings←models.<id>.settings← the selected variant'ssettingsand passes the result into thecreateCommandCodefactory call (theaisdk:bridge spreads the merged settings into the factory options and caches one SDK instance per merged settings key).transform.tsreads bothreasoningEffortandreasoning_effort(resolveReasoningEffort) from the factory options and forwardsparams.reasoning_effortunvalidated — an effort the upstream model does not support fails the whole request, which is intentional and also the signalsync-modelsprobes with. Request-levelproviderOptions.commandcode-go.reasoningEffort(opencode keys request options by the provider id for customaisdk:packages) still overrides the settings chain. The resolved value is logged aseffort=in the debug trace. - Variants are config-only. opencode 2's variant switcher lists what
providers.commandcode-go.models.<id>.variantscontains; customaisdk:providers are only ever asked forlanguageModel(id), so there is no provider-side variant registration hook. V2 spells variants as an array:[{ "id": "high", "settings": { "reasoningEffort": "high" } }], selected ascommandcode-go/<model>#high.scripts/sync-models.mjsprobeslow/medium/high/xhigh/maxper model (tier accepted = tiny request completes) and writes the verified tiers, never overwriting user-defined variants; unreachable models get a static fallback set, reachable-but-effort-less models get none. - Never emit a second
tool-input-startfor one id. CommandCode streams a tool call astool-input-start→ deltas →tool-input-end, then a completetool-callwith the same id. opencode 2's session runner dies withDuplicate tool input start: <id>when a V3 stream opens the same tool id twice (opencode 1.x tolerated the duplicate, which is whystreamPartstracksstartedTools). A baretool-callwithout a preamble still gets a synthetictool-input-start.
Change workflow
- Identify the upstream behavior and the
src/(orplugin/) module that implements it. - Make the smallest change in the matching file.
npm run typecheck— fix all errors.npm run build.npm run smoke— verify text and, when relevant, tool calls.- If the change affects the opencode integration, verify with
opencode run(see below). - Update
README.mdif options, features, or behavior changed. KeepAGENTS.mdinvariants current if you discover a new one.
Do not edit dist/ by hand; it is generated.
Verification
Automated:
npm run typecheck; npm run build; npm run smoke
Quota changes additionally need a live check (needs a key):
npm run quota
Inside opencode 2 (restart it first if config changed):
opencode models commandcode-go
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-go/deepseek/deepseek-v4-flash-vision-exp
opencode run "Reply with exactly: pong" -m commandcode-go/deepseek/deepseek-v4-flash-vision-exp#high
The third command confirms the full tool-call round trip (tool-call emitted, executed, result
replayed). Run it after touching transform.ts or the tool-call mapping in model.ts. The last
one confirms variant settings reach the factory. For the TUI plugin, launch the opencode TUI and
check the sidebar panel plus /cc-status and /cc-usage.
Do / Don't
- Do keep the wire envelope stable; document intentional changes.
- Do run typecheck, build, and smoke after every source change.
- Do prefer
{env:COMMANDCODE_API_KEY}in docs and examples. - Don't commit real API keys,
dist/,node_modules/,dump/, or logs (all gitignored). - Don't add runtime dependencies or make
distrequirenode_modules. - Don't force
stream:false, send objecttool-call.input, or omit thefinishpart. - Don't register the repo root as a plugin, add a
package.jsontoplugin/, or load the TUI plugin fromopencode.jsonplugins. - Don't commit unless the user explicitly asks.