Compare commits

..

No commits in common. "a8a337e7b3223a1b8f260b822ad2db788fcd4b68" and "e63be86ba59da66983ed361b36e938d618925191" have entirely different histories.

21 changed files with 812 additions and 667 deletions

1
.gitattributes vendored
View File

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

View File

@ -8,6 +8,10 @@ Instructions for LLM coding agents working in this repository.
CommandCode `/alpha/generate` API. It implements `LanguageModelV3` from `@ai-sdk/provider@3.0.8`
and is loaded by opencode from `dist/index.js` via a `file://` npm spec.
`server.py` in this directory is the **reference implementation** of the same translation
(an OpenAI-compatible HTTP proxy). When behavior is ambiguous, `server.py` is the source of
truth for the upstream wire shape. This package is the TypeScript port; it does not run Python.
- Language/tooling: TypeScript, ESM, `tsc`.
- Runtime target: opencode's provider loader, `@ai-sdk/provider@3.0.8` (V3 specification).
- No runtime dependencies. `@ai-sdk/provider` is imported with `import type` only; the built
@ -23,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 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 provider.commandcode-go.models from the live catalog
npm run sync-models # regenerate provider.commandcode.models from the live catalog
```
There is no unit-test suite. `scripts/smoke.mjs` is the end-to-end check. `scripts/sync-models.mjs`
@ -46,12 +50,12 @@ src/toggles.ts Shared toggle file (~/.config/opencode/commandcode-toggles.jso
src/quota.ts Live 5-hour/weekly/monthly quota from the CommandCode alpha billing API.
src/tui.tsx opencode TUI plugin: /cc-zdr, /cc-debug, /cc-status, /cc-usage + sidebar.
src/tui-shims.d.ts Ambient types for the opencode-provided solid-js/@opentui/solid runtime.
tsconfig.tui.json Typechecks src/tui.tsx (+ quota/toggles/log) against the shim (no dependencies).
src/constants.ts Defaults, paths, headers, static config block.
tsconfig.tui.json Typechecks src/tui.tsx (+ quota/toggles) against the shim (no dependencies).
src/constants.ts Defaults, paths, headers, passthrough params, static config block.
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 -> provider.commandcode-go.models generator (with vision probing).
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.
scripts/sync-models.mjs Catalog -> provider.commandcode.models generator (with vision probing).
server.py Reference Python proxy (do not modify unless explicitly asked).
```
## Architecture / data flow
@ -77,8 +81,8 @@ opencode
Type-only imports must use `import 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.ts` envelope stable. If you change it, document the upstream behavior that
motivated the change.
- Keep `transform.ts` output in parity with `server.py` `transform()`. If you change the envelope,
explain which `server.py` behavior motivated it.
- Preserve the single public factory `createCommandCode`. `index.ts` re-exports it as both a named
and the default export.
- The package must stay runtime-dependency-free. Do not add a runtime `import` of a package that
@ -103,19 +107,19 @@ These are load-bearing. Breaking one causes silent failures in opencode.
be omitted from the envelope; upstream rejects the whole request otherwise.
6. **Usage is nested in V3.** Fill `inputTokens.{total,noCache,cacheRead,cacheWrite}` and
`outputTokens.{total,text,reasoning}` — not flat `promptTokens`/`completionTokens`.
`inputTokens.total` is input-only; `totalTokens` is input+output.
7. **`supportedUrls` is `{}` and stays empty.** CommandCode URLs are not fetched by the SDK.
`inputTokens.total` is input-only (parity with `server.py`); `totalTokens` is input+output.
7. **`supportedUrls` is `{}` and stays empty.** CommandsCode URLs are not fetched by the SDK.
8. **Redact before surfacing errors.** Any upstream error text passed to the client must go through
`redact()`.
9. **Replay assistant reasoning as a `{type:"reasoning"}` content part.** DeepSeek thinking mode
rejects any request carrying `tools` whose prior assistant turns omit their reasoning. In
`transform.ts`, forward each assistant `reasoning` part as `{type:"reasoning", text, signature?}`;
do not drop it and do not fabricate empty reasoning.
do not drop it and do not fabricate empty reasoning. `server.py` predates this requirement and is
not the guide here.
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`
(`providerMetadata.gateway.cost/marketCost`, strings). `finish.totalUsage` carries tokens
only. Capture both into `providerMetadata` keyed by the resolved provider id
(`options.name`; `commandcode-go` under opencode and as the factory default) on the
only. Capture both into `providerMetadata: { commandcode: { cost, marketCost } }` on the
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`
until the fork consumes this field (anomalyco/opencode#43818); `/cc-usage` is the accurate
@ -123,10 +127,10 @@ 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
must be rebuilt for opencode to see source changes.
12. **`/models` is config-driven, not provider-driven.** opencode builds the model list from
`provider.commandcode-go.models` in `opencode.json` and never asks a custom `file://` provider to
`provider.commandcode.models` in `opencode.json` and never asks a custom `file://` provider to
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.
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
**source** (not `dist/`) via a `tui.json` `plugin` entry that must be a **direct `file://` URL
to `src/tui.tsx`** (global `~/.config/opencode/tui.json` or project `.opencode/tui.json`),
wired by hand: `opencode plugin <path>` cannot install a bare `.tsx` (it needs a `package.json`
@ -167,15 +171,15 @@ 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`.
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
without restarting opencode. Precedence for `zdr`: `providerOptions.commandcode-go.zdr` >
without restarting opencode. Precedence for `zdr`: `providerOptions.commandcode.zdr` >
`x-cmd-zdr` header > toggle file. Do not reintroduce load-time consts.
16. **Quota is live from the alpha billing API.** `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/usage/summary` (the same endpoints the `cmd` CLI `/usage` uses). `resetAt` has shipped
as both seconds and epoch ms — normalize
`/alpha/usage/summary` (the same endpoints the `cmd` CLI `/usage` uses). `server.py` predates
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
plan; never hardcode a plan→cap table. The TUI resolves the key from `api.state` (provider
entry, then `config.provider.commandcode-go.options`, then `COMMANDCODE_API_KEY`), expanding
entry, then `config.provider.commandcode.options`, then `COMMANDCODE_API_KEY`), expanding
`{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
answers `200` and then emits an SSE `error` event carrying `statusCode`/`isRetryable` (e.g.
@ -185,24 +189,10 @@ 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
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.
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
1. Identify the upstream behavior and the `src/` module that implements it.
1. Read `server.py` for the behavior being ported and note the relevant function.
2. Make the smallest change in the matching `src/` file.
3. `npm run typecheck` — fix all errors.
4. `npm run build`.
@ -211,7 +201,7 @@ These are load-bearing. Breaking one causes silent failures in opencode.
7. Update `README.md` if options, features, or behavior changed. Keep `AGENTS.md` invariants
current if you discover a new one.
Do not edit `dist/` by hand; it is generated.
Do not edit `dist/` by hand; it is generated. Do not modify `server.py` unless explicitly asked.
## Verification
@ -230,9 +220,9 @@ npm run quota
Inside opencode (restart it first if config changed):
```powershell
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 models commandcode
opencode run "Reply with exactly: pong" -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/deepseek/deepseek-v4-flash-vision-exp
```
The third command confirms the full tool-call round trip (tool-call emitted, executed, result
@ -240,7 +230,7 @@ replayed). Run it after touching `transform.ts` or the tool-call mapping in `mod
## Do / Don't
- **Do** keep the wire envelope stable; document intentional changes.
- **Do** keep the wire envelope identical to `server.py`.
- **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).

View File

@ -3,8 +3,10 @@
A native [AI SDK](https://ai-sdk.dev/) provider that connects [opencode](https://opencode.ai)
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.
It is the TypeScript successor to the `server.py` proxy in this directory. Where the proxy
exposed an OpenAI-compatible `/v1/chat/completions` endpoint that opencode reached with
`@ai-sdk/openai-compatible`, this package implements the `LanguageModelV3` interface directly,
so opencode talks to CommandCode with no Python process and no local proxy in the middle.
```
opencode ──► @ai-sdk/provider (LanguageModelV3)
@ -18,10 +20,14 @@ opencode ──► @ai-sdk/provider (LanguageModelV3)
api.commandcode.ai
```
`server.py` is kept in the repository as the reference implementation. All wire-shape decisions
(error reshaping, tool-call pairing, `tool_choice` emulation, retry policy, credential redaction)
originate there and are mirrored here.
## Requirements
- **Node.js >= 18** (uses global `fetch`, `ReadableStream`, `TextDecoder`, `structuredClone`).
- **opencode >= 1.17** that ships `@ai-sdk/provider@3.0.8` (verified against opencode 1.18.35).
- **opencode >= 1.17** that ships `@ai-sdk/provider@3.0.8` (verified against opencode 1.18.30).
- A CommandCode account and API key with access to the `/alpha/generate` endpoint.
## Install and wire into opencode
@ -39,9 +45,8 @@ npm run build
// 2. ~/.config/opencode/opencode.json (or a project opencode.json)
{
"$schema": "https://opencode.ai/config.json",
"disabled_providers": ["commandcode"],
"provider": {
"commandcode-go": {
"commandcode": {
"name": "Command Code",
"npm": "file:///C:/dev/opencode-commandcode-provider/dist/index.js",
"options": {
@ -60,19 +65,11 @@ 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.
Then set the key and restart opencode:
```powershell
$env:COMMANDCODE_API_KEY = "user_..."
opencode models commandcode-go
opencode models commandcode
```
> opencode loads configuration **once at startup**. After changing `opencode.json`, a plugin, or
@ -85,7 +82,7 @@ to it, but opencode builds `/models` and the TUI picker from this map and never
## Listing all CommandCode models
opencode reads the model list from `provider.commandcode-go.models`; a custom provider cannot
opencode reads the model list from `provider.commandcode.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 —
@ -103,14 +100,14 @@ without writing. Each row shows the model id and name plus a second line with it
interactive terminal.
Before anything else the script requires a CommandCode API key (from
`provider.commandcode-go.options.apiKey` or `COMMANDCODE_API_KEY`). If neither is present — including
`provider.commandcode.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
(<https://commandcode.ai/studio/provider>) to generate one. It never writes without a key.
Then restart opencode and confirm:
```powershell
opencode models commandcode-go
opencode models commandcode
```
Mapping and behaviour:
@ -127,23 +124,23 @@ Mapping and behaviour:
values. Other fields (`variants`, `options`, `cost`, …) on selected ids are preserved.
Unselected ids are removed from the map.
The API key is read from `COMMANDCODE_API_KEY`, then `provider.commandcode-go.options.apiKey` in the
The API key is read from `COMMANDCODE_API_KEY`, then `provider.commandcode.options.apiKey` in the
global config (`baseURL`/`ccVersion` are read from there too).
## Configuration options
`provider.commandcode-go.options` is forwarded to `createCommandCode(options)`.
`provider.commandcode.options` is forwarded to `createCommandCode(options)`.
| Option | 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. |
| `ccVersion` | `string` | `1.15.1` | 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. |
| `name` | `string` | `commandcode-go` | Provider id reported to the AI SDK. opencode sets this automatically. |
| `name` | `string` | `commandcode` | Provider id reported to the AI SDK. opencode sets this automatically. |
**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
@ -185,12 +182,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
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
`providerOptions.commandcode.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.
1. `providerOptions.commandcode.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`.
3. The toggle file (`zdr` key — see [Runtime toggles](#runtime-toggles)).
@ -247,7 +244,7 @@ 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 `provider.commandcode-go.options.apiKey`. The numbers come live from the same alpha
account behind `provider.commandcode.options.apiKey`. The numbers come live from the same alpha
billing endpoints the `cmd` CLI `/usage` command uses:
| Endpoint | Used for |
@ -298,10 +295,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 |
| 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`. 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.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 |
| Sampling parameters | Yes — `temperature`, `topP`, `topK`, `stopSequences`, `seed`, presence/frequency penalties |
| `reasoning_effort` | Yes — via `providerOptions.commandcode-go` |
| `reasoning_effort` | Yes — via `providerOptions.commandcode` |
| 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 |
@ -324,7 +321,7 @@ Set the per-request reasoning effort through provider options:
```jsonc
// opencode model options / variant
"options": { "providerOptions": { "commandcode-go": { "reasoningEffort": "high" } } }
"options": { "providerOptions": { "commandcode": { "reasoningEffort": "high" } } }
```
Both `reasoning_effort` and `reasoningEffort` keys are recognised and forwarded as
@ -343,11 +340,10 @@ 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/tui.tsx opencode TUI plugin: /cc-zdr, /cc-debug, /cc-status, /cc-usage + sidebar panel.
src/constants.ts Defaults, header names, 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/quota.mjs Print the live quota headlessly.
scripts/sync-models.mjs Pick models interactively and write provider.commandcode-go.models.
scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts.
scripts/sync-models.mjs Pick models interactively and write provider.commandcode.models.
```
### Request lifecycle
@ -376,11 +372,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 smoke # live request against CommandCode
npm run quota # live 5-hour/weekly/monthly quota
npm run sync-models # regenerate provider.commandcode-go.models from the catalog
npm run sync-models # regenerate provider.commandcode.models from the catalog
```
`scripts/smoke.mjs` reads the key from `COMMANDCODE_API_KEY`, falling back to
`provider.commandcode-go.options.apiKey` in `~/.config/opencode/opencode.json`. It exercises both
`provider.commandcode.options.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:
@ -392,16 +388,16 @@ node scripts/smoke.mjs deepseek/deepseek-v4.1-flash
### Verifying inside opencode
```powershell
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 models commandcode
opencode run "Reply with exactly: pong" -m commandcode/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
```
## Troubleshooting
| Symptom | Likely cause / fix |
| --- | --- |
| `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. |
| `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. |
| 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. |
| 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

@ -17,7 +17,6 @@
"src/tui-shims.d.ts",
"src/toggles.ts",
"src/quota.ts",
"src/log.ts",
"src/redact.ts",
"src/constants.ts"
],

View File

@ -1,29 +0,0 @@
// Shared by quota.mjs and sync-models.mjs: locate the opencode config and the CommandCode
// API key the same way the provider does.
import { readFileSync } from "node:fs";
import { PROVIDER_ID } from "../dist/constants.js";
/** Parse an opencode.json; a missing file is `{ text: "", data: {}, exists: false }`. */
export function readConfig(path) {
try {
const text = readFileSync(path, "utf8");
return { text, data: JSON.parse(text), exists: true };
} catch (error) {
// A fresh install has no opencode.json yet; treat it as empty. Bad JSON or unreadable
// files still throw.
if (error.code === "ENOENT") return { text: "", data: {}, exists: false };
throw error;
}
}
/** COMMANDCODE_API_KEY, then provider options apiKey, then a configured Authorization header. */
export function resolveKey(config, env) {
const fromEnv = env.COMMANDCODE_API_KEY;
if (fromEnv && fromEnv.trim()) return fromEnv.trim();
const options = config?.provider?.[PROVIDER_ID]?.options ?? {};
const fromConfig = options.apiKey;
if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim();
const auth = options.headers?.Authorization ?? options.headers?.authorization;
if (typeof auth === "string" && auth.trim()) return auth.replace(/^Bearer\s+/i, "").trim();
return undefined;
}

View File

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

View File

@ -3,71 +3,85 @@
// the headless check and does not need opencode running.
//
// Run: node scripts/quota.mjs [--config <path>] [--base-url <url>] [--json] (build first: npm run build)
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { fetchQuota, formatQuota } from "../dist/quota.js";
import { PROVIDER_ID } from "../dist/constants.js";
import { readConfig, resolveKey } from "./opencode-config.mjs";
const opts = {
config: join(homedir(), ".config", "opencode", "opencode.json"),
baseURL: undefined,
json: false,
};
const argv = process.argv.slice(2);
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
const value = () => {
const next = argv[++i];
if (next === undefined) throw new Error(`Missing value for ${arg}`);
return next;
function parseArgs(argv) {
const opts = {
config: join(homedir(), ".config", "opencode", "opencode.json"),
baseURL: undefined,
json: false,
};
switch (arg) {
case "--config":
opts.config = value();
break;
case "--base-url":
opts.baseURL = value();
break;
case "--json":
opts.json = true;
break;
case "-h":
case "--help":
console.log(
[
"Print CommandCode quota from the alpha billing endpoints.",
"",
"Usage: node scripts/quota.mjs [options]",
" --config <path> opencode config to read (default ~/.config/opencode/opencode.json)",
" --base-url <url> upstream origin (default from config or api.commandcode.ai)",
" --json print the raw quota object instead of formatted text",
].join("\n"),
);
process.exit(0);
break;
default:
throw new Error(`Unknown argument: ${arg}`);
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
const value = () => {
const next = argv[++i];
if (next === undefined) throw new Error(`Missing value for ${arg}`);
return next;
};
switch (arg) {
case "--config":
opts.config = value();
break;
case "--base-url":
opts.baseURL = value();
break;
case "--json":
opts.json = true;
break;
case "-h":
case "--help":
console.log(
[
"Print CommandCode quota from the alpha billing endpoints.",
"",
"Usage: node scripts/quota.mjs [options]",
" --config <path> opencode config to read (default ~/.config/opencode/opencode.json)",
" --base-url <url> upstream origin (default from config or api.commandcode.ai)",
" --json print the raw quota object instead of formatted text",
].join("\n"),
);
process.exit(0);
break;
default:
throw new Error(`Unknown argument: ${arg}`);
}
}
return opts;
}
function readConfig(path) {
try {
return JSON.parse(readFileSync(path, "utf8"));
} catch {
return {};
}
}
let config = {};
try {
config = readConfig(opts.config).data;
} catch {
config = {};
function resolveKey(config, env) {
const fromEnv = env.COMMANDCODE_API_KEY;
if (fromEnv && fromEnv.trim()) return fromEnv.trim();
const options = config?.provider?.commandcode?.options ?? {};
const fromConfig = options.apiKey;
if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim();
const auth = options.headers?.Authorization ?? options.headers?.authorization;
if (typeof auth === "string" && auth.trim()) return auth.replace(/^Bearer\s+/i, "").trim();
return undefined;
}
const opts = parseArgs(process.argv.slice(2));
const config = readConfig(opts.config);
const apiKey = resolveKey(config, process.env);
if (!apiKey) {
console.error(
`No CommandCode API key found. Set COMMANDCODE_API_KEY or provider.${PROVIDER_ID}.options.apiKey in ${opts.config}.`,
`No CommandCode API key found. Set COMMANDCODE_API_KEY or provider.commandcode.options.apiKey in ${opts.config}.`,
);
process.exit(1);
}
const baseURL = opts.baseURL ?? config?.provider?.[PROVIDER_ID]?.options?.baseURL;
const baseURL = opts.baseURL ?? config?.provider?.commandcode?.options?.baseURL;
const result = await fetchQuota({ apiKey, baseURL: typeof baseURL === "string" ? baseURL : undefined });
if (!result.ok) {
console.error(result.error.message);

View File

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

View File

@ -1,4 +1,4 @@
// Interactive model picker for opencode `provider.commandcode-go.models`.
// Interactive model picker for opencode `provider.commandcode.models`.
//
// 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
@ -7,14 +7,13 @@
// the result into the global opencode config. Deselecting a model removes it from the config.
//
// Run: node scripts/sync-models.mjs (build first: npm run build)
import { mkdirSync, realpathSync, writeFileSync, renameSync } from "node:fs";
import { mkdirSync, readFileSync, realpathSync, writeFileSync, renameSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import readline from "node:readline";
import { createCommandCode } from "../dist/index.js";
import { redact } from "../dist/redact.js";
import { DEFAULT_BASE_URL, DEFAULT_CC_VERSION, DEFAULT_MAX_TOKENS, MODELS_PATH, PROVIDER_ID } from "../dist/constants.js";
import { readConfig, resolveKey } from "./opencode-config.mjs";
import { DEFAULT_BASE_URL, DEFAULT_CC_VERSION, DEFAULT_MAX_TOKENS, MODELS_PATH } from "../dist/constants.js";
const CONFIG_PATH = join(homedir(), ".config", "opencode", "opencode.json");
const CONSOLE_URL = "https://commandcode.ai/studio/provider";
@ -37,6 +36,53 @@ const NO_IMAGE =
// so this is only a best guess for ids that look like known vision families.
const VISION_HEURISTIC = /claude|gpt-5|gemini|grok|qwen.*vl|vision|(?:^|[^a-z])vl(?:[^a-z]|$)|omni|multimodal/i;
function readConfig(path) {
try {
const text = readFileSync(path, "utf8");
return { text, data: JSON.parse(text), exists: true };
} catch (error) {
// A fresh install has no opencode.json yet; treat it as empty so the console
// guidance / env-key path can still run. Bad JSON or unreadable files still throw.
if (error.code === "ENOENT") return { text: "", data: {}, exists: false };
throw error;
}
}
function detectIndent(text) {
const match = /\n([ \t]+)\S/.exec(text);
if (!match) return 2;
const indent = match[1];
if (indent.startsWith("\t")) return "\t";
return indent.length;
}
function resolveKey(config, env) {
const fromEnv = env.COMMANDCODE_API_KEY;
if (fromEnv) return fromEnv.trim();
const options = config?.provider?.commandcode?.options ?? {};
const fromConfig = options.apiKey;
if (typeof fromConfig === "string" && fromConfig.trim()) return fromConfig.trim();
const auth = options.headers?.Authorization ?? options.headers?.authorization;
if (typeof auth === "string" && auth.trim()) return auth.replace(/^Bearer\s+/i, "").trim();
return undefined;
}
async function fetchCatalog(baseURL, apiKey, ccVersion) {
const response = await fetch(`${baseURL}${MODELS_PATH}`, {
headers: {
Authorization: /^Bearer\s/i.test(apiKey) ? apiKey : `Bearer ${apiKey}`,
"x-command-code-version": ccVersion,
},
});
const body = await response.text();
if (!response.ok) {
throw new Error(`catalog ${response.status}: ${redact(body.slice(0, 500)) || response.statusText}`);
}
const parsed = JSON.parse(body);
const data = Array.isArray(parsed?.data) ? parsed.data : [];
return data.filter((m) => m && typeof m.id === "string" && m.id.length > 0);
}
async function probeVision(provider, id) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(new Error("probe timeout")), 30000);
@ -76,6 +122,68 @@ async function probeVision(provider, id) {
}
}
// Some models intermittently deny seeing an image on the first try. Retry an explicit "no image"
// once so a flaky denial does not mislabel a vision model; inconclusive results skip the retry.
async function probeVisionConfirmed(provider, id) {
let outcome = await probeVision(provider, id);
if (outcome.vision === false) outcome = await probeVision(provider, id);
return outcome;
}
async function mapPool(items, concurrency, worker) {
const results = new Array(items.length);
let cursor = 0;
const runners = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
while (true) {
const index = cursor++;
if (index >= items.length) return;
results[index] = await worker(items[index], index);
}
});
await Promise.all(runners);
return results;
}
function modelEntry(catalogModel, vision) {
const id = catalogModel.id;
const context = Number(catalogModel.context_length) || 0;
const entry = {
name: typeof catalogModel.name === "string" && catalogModel.name ? catalogModel.name : id,
limit: { context, output: DEFAULT_MAX_TOKENS },
reasoning: true,
attachment: vision,
modalities: {
input: vision ? ["text", "image"] : ["text"],
output: ["text"],
},
};
return entry;
}
function writeAtomic(path, contents) {
// Write next to the real file: renaming over a symlink would replace the link itself.
try {
path = realpathSync(path);
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
const tmp = `${path}.${process.pid}.tmp`;
writeFileSync(tmp, contents);
renameSync(tmp, path);
}
// The catalog carries no pricing fields (id/name/context_length/supported_endpoints only),
// so the picker shows context with any opportunistically present pricing keys omitted.
function formatContext(value) {
const n = Number(value);
if (!Number.isFinite(n) || n <= 0) return "unknown";
if (n >= 1_000_000 && n % 1_000_000 === 0) return `${n / 1_000_000}M (${n})`;
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M (${n})`;
if (n >= 1000 && n % 1000 === 0) return `${n / 1000}k (${n})`;
if (n >= 1000) return `${(n / 1000).toFixed(0)}k (${n})`;
return `${n}`;
}
// Builtins-only checkbox picker (no dependencies, so the package stays runtime-dependency-free).
// Nothing is pre-checked; deselected ids are dropped by the caller. Resolves to the selected
// catalog indices, or null when the user aborts (Esc on empty filter / Ctrl-C).
@ -145,22 +253,7 @@ function pickModels(catalog, existingIds) {
// Selected rows render green (both lines); the cursor row renders bold on top.
const code = selected ? (active ? "1;32" : "32") : active ? "1" : undefined;
line(`${active ? "\u203a" : " "} [${mark}] ${model.id} \u2014 ${model.name ?? model.id}${current}`, code);
// The catalog carries no pricing fields (id/name/context_length only), so only context
// is shown; opportunistically present extra keys are omitted.
const ctx = Number(model.context_length);
const ctxText =
!Number.isFinite(ctx) || ctx <= 0
? "unknown"
: ctx >= 1_000_000 && ctx % 1_000_000 === 0
? `${ctx / 1_000_000}M (${ctx})`
: ctx >= 1_000_000
? `${(ctx / 1_000_000).toFixed(1)}M (${ctx})`
: ctx >= 1000 && ctx % 1000 === 0
? `${ctx / 1000}k (${ctx})`
: ctx >= 1000
? `${(ctx / 1000).toFixed(0)}k (${ctx})`
: `${ctx}`;
line(` ctx ${ctxText}`, code);
line(` ctx ${formatContext(model.context_length)}`, code);
});
line("");
line("\u2191/\u2193 navigate · space toggle · ctrl-a all · ctrl-u none · esc back/abort · enter confirm");
@ -302,8 +395,8 @@ async function main() {
`${where}\n` +
`Generate an API key in the CommandCode Console: ${CONSOLE_URL}\n` +
(exists
? `Add it as provider.${PROVIDER_ID}.options.apiKey, or export COMMANDCODE_API_KEY.`
: `Create that file with provider.${PROVIDER_ID}.options.apiKey, or export COMMANDCODE_API_KEY.`) +
? `Add it as provider.commandcode.options.apiKey, or export COMMANDCODE_API_KEY.`
: `Create that file with provider.commandcode.options.apiKey, or export COMMANDCODE_API_KEY.`) +
`\nNothing was written.`,
);
process.exit(1);
@ -314,25 +407,13 @@ async function main() {
process.exit(1);
}
const baseURL = (config?.provider?.[PROVIDER_ID]?.options?.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
const ccVersion = config?.provider?.[PROVIDER_ID]?.options?.ccVersion ?? DEFAULT_CC_VERSION;
const baseURL = (config?.provider?.commandcode?.options?.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
const ccVersion = config?.provider?.commandcode?.options?.ccVersion ?? DEFAULT_CC_VERSION;
console.log(`Fetching catalog: ${baseURL}${MODELS_PATH}`);
let catalog;
try {
const response = await fetch(`${baseURL}${MODELS_PATH}`, {
headers: {
Authorization: /^Bearer\s/i.test(key) ? key : `Bearer ${key}`,
"x-command-code-version": ccVersion,
},
});
const body = await response.text();
if (!response.ok) {
throw new Error(`catalog ${response.status}: ${redact(body.slice(0, 500)) || response.statusText}`);
}
const parsed = JSON.parse(body);
const data = Array.isArray(parsed?.data) ? parsed.data : [];
catalog = data.filter((m) => m && typeof m.id === "string" && m.id.length > 0);
catalog = await fetchCatalog(baseURL, key, ccVersion);
} catch (error) {
console.error(`Failed to fetch catalog: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
@ -343,7 +424,7 @@ async function main() {
}
console.log(`Catalog: ${catalog.length} models`);
const existing = config?.provider?.[PROVIDER_ID]?.models ?? {};
const existing = config?.provider?.commandcode?.models ?? {};
const existingIds = new Set(Object.keys(existing));
const picked = await pickModels(catalog, existingIds);
@ -358,25 +439,13 @@ async function main() {
const selected = picked.map((index) => catalog[index]).filter(Boolean);
console.log(`Probing vision (${selected.length} models, concurrency ${CONCURRENCY})...`);
const provider = createCommandCode({ name: PROVIDER_ID, apiKey: key, baseURL, ccVersion, maxRetries: 1 });
const probeResults = new Array(selected.length);
let probeCursor = 0;
const probeRunners = Array.from({ length: Math.min(CONCURRENCY, selected.length) }, async () => {
while (true) {
const index = probeCursor++;
if (index >= selected.length) return;
const model = selected[index];
// Some models intermittently deny seeing an image on the first try. Retry an explicit
// "no image" once so a flaky denial does not mislabel a vision model; inconclusive
// results skip the retry.
let outcome = await probeVision(provider, model.id);
if (outcome.vision === false) outcome = await probeVision(provider, model.id);
const tag = outcome.vision === true ? "vision" : outcome.vision === false ? "no-vision" : "unknown";
console.log(` [${index + 1}/${selected.length}] ${model.id}: ${tag} (${outcome.reason})`);
probeResults[index] = outcome;
}
const provider = createCommandCode({ name: "commandcode", apiKey: key, baseURL, ccVersion, maxRetries: 1 });
const probeResults = await mapPool(selected, CONCURRENCY, async (model, index) => {
const outcome = await probeVisionConfirmed(provider, model.id);
const tag = outcome.vision === true ? "vision" : outcome.vision === false ? "no-vision" : "unknown";
console.log(` [${index + 1}/${selected.length}] ${model.id}: ${tag} (${outcome.reason})`);
return outcome;
});
await Promise.all(probeRunners);
// Deselect = remove: the final map holds exactly the picked ids. Extra user fields on
// picked ids are preserved; unpicked ids are dropped.
@ -395,47 +464,27 @@ async function main() {
stats.unknown++;
if (vision) stats.heuristic++;
}
const entry = {
name: typeof model.name === "string" && model.name ? model.name : model.id,
limit: { context: Number(model.context_length) || 0, output: DEFAULT_MAX_TOKENS },
reasoning: true,
attachment: vision,
modalities: {
input: vision ? ["text", "image"] : ["text"],
output: ["text"],
},
};
merged[model.id] = { ...(existing[model.id] ?? {}), ...entry };
merged[model.id] = { ...(existing[model.id] ?? {}), ...modelEntry(model, vision) };
});
const removed = [...existingIds].filter((id) => !(id in merged)).length;
config.provider ??= {};
config.provider[PROVIDER_ID] ??= {};
config.provider[PROVIDER_ID].models = merged;
config.provider.commandcode ??= {};
config.provider.commandcode.models = merged;
const indentMatch = /\n([ \t]+)\S/.exec(text);
const indent = !indentMatch ? 2 : indentMatch[1].startsWith("\t") ? "\t" : indentMatch[1].length;
const indent = detectIndent(text);
const trailing = text === "" || text.endsWith("\n") ? "\n" : "";
// The config directory may not exist yet on a fresh install; create it before the atomic write.
mkdirSync(dirname(CONFIG_PATH), { recursive: true });
// Write next to the real file: renaming over a symlink would replace the link itself.
let target = CONFIG_PATH;
try {
target = realpathSync(target);
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
const tmp = `${target}.${process.pid}.tmp`;
writeFileSync(tmp, `${JSON.stringify(config, null, indent)}${trailing}`);
renameSync(tmp, target);
writeAtomic(CONFIG_PATH, `${JSON.stringify(config, null, indent)}${trailing}`);
console.log(
`Wrote ${Object.keys(merged).length} models to ${CONFIG_PATH}\n` +
` selected=${selected.length} removed=${removed}\n` +
` probed=${stats.probed} vision=${stats.vision} no-vision=${stats.noVision} ` +
`unknown=${stats.unknown} heuristic-vision=${stats.heuristic}\n` +
`Restart opencode, then run: opencode models ${PROVIDER_ID}`,
`Restart opencode, then run: opencode models commandcode`,
);
}

View File

@ -1,23 +1,27 @@
// Wire-format constants for the CommandCode /alpha/generate API.
// 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";
// Shared constants. Ported from server.py so the wire shape stays identical.
export const DEFAULT_BASE_URL = "https://api.commandcode.ai";
export const GENERATE_PATH = "/alpha/generate";
export const MODELS_PATH = "/provider/v1/models";
export const DEFAULT_CC_VERSION = "1.84.0";
export const DEFAULT_CC_VERSION = "1.15.1";
export const DEFAULT_MAX_TOKENS = 32000;
export const DEFAULT_MAX_RETRIES = 2;
export const BASE_RETRY_DELAY = 0.5;
export const DEFAULT_RETRY_MAX_DELAY = 60;
// Sampling knobs CommandCode accepts (probed individually in server.py). Forwarded verbatim.
export const PASSTHROUGH_PARAMS = [
"temperature",
"top_p",
"top_k",
"stop",
"seed",
"presence_penalty",
"frequency_penalty",
"reasoning_effort",
] as const;
export const STATIC_CONFIG = {
workingDir: "",
date: "",

View File

@ -10,34 +10,43 @@ import { debugEnabled } from "./toggles.js";
const FILE = join(tmpdir(), "commandcode-debug.log");
function serialize(value: unknown): string {
if (typeof value === "string") return value;
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
function emit(scope: string, args: unknown[]): void {
const parts = args.map(serialize);
const line = `[commandcode] ${new Date().toISOString()} [${scope}] ${parts.join(" ")}`;
try {
appendFileSync(FILE, redact(line) + "\n", "utf8");
} catch {
// Never let tracing break the request path.
try {
process.stderr.write(redact(line) + "\n");
} catch {
/* ignore */
}
}
}
/** Effective default tracing state (toggle file). Re-read on every call. */
export function isDebugEnabled(): boolean {
return debugEnabled();
}
/** Write a trace line (appended) if tracing is enabled. Values are redacted before write. */
export function debug(scope: string, ...args: unknown[]): void {
if (!debugEnabled()) return;
emit(scope, args);
}
/** Trace with a per-request override, so providerOptions/history state is not global. */
export function debugWhen(enabled: boolean, scope: string, ...args: unknown[]): void {
if (!enabled) return;
const parts = args.map((value) => {
if (typeof value === "string") return value;
try {
return JSON.stringify(value);
} catch {
return String(value);
}
});
const line = `[commandcode] ${new Date().toISOString()} [${scope}] ${parts.join(" ")}`;
try {
appendFileSync(FILE, redact(line) + "\n", "utf8");
} catch {
// Never let tracing break the request path, or corrupt an interactive terminal
// (the TUI plugin shares this writer and its stderr may be the rendered screen).
if (!process.stderr.isTTY) {
try {
process.stderr.write(redact(line) + "\n");
} catch {
/* ignore */
}
}
}
emit(scope, args);
}

View File

@ -17,7 +17,6 @@ import {
DEFAULT_MAX_RETRIES,
DEFAULT_RETRY_MAX_DELAY,
GENERATE_PATH,
PROVIDER_ID,
} from "./constants.js";
import { iterateEvents } from "./events.js";
import { debugWhen, isDebugEnabled } from "./log.js";
@ -26,8 +25,26 @@ import { zdrEnabled } from "./toggles.js";
import { transform } from "./transform.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).
// Precedence: providerOptions.commandcode.zdr > x-cmd-zdr header > toggle file.
// "undefined" means the header is omitted entirely.
function providerScoped(options: LanguageModelV3CallOptions): Record<string, unknown> | undefined {
return options.providerOptions?.[PROVIDER_ID] as Record<string, unknown> | undefined;
return options.providerOptions?.["commandcode"] as Record<string, unknown> | undefined;
}
function truthyHeader(value: string): boolean {
return !/^(0|false|no|off)$/i.test(value);
}
function resolveZdr(
options: LanguageModelV3CallOptions,
providerHeaders: Record<string, string>,
): string | undefined {
const scoped = providerScoped(options)?.["zdr"];
if (typeof scoped === "boolean") return scoped ? "1" : "0";
const header = headerValue({ ...providerHeaders, ...(options.headers ?? {}) }, "x-cmd-zdr");
if (header !== undefined) return truthyHeader(header) ? "1" : "0";
return zdrEnabled() ? "1" : undefined;
}
function resolveDebug(options: LanguageModelV3CallOptions): boolean {
@ -61,6 +78,26 @@ function headerValue(headers: Record<string, string | undefined>, key: string):
return undefined;
}
function bearer(token: string | undefined): string | undefined {
if (!token) return undefined;
return /^Bearer\s/i.test(token) ? token : `Bearer ${token}`;
}
function resolve(options: CommandCodeOptions): ResolvedOptions {
const headers = { ...(options.headers ?? {}) };
const fromHeader = headerValue(headers, "authorization");
const apiKey = options.apiKey ?? fromHeader?.replace(/^Bearer\s+/i, "");
return {
providerId: options.name ?? "commandcode",
apiKey,
headers,
baseURL: (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ""),
ccVersion: options.ccVersion ?? DEFAULT_CC_VERSION,
maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,
retryMaxDelay: options.retryMaxDelaySeconds ?? DEFAULT_RETRY_MAX_DELAY,
};
}
function zeroUsage(): LanguageModelV3Usage {
return {
inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },
@ -76,6 +113,23 @@ function isRetryable(status: number): boolean {
// CommandCode's gateway marks these with `statusCode`/`isRetryable`; retry before content.
type StreamErrorInfo = { message: string; statusCode?: number; isRetryable?: boolean };
function streamErrorInfo(evt: Record<string, any>): StreamErrorInfo | null {
if (evt?.["type"] !== "error") return null;
const err = evt["error"];
if (err === null || typeof err !== "object") return { message: String(err) };
const record = err as Record<string, unknown>;
const message = typeof record["message"] === "string" ? record["message"] : JSON.stringify(err);
return {
message,
...(typeof record["statusCode"] === "number" ? { statusCode: record["statusCode"] } : {}),
...(typeof record["isRetryable"] === "boolean" ? { isRetryable: record["isRetryable"] } : {}),
};
}
function isRetryableStreamError(info: StreamErrorInfo): boolean {
return info.isRetryable === true || (info.statusCode !== undefined && isRetryable(info.statusCode));
}
// Only `start`/`start-step` are safe to buffer while looking for an immediate stream error;
// once real output appears a retry would duplicate the response.
const STREAM_PREAMBLE = new Set(["start", "start-step"]);
@ -110,6 +164,31 @@ function retryDelay(attempt: number, retryAfter: string | null, maxDelay: number
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function toReadableStream<T>(iterator: AsyncGenerator<T>): ReadableStream<T> {
return new ReadableStream<T>({
async pull(controller) {
try {
const { done, value } = await iterator.next();
if (done) controller.close();
else controller.enqueue(value);
} catch (error) {
controller.error(error);
}
},
async cancel(reason) {
await iterator.return?.(reason as never);
},
});
}
function headerObject(headers: Headers): Record<string, string> {
const out: Record<string, string> = {};
headers.forEach((value, key) => {
out[key] = value;
});
return out;
}
class CommandCodeLanguageModel implements LanguageModelV3 {
readonly specificationVersion = "v3" as const;
readonly provider: string;
@ -125,23 +204,11 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
supportedUrls: Record<string, RegExp[]> = {};
private async fetchWithRetry(
body: string,
options: LanguageModelV3CallOptions,
private requestHeaders(
extra: Record<string, string | undefined> | undefined,
zdr: string | undefined,
dbg: boolean,
): Promise<OpenedStream> {
// x-cmd-zdr breaks some models; off by default.
// Precedence: providerOptions["commandcode-go"].zdr > x-cmd-zdr header > toggle file.
// "undefined" means the header is omitted entirely.
const scopedZdr = providerScoped(options)?.["zdr"];
let zdr: string | undefined;
if (typeof scopedZdr === "boolean") zdr = scopedZdr ? "1" : "0";
else {
const header = headerValue({ ...this.opts.headers, ...(options.headers ?? {}) }, "x-cmd-zdr");
if (header !== undefined) zdr = /^(0|false|no|off)$/i.test(header) ? "0" : "1";
else if (zdrEnabled()) zdr = "1";
}
): Record<string, string> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
"x-command-code-version": this.opts.ccVersion,
@ -153,10 +220,18 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
};
if (zdr !== undefined) headers["x-cmd-zdr"] = zdr;
debugWhen(dbg, "fetch", "zdr", zdr === "1" ? "on" : "off");
const apiKey = this.opts.apiKey;
if (apiKey) headers["Authorization"] = /^Bearer\s/i.test(apiKey) ? apiKey : `Bearer ${apiKey}`;
for (const [k, v] of Object.entries(options.headers ?? {})) if (v !== undefined) headers[k] = v;
const auth = bearer(this.opts.apiKey);
if (auth) headers["Authorization"] = auth;
for (const [k, v] of Object.entries(extra ?? {})) if (v !== undefined) headers[k] = v;
return headers;
}
private async fetchWithRetry(
body: string,
options: LanguageModelV3CallOptions,
dbg: boolean,
): Promise<OpenedStream> {
const headers = this.requestHeaders(options.headers, resolveZdr(options, this.opts.headers), dbg);
let lastError: unknown;
const url = `${this.opts.baseURL}${GENERATE_PATH}`;
@ -231,21 +306,9 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
if (next.done) break;
const evt = next.value;
prefix.push(evt);
if (evt?.["type"] === "error") {
const err = evt["error"];
let info: StreamErrorInfo;
if (err === null || typeof err !== "object") {
info = { message: String(err) };
} else {
const record = err as Record<string, unknown>;
info = {
message: typeof record["message"] === "string" ? record["message"] : JSON.stringify(err),
...(typeof record["statusCode"] === "number" ? { statusCode: record["statusCode"] } : {}),
...(typeof record["isRetryable"] === "boolean" ? { isRetryable: record["isRetryable"] } : {}),
};
}
const retryable = info.isRetryable === true || (info.statusCode !== undefined && isRetryable(info.statusCode));
if (retryable && attempt < this.opts.maxRetries) streamRetry = info;
const info = streamErrorInfo(evt);
if (info) {
if (isRetryableStreamError(info) && attempt < this.opts.maxRetries) streamRetry = info;
break;
}
if (!STREAM_PREAMBLE.has(evt["type"])) break;
@ -287,52 +350,40 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
throw lastError instanceof Error ? lastError : new Error("Upstream unreachable");
}
private async errorFrom(response: Response, dbg: boolean): Promise<Error> {
let body = "";
try {
body = await response.text();
} catch {
/* ignore */
}
let message = body;
try {
const parsed = JSON.parse(body);
const err = parsed?.error;
if (typeof err === "string") message = err;
else if (err && typeof err === "object" && typeof err.message === "string") message = err.message;
} catch {
/* keep raw body */
}
const surfaced = redact(message.slice(0, 2000) || `Upstream returned ${response.status}`);
debugWhen(dbg, "error", `status=${response.status}`, `body=${surfaced}`);
return new Error(surfaced);
}
async doStream(options: LanguageModelV3CallOptions): Promise<LanguageModelV3StreamResult> {
const dbg = resolveDebug(options);
const body = transform(options, this.modelId);
debugWhen(dbg, "doStream", `model=${this.modelId}`, `bodyBytes=${Buffer.byteLength(body, "utf8")}`);
const { response, prefix, events } = await this.fetchWithRetry(body, options, dbg);
if (!response.ok || !response.body) {
let responseBody = "";
try {
responseBody = await response.text();
} catch {
/* ignore */
}
let message = responseBody;
try {
const parsed = JSON.parse(responseBody);
const err = parsed?.error;
if (typeof err === "string") message = err;
else if (err && typeof err === "object" && typeof err.message === "string") message = err.message;
} catch {
/* keep raw body */
}
const surfaced = redact(message.slice(0, 2000) || `Upstream returned ${response.status}`);
debugWhen(dbg, "error", `status=${response.status}`, `body=${surfaced}`);
throw new Error(surfaced);
}
if (!response.ok || !response.body) throw await this.errorFrom(response, dbg);
debugWhen(dbg, "doStream", "ok", `status=${response.status}`);
const iterator = this.streamParts(prefix, events, dbg);
const stream = new ReadableStream<LanguageModelV3StreamPart>({
async pull(controller) {
try {
const { done, value } = await iterator.next();
if (done) controller.close();
else controller.enqueue(value);
} catch (error) {
controller.error(error);
}
},
async cancel(reason) {
await iterator.return?.(reason as never);
},
});
const stream = toReadableStream(this.streamParts(prefix, events, dbg));
return {
stream,
request: { body: JSON.parse(body) as unknown },
response: { headers: Object.fromEntries(response.headers) },
response: { headers: headerObject(response.headers) },
};
}
@ -541,7 +592,7 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
};
const hasCost = cost !== undefined || marketCost !== undefined;
if (hasCost) finalUsage.raw = { ...(finalUsage.raw ?? {}), ...reported };
const finishMetadata: SharedV3ProviderMetadata | undefined = hasCost ? { [this.opts.providerId]: reported } : undefined;
const finishMetadata: SharedV3ProviderMetadata | undefined = hasCost ? { commandcode: reported } : undefined;
debugWhen(dbg, "stream", "terminal", `finish=${finishReason ? (finishReason.unified ?? "?") : "synthesized"}`, `usage=${JSON.stringify(finalUsage)}`, `providerMetadata=${JSON.stringify(finishMetadata ?? {})}`);
yield {
type: "finish",
@ -560,17 +611,7 @@ class CommandCodeLanguageModel implements LanguageModelV3 {
export function createCommandCode(options: CommandCodeOptions = {}): {
languageModel(modelId: string): LanguageModelV3;
} {
const headers = { ...(options.headers ?? {}) };
const fromHeader = headerValue(headers, "authorization");
const resolved: ResolvedOptions = {
providerId: options.name ?? PROVIDER_ID,
apiKey: options.apiKey ?? fromHeader?.replace(/^Bearer\s+/i, ""),
headers,
baseURL: (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ""),
ccVersion: options.ccVersion ?? DEFAULT_CC_VERSION,
maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,
retryMaxDelay: options.retryMaxDelaySeconds ?? DEFAULT_RETRY_MAX_DELAY,
};
const resolved = resolve(options);
return {
languageModel(modelId: string) {
return new CommandCodeLanguageModel(modelId, resolved);

View File

@ -370,41 +370,46 @@ export function formatReset(resetAtMs: number | null, now: number = Date.now()):
return rem > 0 ? `${days}d ${rem}h` : `${days}d`;
}
function formatTokens(tokens: number): string {
if (tokens >= 1_000_000_000) return `${(tokens / 1_000_000_000).toFixed(1)}B`;
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}k`;
return String(tokens);
}
function formatWindowLine(w: QuotaWindow, now: number): string {
const pct = Math.min(percent(w.used, w.cap), 999);
const reset = formatReset(w.resetAtMs, now);
const amount =
w.id === "monthly"
? `$${w.used.toFixed(2)} / $${w.cap.toFixed(2)}`
: `${w.used.toFixed(2)} / ${w.cap.toFixed(2)} credits`;
return `${w.label.padEnd(8)} ${quotaBar(w.used, w.cap)} ${String(pct).padStart(3)}% ${amount}${
reset ? ` (resets in ${reset})` : ""
}`;
}
function planLine(plan: QuotaPlan, now: number): string {
const name = plan.id.replace(/[_-]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
const status = plan.status ? ` · ${plan.status}` : "";
const end = periodEndMs(plan);
if (end === null) return `Plan: ${name}${status}`;
const remaining = end - now;
const days = Math.ceil(remaining / 86_400_000);
const date = new Date(end).toISOString().slice(0, 10);
const when = days > 0 ? `renews ${date} (${days}d)` : days === 0 ? `renews ${date} (today)` : `renewed ${date}`;
return `Plan: ${name}${status} · ${when}`;
}
/** Human-readable multi-line quota summary for the `/cc-usage` command and CLI. */
export function formatQuota(quota: Quota, now: number = Date.now()): string {
const lines: string[] = [];
lines.push(quota.account.keyName ?? quota.account.login);
if (quota.plan) {
const plan = quota.plan;
const name = plan.id.replace(/[_-]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
const status = plan.status ? ` · ${plan.status}` : "";
const end = periodEndMs(plan);
if (end === null) {
lines.push(`Plan: ${name}${status}`);
} else {
const days = Math.ceil((end - now) / 86_400_000);
const date = new Date(end).toISOString().slice(0, 10);
const when = days > 0 ? `renews ${date} (${days}d)` : days === 0 ? `renews ${date} (today)` : `renewed ${date}`;
lines.push(`Plan: ${name}${status} · ${when}`);
}
}
if (quota.plan) lines.push(planLine(quota.plan, now));
if (quota.windows.length > 0) {
lines.push("");
for (const w of quota.windows) {
const pct = Math.min(percent(w.used, w.cap), 999);
const reset = formatReset(w.resetAtMs, now);
const amount =
w.id === "monthly"
? `$${w.used.toFixed(2)} / $${w.cap.toFixed(2)}`
: `${w.used.toFixed(2)} / ${w.cap.toFixed(2)} credits`;
lines.push(
`${w.label.padEnd(8)} ${quotaBar(w.used, w.cap)} ${String(pct).padStart(3)}% ${amount}${
reset ? ` (resets in ${reset})` : ""
}`,
);
}
for (const w of quota.windows) lines.push(formatWindowLine(w, now));
}
if (quota.credits) {
@ -415,19 +420,7 @@ export function formatQuota(quota: Quota, now: number = Date.now()): string {
if (quota.summary) {
const period = quota.plan?.currentPeriodStart ? "this billing period" : "total";
const totalTokens = quota.summary.totalTokens;
let tokens = "";
if (totalTokens !== undefined) {
const amount =
totalTokens >= 1_000_000_000
? `${(totalTokens / 1_000_000_000).toFixed(1)}B`
: totalTokens >= 1_000_000
? `${(totalTokens / 1_000_000).toFixed(1)}M`
: totalTokens >= 1_000
? `${(totalTokens / 1_000).toFixed(1)}k`
: String(totalTokens);
tokens = ` · ${amount} tokens`;
}
const tokens = quota.summary.totalTokens === undefined ? "" : ` · ${formatTokens(quota.summary.totalTokens)} tokens`;
lines.push(
`Usage: ${quota.summary.totalCount.toLocaleString("en-US")} requests · $${quota.summary.totalCost.toFixed(2)} (${period})${tokens}`,
);

View File

@ -1,4 +1,5 @@
// Credential redaction. Upstream error bodies can echo the caller's credentials and are
// Credential redaction. Ported from server.py (which ported pi-commandcode-provider
// src/overflow.ts). Upstream error bodies can echo the caller's credentials and are
// forwarded to the client, so scrub them first.
const REDACT: Array<[RegExp, string]> = [

View File

@ -30,9 +30,8 @@ export function readToggles(): Toggles {
}
}
export function toggle(name: ToggleName): Toggles {
const current = readToggles();
const merged = { ...current, [name]: current[name] !== true };
export function writeToggles(patch: Toggles): Toggles {
const merged = { ...readToggles(), ...patch };
const path = togglesPath();
mkdirSync(dirname(path), { recursive: true });
const tmp = `${path}.${process.pid}.tmp`;
@ -41,6 +40,11 @@ export function toggle(name: ToggleName): Toggles {
return merged;
}
export function toggle(name: ToggleName): Toggles {
const current = readToggles();
return writeToggles({ [name]: current[name] !== true });
}
/** Toggle state from the shared flag file; an absent key means off. */
export function zdrEnabled(): boolean {
return readToggles().zdr === true;

View File

@ -1,30 +1,44 @@
import type {
LanguageModelV3CallOptions,
LanguageModelV3FunctionTool,
LanguageModelV3ToolResultOutput,
LanguageModelV3ToolResultPart,
} from "@ai-sdk/provider";
import { DEFAULT_MAX_TOKENS, PROVIDER_ID, STATIC_CONFIG } from "./constants.js";
import { DEFAULT_MAX_TOKENS, PASSTHROUGH_PARAMS, STATIC_CONFIG } from "./constants.js";
type ContentPart = Record<string, unknown>;
function stringify(value: unknown): string {
if (typeof value === "string") return value;
try {
return JSON.stringify(value);
} catch {
return String(value);
}
type ToolCallRef = { id: string; name: string };
function environmentInfo(): string {
const plat = typeof process !== "undefined" ? `${process.platform}-${process.arch}` : "unknown";
const ver = typeof process !== "undefined" && process.version ? process.version : "";
return `${plat}${ver ? `, Node ${ver}` : ""}`;
}
/** AI SDK call options -> CommandCode `/alpha/generate` envelope (JSON string). */
export function transform(options: LanguageModelV3CallOptions, modelId: string): string {
const systemParts: string[] = [];
const messages: Array<Record<string, unknown>> = [];
function today(): string {
return new Date().toISOString().slice(0, 10);
}
// Tool ids that have both a call and a result. Unmatched ids make upstream reject the request.
/** tool_call_id -> tool name, so tool results can be attributed. */
function collectToolNames(prompt: LanguageModelV3CallOptions["prompt"]): Map<string, string> {
const names = new Map<string, string>();
for (const message of prompt) {
if (message.role !== "assistant") continue;
for (const part of message.content) {
if (part.type === "tool-call" && part.toolCallId) {
names.set(part.toolCallId, part.toolName);
}
}
}
return names;
}
/** Tool ids that have both a call and a result. Unmatched ids make upstream reject the request. */
function pairedToolCallIds(prompt: LanguageModelV3CallOptions["prompt"]): Set<string> {
const calls = new Set<string>();
const results = new Set<string>();
for (const message of options.prompt) {
for (const message of prompt) {
if (message.role === "assistant") {
for (const part of message.content) {
if (part.type === "tool-call" && part.toolCallId) calls.add(part.toolCallId);
@ -35,16 +49,119 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
}
}
}
const paired = new Set([...calls].filter((id) => results.has(id)));
return new Set([...calls].filter((id) => results.has(id)));
}
// tool_call_id -> tool name, so tool results can be attributed.
const toolNames = new Map<string, string>();
for (const message of options.prompt) {
if (message.role !== "assistant") continue;
for (const part of message.content) {
if (part.type === "tool-call" && part.toolCallId) toolNames.set(part.toolCallId, part.toolName);
}
function stringify(value: unknown): string {
if (typeof value === "string") return value;
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
function toolResultOutput(output: LanguageModelV3ToolResultOutput): ContentPart {
switch (output.type) {
case "text":
case "error-text":
return { type: "text", value: output.value };
case "json":
case "error-json":
return { type: "text", value: stringify(output.value) };
case "execution-denied":
return { type: "text", value: output.reason ?? "Execution denied" };
case "content": {
const parts: ContentPart[] = [];
for (const item of output.value) {
if (item.type === "text") {
parts.push({ type: "text", text: item.text });
} else if (item.type === "image-data") {
parts.push({
type: "image",
image: `data:${item.mediaType};base64,${item.data}`,
mimeType: item.mediaType,
});
} else if (item.type === "image-url" || item.type === "file-url") {
parts.push({ type: "image", image: item.url });
} else if (item.type === "file-data") {
parts.push({
type: "image",
image: `data:${item.mediaType};base64,${item.data}`,
mimeType: item.mediaType,
});
} else {
parts.push({ type: "text", text: stringify(item) });
}
}
return { type: "text", value: stringify(parts) };
}
default:
return { type: "text", value: stringify(output) };
}
}
/** AI SDK file part -> CommandCode image part. */
function imagePart(data: unknown, mediaType: string): ContentPart | null {
if (data instanceof URL) return { type: "image", image: data.toString() };
if (typeof data === "string") {
if (/^data:[^;,]+;base64,/.test(data)) return { type: "image", image: data, mimeType: mediaType };
if (/^https?:\/\//i.test(data)) return { type: "image", image: data };
return { type: "image", image: `data:${mediaType};base64,${data}`, mimeType: mediaType };
}
if (data instanceof Uint8Array) {
return { type: "image", image: `data:${mediaType};base64,${Buffer.from(data).toString("base64")}`, mimeType: mediaType };
}
return null;
}
function mapTools(tools: LanguageModelV3CallOptions["tools"]): Array<Record<string, unknown>> {
const out: Array<Record<string, unknown>> = [];
for (const tool of tools ?? []) {
if (tool.type !== "function") continue;
const fn = tool as LanguageModelV3FunctionTool;
out.push({
type: "function",
name: fn.name,
description: fn.description ?? "",
input_schema: fn.inputSchema ?? { type: "object", properties: {} },
});
}
return out;
}
/**
* OpenAI/upstream `tool_choice` -> (tools, params.tool_choice).
*
* Upstream accepts exactly one value, `{"type":"auto"}`. `none` is emulated by sending no
* tools; a named tool by sending only that tool; `required` is not expressible.
*/
function applyToolChoice(
tools: Array<Record<string, unknown>>,
toolChoice: LanguageModelV3CallOptions["toolChoice"],
): { tools: Array<Record<string, unknown>>; toolChoice: Record<string, unknown> | null } {
if (!toolChoice) return { tools, toolChoice: null };
if (toolChoice.type === "auto") return { tools, toolChoice: { type: "auto" } };
if (toolChoice.type === "none") return { tools: [], toolChoice: null };
if (toolChoice.type === "required") return { tools, toolChoice: null };
if (toolChoice.type === "tool") {
const picked = tools.filter((t) => t.name === toolChoice.toolName);
return { tools: picked.length ? picked : tools, toolChoice: null };
}
return { tools, toolChoice: null };
}
function reasoningEffort(options: LanguageModelV3CallOptions): unknown {
const scoped = options.providerOptions?.["commandcode"] as Record<string, unknown> | undefined;
return scoped?.["reasoning_effort"] ?? scoped?.["reasoningEffort"];
}
/** AI SDK call options -> CommandCode `/alpha/generate` envelope (JSON string). */
export function transform(options: LanguageModelV3CallOptions, modelId: string): string {
const systemParts: string[] = [];
const messages: Array<Record<string, unknown>> = [];
const paired = pairedToolCallIds(options.prompt);
const toolNames = collectToolNames(options.prompt);
for (const message of options.prompt) {
if (message.role === "system") {
@ -56,49 +173,6 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
for (const part of message.content) {
if (part.type !== "tool-result") continue;
if (!paired.has(part.toolCallId)) continue;
const output = (part as LanguageModelV3ToolResultPart).output;
let rendered: ContentPart;
switch (output.type) {
case "text":
case "error-text":
rendered = { type: "text", value: output.value };
break;
case "json":
case "error-json":
rendered = { type: "text", value: stringify(output.value) };
break;
case "execution-denied":
rendered = { type: "text", value: output.reason ?? "Execution denied" };
break;
case "content": {
const items: ContentPart[] = [];
for (const item of output.value) {
if (item.type === "text") {
items.push({ type: "text", text: item.text });
} else if (item.type === "image-data") {
items.push({
type: "image",
image: `data:${item.mediaType};base64,${item.data}`,
mimeType: item.mediaType,
});
} else if (item.type === "image-url" || item.type === "file-url") {
items.push({ type: "image", image: item.url });
} else if (item.type === "file-data") {
items.push({
type: "image",
image: `data:${item.mediaType};base64,${item.data}`,
mimeType: item.mediaType,
});
} else {
items.push({ type: "text", text: stringify(item) });
}
}
rendered = { type: "text", value: stringify(items) };
break;
}
default:
rendered = { type: "text", value: stringify(output) };
}
messages.push({
role: "tool",
content: [
@ -106,7 +180,7 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
type: "tool-result",
toolCallId: part.toolCallId,
toolName: part.toolName ?? toolNames.get(part.toolCallId) ?? "unknown",
output: rendered,
output: toolResultOutput((part as LanguageModelV3ToolResultPart).output),
},
],
});
@ -148,23 +222,9 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
if (part.type === "text") {
parts.push({ type: "text", text: part.text });
} else if (part.type === "file") {
const mediaType = part.mediaType;
if (mediaType?.startsWith("image/")) {
// AI SDK file part -> CommandCode image part.
const data = (part as { data?: unknown }).data;
if (data instanceof URL) {
parts.push({ type: "image", image: data.toString() });
} else if (typeof data === "string") {
if (/^data:[^;,]+;base64,/.test(data)) parts.push({ type: "image", image: data, mimeType: mediaType });
else if (/^https?:\/\//i.test(data)) parts.push({ type: "image", image: data });
else parts.push({ type: "image", image: `data:${mediaType};base64,${data}`, mimeType: mediaType });
} else if (data instanceof Uint8Array) {
parts.push({
type: "image",
image: `data:${mediaType};base64,${Buffer.from(data).toString("base64")}`,
mimeType: mediaType,
});
}
if (part.mediaType?.startsWith("image/")) {
const img = imagePart((part as { data?: unknown }).data, part.mediaType);
if (img) parts.push(img);
} else {
parts.push({ type: "text", text: `[file: ${part.filename ?? part.mediaType}]` });
}
@ -173,30 +233,8 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
messages.push({ role: "user", content: parts });
}
const tools: Array<Record<string, unknown>> = [];
for (const tool of options.tools ?? []) {
if (tool.type !== "function") continue;
const fn = tool as LanguageModelV3FunctionTool;
tools.push({
type: "function",
name: fn.name,
description: fn.description ?? "",
input_schema: fn.inputSchema ?? { type: "object", properties: {} },
});
}
// Upstream accepts exactly one `tool_choice` value, `{"type":"auto"}`. `none` is emulated
// by sending no tools; a named tool by sending only that tool; `required` is not expressible.
let toolChoice: Record<string, unknown> | null = null;
if (options.toolChoice) {
const choice = options.toolChoice;
if (choice.type === "auto") toolChoice = { type: "auto" };
else if (choice.type === "none") tools.length = 0;
else if (choice.type === "tool") {
const picked = tools.filter((t) => t.name === choice.toolName);
if (picked.length) tools.splice(0, tools.length, ...picked);
}
}
const mapped = mapTools(options.tools);
const { tools, toolChoice } = applyToolChoice(mapped, options.toolChoice);
const params: Record<string, unknown> = { model: modelId };
const systemText = systemParts.filter(Boolean).join("\n\n");
@ -215,17 +253,10 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
if (options.seed !== undefined) params["seed"] = options.seed;
if (options.presencePenalty !== undefined) params["presence_penalty"] = options.presencePenalty;
if (options.frequencyPenalty !== undefined) params["frequency_penalty"] = options.frequencyPenalty;
const scoped = options.providerOptions?.[PROVIDER_ID] as Record<string, unknown> | undefined;
const effort = scoped?.["reasoning_effort"] ?? scoped?.["reasoningEffort"];
const effort = reasoningEffort(options);
if (effort !== undefined) params["reasoning_effort"] = effort;
const plat = typeof process !== "undefined" ? `${process.platform}-${process.arch}` : "unknown";
const ver = typeof process !== "undefined" && process.version ? process.version : "";
const config = {
...STATIC_CONFIG,
date: new Date().toISOString().slice(0, 10),
environment: `${plat}${ver ? `, Node ${ver}` : ""}`,
};
const config = { ...STATIC_CONFIG, date: today(), environment: environmentInfo() };
return JSON.stringify({
config,
@ -236,3 +267,5 @@ export function transform(options: LanguageModelV3CallOptions, modelId: string):
params,
});
}
export { PASSTHROUGH_PARAMS };

1
src/tui-shims.d.ts vendored
View File

@ -6,7 +6,6 @@
declare module "solid-js" {
export function createSignal<Value>(value: Value): [get: () => Value, set: (value: Value) => void];
export function createMemo<Value>(fn: () => Value): () => Value;
}
declare namespace JSX {

View File

@ -14,11 +14,12 @@
// `namespace: "palette"` command list, so these entries appear in both; `hidden: true`
// would remove them from both.
import { createMemo, createSignal } from "solid-js";
import { appendFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createSignal } from "solid-js";
import { fetchQuota, formatQuota, formatReset, percent, quotaBar, type QuotaResult } from "./quota.js";
import { PROVIDER_ID } from "./constants.js";
import { debugWhen } from "./log.js";
import { fetchQuota, formatQuota, formatReset, percent, quotaBar, type QuotaResult, type QuotaWindow } from "./quota.js";
import { redact } from "./redact.js";
import { debugEnabled, readToggles, toggle, type ToggleName, type Toggles } from "./toggles.js";
@ -123,7 +124,23 @@ function safeEnv(name: string): string | undefined {
/** Debug-only trace to the shared debug file. Silent unless debug is on; never logs the key. */
function trace(...args: unknown[]): void {
debugWhen(debugEnabled(), "tui-quota", ...args);
if (!debugEnabled()) return;
const file = join(tmpdir(), "commandcode-debug.log");
const parts = args.map((value) => (typeof value === "string" ? value : safeJson(value)));
const line = `[commandcode] ${new Date().toISOString()} [tui-quota] ${parts.join(" ")}`;
try {
appendFileSync(file, redact(line) + "\n", "utf8");
} catch {
// Never let tracing break the panel.
}
}
function safeJson(value: unknown): string {
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
function state(value: boolean | undefined): string {
@ -146,23 +163,26 @@ function resolveRef(value: unknown): string | undefined {
function commandCodeOptions(api: TuiApi): Record<string, unknown> | undefined {
try {
return api.state?.config?.provider?.[PROVIDER_ID]?.options;
return api.state?.config?.provider?.["commandcode"]?.options;
} catch {
return undefined;
}
}
function resolveApiKeySource(api: TuiApi): { key?: string; source: string } {
let providers: readonly TuiProvider[] = [];
function providersOf(api: TuiApi): TuiProvider[] {
try {
const list = api.state?.provider;
if (Array.isArray(list)) providers = list as TuiProvider[];
if (Array.isArray(list)) return list as TuiProvider[];
// Tolerate a non-array provider state shape instead of throwing.
else if (list && typeof list === "object") providers = Object.values(list) as TuiProvider[];
if (list && typeof list === "object") return Object.values(list) as TuiProvider[];
} catch {
/* fall through */
}
const provider = providers.find((entry) => entry?.id === PROVIDER_ID);
return [];
}
function resolveApiKeySource(api: TuiApi): { key?: string; source: string } {
const provider = providersOf(api).find((entry) => entry?.id === "commandcode");
const options = commandCodeOptions(api);
const headers = options?.["headers"] as Record<string, unknown> | undefined;
const named: Array<[string, unknown]> = [
@ -206,6 +226,61 @@ function summarizeTotals(totals: TokenTotals): CacheSummary | undefined {
};
}
/**
* Session-cumulative token accounting from the reactive session store opencode's built-in
* context panel also reads. `tokens.input` is non-cached, so total prompt tokens are
* input+cache.read+cache.write; output includes reasoning. `hit` is cacheRead/total-input.
*/
function sessionCacheSummary(api: TuiApi, sessionID: string | undefined): CacheSummary | undefined {
if (!sessionID) return undefined;
let messages: ReadonlyArray<TuiMessageInfo>;
try {
const list = api.state?.session?.messages(sessionID);
if (!Array.isArray(list)) return undefined;
messages = list;
} catch {
return undefined;
}
const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
for (const message of messages) {
if (message?.role !== "assistant") continue;
addMessageTokens(totals, message.tokens);
}
return summarizeTotals(totals);
}
function safeSessionGet(api: TuiApi, sessionID: string): TuiSessionInfo | undefined {
try {
return api.state?.session?.get?.(sessionID);
} catch {
return undefined;
}
}
/**
* Prefer the child session's aggregate tokens (the v2 store exposes them), and fall back to
* summing its assistant messages when the aggregate is absent. Mirrors sessionCacheSummary so
* parent and descendant numbers use the same math.
*/
async function addChildTokens(api: TuiApi, child: TuiSessionInfo, totals: TokenTotals): Promise<void> {
const aggregate = safeSessionGet(api, child.id)?.tokens ?? child.tokens;
if (aggregate) {
addMessageTokens(totals, aggregate);
return;
}
const client = api.client;
if (!client?.session?.messages) return;
try {
const response = await client.session.messages({ sessionID: child.id, limit: FAMILY_MESSAGE_LIMIT });
for (const entry of response?.data ?? []) {
if (entry?.info?.role !== "assistant") continue;
addMessageTokens(totals, entry.info.tokens);
}
} catch (error) {
trace("family-messages-error", redact(error instanceof Error ? error.message : String(error)));
}
}
/**
* Walk every descendant sub-agent session (task tool children can nest) via the SDK
* `session.children` endpoint and sum their token usage. Never throws into the render path.
@ -233,28 +308,7 @@ async function collectFamily(api: TuiApi, rootID: string): Promise<CacheSummary
visited.add(child.id);
next.push(child.id);
counted++;
// Prefer the child's aggregate tokens (the v2 store exposes them) and fall back to
// summing its assistant messages; mirrors the parent accounting so the math matches.
let aggregate = child.tokens;
try {
aggregate = api.state?.session?.get?.(child.id)?.tokens ?? child.tokens;
} catch {
/* fall back to the child entry's tokens */
}
if (aggregate) {
addMessageTokens(totals, aggregate);
continue;
}
if (!client.session?.messages) continue;
try {
const response = await client.session.messages({ sessionID: child.id, limit: FAMILY_MESSAGE_LIMIT });
for (const entry of response?.data ?? []) {
if (entry?.info?.role !== "assistant") continue;
addMessageTokens(totals, entry.info.tokens);
}
} catch (error) {
trace("family-messages-error", redact(error instanceof Error ? error.message : String(error)));
}
await addChildTokens(api, child, totals);
}
}
frontier = next;
@ -273,6 +327,56 @@ type TokenView = {
empty: boolean;
};
function combineTokens(main: CacheSummary | undefined, sub: CacheSummary | undefined): TokenView {
const input = (main?.input ?? 0) + (sub?.input ?? 0);
const output = (main?.output ?? 0) + (sub?.output ?? 0);
const read = (main?.read ?? 0) + (sub?.read ?? 0);
return {
input,
output,
subInput: sub?.input ?? 0,
subOutput: sub?.output ?? 0,
hasSub: sub !== undefined,
hit: input > 0 ? (read / input) * 100 : undefined,
empty: main === undefined && sub === undefined,
};
}
function formatIn(view: TokenView): string {
if (view.empty) return "in: --";
const delta = view.hasSub ? ` (+${view.subInput.toLocaleString()})` : "";
return `in: ${view.input.toLocaleString()}${delta}`;
}
function formatOut(view: TokenView): string {
if (view.empty) return "out: --";
const delta = view.hasSub ? ` (+${view.subOutput.toLocaleString()})` : "";
return `out: ${view.output.toLocaleString()}${delta}`;
}
function formatHit(view: TokenView): string {
if (view.empty || view.hit === undefined) return "hit: --";
return `hit: ${view.hit.toFixed(1)}%`;
}
function quotaIntervalMs(): number {
const raw = Number(safeEnv("COMMANDCODE_QUOTA_INTERVAL_MS"));
return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_QUOTA_INTERVAL_MS;
}
function formatClock(ms: number): string {
if (!(ms > 0)) return "--:--:--";
return new Date(ms).toTimeString().slice(0, 8);
}
function shortWindow(w: QuotaWindow, nowMs: number): string {
const label = w.id === "fiveHour" ? "5h" : w.id === "weekly" ? "7d" : "mo";
const reset = formatReset(w.resetAtMs, nowMs);
const tail = reset ? ` · ${reset}` : "";
const amount = w.id === "monthly" ? `$${w.used.toFixed(2)}/$${w.cap.toFixed(2)}` : `${percent(w.used, w.cap)}%`;
return `${label} ${quotaBar(w.used, w.cap, 8)} ${amount}${tail}`;
}
export const tui = async (api: TuiApi): Promise<void> => {
const [toggles, setToggles] = createSignal(readToggles());
const [quota, setQuota] = createSignal<QuotaResult | null>(null);
@ -289,6 +393,8 @@ export const tui = async (api: TuiApi): Promise<void> => {
let familyRequestId = 0;
let familyTimer: ReturnType<typeof setTimeout> | undefined;
const refresh = (): void => setToggles(readToggles());
const refreshQuota = async (): Promise<void> => {
if (inflight) {
pending = true;
@ -383,50 +489,49 @@ export const tui = async (api: TuiApi): Promise<void> => {
});
};
/**
* Session-cumulative token accounting from the reactive session store opencode's built-in
* context panel also reads. `tokens.input` is non-cached, so total prompt tokens are
* input+cache.read+cache.write; output includes reasoning. `hit` is cacheRead/total-input.
* A memo over the sessionId()/family() signals so the panel walks messages once per change.
*/
const view = createMemo((): TokenView => {
const sessionID = sessionId();
let main: CacheSummary | undefined;
if (sessionID) {
let messages: ReadonlyArray<TuiMessageInfo> | undefined;
try {
const list = api.state?.session?.messages(sessionID);
if (Array.isArray(list)) messages = list;
} catch {
messages = undefined;
}
if (messages) {
const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
for (const message of messages) {
if (message?.role !== "assistant") continue;
addMessageTokens(totals, message.tokens);
}
main = summarizeTotals(totals);
}
}
const sub = family();
const input = (main?.input ?? 0) + (sub?.input ?? 0);
const output = (main?.output ?? 0) + (sub?.output ?? 0);
const read = (main?.read ?? 0) + (sub?.read ?? 0);
return {
input,
output,
subInput: sub?.input ?? 0,
subOutput: sub?.output ?? 0,
hasSub: sub !== undefined,
hit: input > 0 ? (read / input) * 100 : undefined,
empty: main === undefined && sub === undefined,
};
});
function tone(w: QuotaWindow, theme: TuiTheme): unknown {
if (w.exceeded || percent(w.used, w.cap) >= 100) return theme.current.error;
if (percent(w.used, w.cap) >= 80) return theme.current.warning;
return theme.current.success;
}
// Reads quota()/now() inside the JSX so Solid tracks the signals. Hoisting
// `quota()` into a `const` above the return would subscribe once under a
// non-tracking owner (the slot re-invokes the handler on session change,
// which is why /session "fixed" it) and freeze the panel after first paint.
const windowsOf = (result: QuotaResult | null): QuotaWindow[] =>
result?.ok === true ? result.quota.windows : [];
const errorOf = (result: QuotaResult | null): string | undefined =>
result?.ok === false ? result.error.message : undefined;
const Status = () => {
const theme = api.theme;
const view = () => combineTokens(sessionCacheSummary(api, sessionId()), family());
return (
<box flexDirection="column" gap={0}>
<text fg={theme.current.text}>
<b>CommandCode</b>
</text>
<text fg={theme.current.textMuted}>
zdr:{state(toggles().zdr)} debug:{state(toggles().debug)}
</text>
<text fg={theme.current.textMuted}>{formatIn(view())}</text>
<text fg={theme.current.textMuted}>{formatOut(view())}</text>
<text fg={theme.current.textMuted}>{formatHit(view())}</text>
{windowsOf(quota()).map((w) => (
<text fg={tone(w, theme)}>{shortWindow(w, now())}</text>
))}
{errorOf(quota()) !== undefined ? (
<text fg={theme.current.error}>quota: {errorOf(quota())}</text>
) : quota() === null ? (
<text fg={theme.current.textMuted}>quota: loading…</text>
) : null}
<text fg={theme.current.textMuted}>updated @ {formatClock(updatedAt())}</text>
</box>
);
};
api.slots.register({
order: SIDEBAR_ORDER,
slots: {
@ -438,64 +543,7 @@ export const tui = async (api: TuiApi): Promise<void> => {
scheduleFamilyRefresh(id);
}
if (id !== undefined) setSessionId(id);
const theme = api.theme;
// Reads toggles()/quota()/view()/now() inside the JSX so Solid tracks the signals.
// Hoisting them into a `const` above the return would subscribe once under a
// non-tracking owner (the slot re-invokes the handler on session change, which is
// why /session "fixed" it) and freeze the panel after first paint.
return (
<box flexDirection="column" gap={0}>
<text fg={theme.current.text}>
<b>CommandCode</b>
</text>
<text fg={theme.current.textMuted}>
zdr:{state(toggles().zdr)} debug:{state(toggles().debug)}
</text>
<text fg={theme.current.textMuted}>
{view().empty
? "in: --"
: `in: ${view().input.toLocaleString()}${view().hasSub ? ` (+${view().subInput.toLocaleString()})` : ""}`}
</text>
<text fg={theme.current.textMuted}>
{view().empty
? "out: --"
: `out: ${view().output.toLocaleString()}${view().hasSub ? ` (+${view().subOutput.toLocaleString()})` : ""}`}
</text>
<text fg={theme.current.textMuted}>
{view().empty || view().hit === undefined ? "hit: --" : `hit: ${view().hit?.toFixed(1)}%`}
</text>
{(quota()?.ok === true
? (quota() as Extract<QuotaResult, { ok: true }>).quota.windows
: []
).map((w) => {
const label = w.id === "fiveHour" ? "5h" : w.id === "weekly" ? "7d" : "mo";
const reset = formatReset(w.resetAtMs, now());
const amount =
w.id === "monthly" ? `$${w.used.toFixed(2)}/$${w.cap.toFixed(2)}` : `${percent(w.used, w.cap)}%`;
return (
<text
fg={
w.exceeded || percent(w.used, w.cap) >= 100
? theme.current.error
: percent(w.used, w.cap) >= 80
? theme.current.warning
: theme.current.success
}
>
{`${label} ${quotaBar(w.used, w.cap, 8)} ${amount}${reset ? ` · ${reset}` : ""}`}
</text>
);
})}
{errorOf(quota()) !== undefined ? (
<text fg={theme.current.error}>quota: {errorOf(quota())}</text>
) : quota() === null ? (
<text fg={theme.current.textMuted}>quota: loading…</text>
) : null}
<text fg={theme.current.textMuted}>
updated @ {updatedAt() > 0 ? new Date(updatedAt()).toTimeString().slice(0, 8) : "--:--:--"}
</text>
</box>
);
return <Status />;
},
},
});
@ -541,7 +589,7 @@ export const tui = async (api: TuiApi): Promise<void> => {
if (!apiKey) {
api.ui.toast({
title: CATEGORY,
message: `No API key found. Set provider.${PROVIDER_ID}.options.apiKey or COMMANDCODE_API_KEY.`,
message: "No API key found. Set provider.commandcode.options.apiKey or COMMANDCODE_API_KEY.",
variant: "warning",
});
return;
@ -571,13 +619,12 @@ export const tui = async (api: TuiApi): Promise<void> => {
});
void refreshQuota();
const toggleTimer = setInterval(() => setToggles(readToggles()), 1500);
const toggleTimer = setInterval(refresh, 1500);
const clockTimer = setInterval(() => setNow(Date.now()), 30_000);
const configIntervalMs = Number(safeEnv("COMMANDCODE_QUOTA_INTERVAL_MS"));
const quotaTimer = setInterval(() => {
void refreshQuota();
void refreshFamily(sessionId());
}, Number.isFinite(configIntervalMs) && configIntervalMs > 0 ? configIntervalMs : DEFAULT_QUOTA_INTERVAL_MS);
}, quotaIntervalMs());
const unsubs = QUOTA_TRIGGER_EVENTS.map((type) =>
api.event.on(type, (event) => {
scheduleQuotaRefresh(event?.type ?? type);

View File

@ -100,7 +100,7 @@ export function usageFromFinish(evt: FinishEvent): LanguageModelV3Usage {
const details = tu.inputTokenDetails ?? {};
const outDetails = tu.outputTokenDetails ?? {};
const cacheRead = tu.cachedInputTokens ?? details.cacheReadTokens;
// inputTokens.total is input-only; totalTokens is input+output.
// inputTokens.total is input-only (parity with server.py); totalTokens is input+output.
const total = tu.totalTokens ?? input + output;
return {
@ -143,7 +143,7 @@ function unify(value: string | undefined): LanguageModelV3FinishReason["unified"
}
}
/** CommandCode `finish` reason -> V3 finish reason. `rawFinishReason` is already OpenAI-spelled. */
/** Ported from server.py `finish_reason_from`. `rawFinishReason` is already OpenAI-spelled. */
export function finishReasonFrom(evt: FinishEvent, hadToolCalls: boolean): LanguageModelV3FinishReason {
const raw = evt.rawFinishReason;
const reason = evt.finishReason;

View File

@ -5,8 +5,6 @@
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"declaration": true,
"outDir": "dist",
"rootDir": "src",

View File

@ -6,8 +6,6 @@
"moduleResolution": "Bundler",
"types": ["node"],
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true,
"esModuleInterop": true,
@ -16,5 +14,5 @@
"jsx": "preserve",
"noEmit": true
},
"include": ["src/tui.tsx", "src/tui-shims.d.ts", "src/quota.ts", "src/toggles.ts", "src/log.ts", "src/redact.ts", "src/constants.ts"]
"include": ["src/tui.tsx", "src/tui-shims.d.ts", "src/quota.ts", "src/toggles.ts", "src/redact.ts", "src/constants.ts"]
}