diff --git a/AGENTS.md b/AGENTS.md index 2de7a42..c66c720 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,7 +23,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-go.models (models + reasoning-effort variants) ``` There is no unit-test suite. `scripts/smoke.mjs` is the end-to-end check. `scripts/sync-models.mjs` @@ -50,7 +50,7 @@ tsconfig.tui.json Typechecks src/tui.tsx (+ quota/toggles/log) against the shim src/constants.ts Defaults, paths, headers, 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/sync-models.mjs Catalog -> provider.commandcode-go.models generator (vision + reasoning-effort probing). scripts/opencode-config.mjs Shared opencode config/key lookup for the dev scripts. ``` @@ -199,6 +199,28 @@ These are load-bearing. Breaking one causes silent failures in opencode. 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`. +19. **Reasoning effort: request options beat the provider default.** opencode merges + `provider..models..options` ← `agent..options` ← the selected variant and + passes the result as `providerOptions[model.providerID]` — for a `file://` npm spec the + `sdkKey()` lookup in opencode's provider transform returns undefined and the key falls back to + the provider id (`commandcode-go`; verified in opencode 1.18.35 + `session/llm/request.ts` + `provider/transform.ts`). `transform.ts` reads both + `reasoningEffort` and `reasoning_effort` (`resolveReasoningEffort`) and forwards + `params.reasoning_effort` **unvalidated** — an effort the upstream model does not support + fails the whole request, which is intentional and also the signal `sync-models` probes with. + `provider.commandcode-go.options.reasoningEffort` (`reasoning_effort` alias) reaches + `createCommandCode` because opencode's `resolveSDK` spreads `{ ...provider.options }` into the + factory call; it is only a fallback when the request carries no effort. The resolved value is + logged as `effort=` in the debug trace. +20. **Variants are config-only.** opencode's built-in reasoning presets + (`ProviderTransform.variants()`) return `{}` for unknown npm packages, and the TUI hides + `/variants` entirely when the server-side `model.variants` is empty. Custom `file://` + providers are only ever asked for `languageModel(id)` (see invariant 12), so there is no + provider-side variant registration hook: reasoning-effort switching exists only if + `provider.commandcode-go.models..variants` is present in opencode.json. + `scripts/sync-models.mjs` probes `low/medium/high/xhigh/max` per model (tier accepted = tiny + request completes) and writes the verified tiers, never overwriting user-defined variants; + unreachable models get a static fallback set, reachable-but-effort-less models get none. ## Change workflow diff --git a/README.md b/README.md index 027135e..e87818c 100644 --- a/README.md +++ b/README.md @@ -123,9 +123,17 @@ Mapping and behaviour: temporarily unavailable — fall back to a family heuristic (`claude`, `gpt-5`, `gemini`, `grok`, `qwen…vl`, …). Probing is best-effort: upstream is nondeterministic and a re-run may flip a borderline model. +- Reasoning effort (`variants`) is **probed** per model: a tiny request is sent for each candidate + tier (`low`, `medium`, `high`, `xhigh`, `max`) carrying `reasoningEffort`, and a tier counts as + supported when the request completes (an unsupported tier fails the request, which is the + signal). Verified tiers are written as `variants` (e.g. `"high": { "reasoningEffort": "high" }`) + so opencode's `/variants` switcher works. If every tier is rejected, a no-effort baseline probe + decides: a reachable model gets no variants at all; an unreachable or plan-gated model falls + back to a static guess (`low`/`medium`/`high`, plus `max` for `deepseek-v4`). Probing is skipped + for ids that already carry user-defined variants — those are preserved as-is. - Generated fields (`name`, `limit`, `reasoning`, `attachment`, `modalities`) overwrite existing - values. Other fields (`variants`, `options`, `cost`, …) on selected ids are preserved. - Unselected ids are removed from the map. + values. `variants` are written only when the entry has none; other fields (`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 global config (`baseURL`/`ccVersion` are read from there too). @@ -143,6 +151,7 @@ global config (`baseURL`/`ccVersion` are read from there too). | `ccVersion` | `string` | `1.84.0` | Value of the `x-command-code-version` header. | | `maxRetries` | `number` | `2` | Retry attempts for retryable failures (429/5xx/network). | | `retryMaxDelaySeconds` | `number` | `60` | Longest wait honoured from `Retry-After`; longer values are not retried. | +| `reasoningEffort` | `string` | — | Provider-level default reasoning effort, sent as `params.reasoning_effort` (`reasoning_effort` is an accepted alias). Model/agent options and a selected variant override it — see [Reasoning effort](#reasoning-effort). | | `name` | `string` | `commandcode-go` | Provider id reported to the AI SDK. opencode sets this automatically. | **Auth precedence:** `options.apiKey` wins; otherwise the value of an `Authorization` header in @@ -301,7 +310,7 @@ The API key is never logged; quota errors pass through `redact()` like every oth | Provider-reported cost | Yes — per-request USD from `finish-step`/`provider-metadata` is forwarded as `providerMetadata.commandcode-go.cost` (plus `marketCost`); also stashed in `usage.raw`. The built-in sidebar still shows `$0.00` until opencode itself consumes this field (upstream `anomalyco/opencode#43818`); `/cc-usage` remains the accurate dollar source | | Finish reasons | Yes — unified (`stop`, `length`, `tool-calls`, `content-filter`, `error`, `other`) plus raw | | Sampling parameters | Yes — `temperature`, `topP`, `topK`, `stopSequences`, `seed`, presence/frequency penalties | -| `reasoning_effort` | Yes — via `providerOptions.commandcode-go` | +| `reasoning_effort` | Yes — provider default via `options.reasoningEffort`; per request via model/agent options or `providerOptions.commandcode-go.reasoningEffort`; switchable per message through `/variants` / `--variant` (variants generated by `sync-models`) | | Retry with backoff | Yes — 429/5xx and network errors, honouring `Retry-After`; also retryable `error` events that arrive inside an HTTP 200 stream before any content (gateway 520s) | | Credential redaction | Yes — error bodies are scrubbed before surfacing | | Runtime toggles | Yes — `/cc-zdr` and `/cc-debug` flip the shared toggle file without a restart | @@ -320,15 +329,48 @@ values accordingly: ### Reasoning effort -Set the per-request reasoning effort through provider options: +The effort reaches CommandCode as `params.reasoning_effort`. Four config layers are available, +most specific wins: + +| Layer | opencode.json location | Notes | +| --- | --- | --- | +| Selected variant | `provider..models..variants.` | Switched per message via `/variants`, the variant-cycle keybind, or `opencode run --variant ` — no restart needed | +| Agent | `agent..options.reasoningEffort` (or `agent..variant`) | Applies to that agent only | +| Model default | `provider..models..options.reasoningEffort` | Every request for that model | +| Provider default | `provider..options.reasoningEffort` | Fallback when nothing more specific is set | ```jsonc -// opencode model options / variant -"options": { "providerOptions": { "commandcode-go": { "reasoningEffort": "high" } } } +// opencode.json +{ + "provider": { + "commandcode-go": { + "options": { "reasoningEffort": "medium" }, + "models": { + "deepseek/deepseek-v4.1-flash": { + "options": { "reasoningEffort": "low" }, + "variants": { + "low": { "reasoningEffort": "low" }, + "high": { "reasoningEffort": "high" } + } + } + } + } + } +} ``` -Both `reasoning_effort` and `reasoningEffort` keys are recognised and forwarded as -`params.reasoning_effort`. +Notes: + +- `reasoning_effort` is accepted as a key alias at every layer (request options and the + provider default). +- Values are forwarded **unvalidated**: an effort the upstream model does not support fails the + request. Run `npm run sync-models` to probe which tiers each model actually accepts and write + the verified ones as variants. +- Variants must exist in config for `/variants` to appear — opencode ships no built-in variants + for custom `file://` providers, and a custom provider cannot register variants itself + (see [Listing all CommandCode models](#listing-all-commandcode-models)). +- Config edits need a restart; selecting a different variant does not (it is resolved per + message). With `/cc-debug` enabled, each request logs an `effort=` line. ## How it works @@ -409,6 +451,8 @@ opencode run "Use the glob tool to list *.mjs and report the filenames." -m comm | Need to see what the provider sends/receives | Flip `/cc-debug` and read the appended log file (see [Debug tracing](#debug-tracing)). | | `tool_choice` seemingly ignored | Expected for `required`; upstream cannot force a call. `none` and named-tool are emulated via the tool list. | | Config change had no effect | opencode reads config once at startup. Restart it. | +| `/variants` missing or only shows "Default" | The model has no `variants` in config. Run `npm run sync-models` (probes tiers live) or add `variants` manually, then restart opencode. | +| Reasoning-effort change has no effect | Check the selected variant and the config key spelling (`reasoningEffort`), then look for the `effort=` line in the debug log. Config edits need a restart; variant switches do not. An effort the upstream model rejects fails the request by design. | | `/cc-*` commands and the sidebar panel are missing | TUI plugin not registered: add a direct `file://` URL to `src/tui.tsx` in `tui.json` (see [Runtime toggles](#runtime-toggles)). A repo-root or `src/tui.tsx`-less entry does not load. | ## Security diff --git a/src/model.ts b/src/model.ts index 7d2bf7e..095a06e 100644 --- a/src/model.ts +++ b/src/model.ts @@ -23,7 +23,7 @@ import { iterateEvents } from "./events.js"; import { debugWhen, isDebugEnabled } from "./log.js"; import { redact } from "./redact.js"; import { zdrEnabled } from "./toggles.js"; -import { transform } from "./transform.js"; +import { resolveReasoningEffort, transform } from "./transform.js"; import { finishReasonFrom, usageFromFinish, costFromFinishStep, costFromProviderMetadata, type FinishEvent, type FinishStepEvent, type ProviderMetadataEvent } from "./usage.js"; function providerScoped(options: LanguageModelV3CallOptions): Record | undefined { @@ -43,6 +43,10 @@ export type CommandCodeOptions = { ccVersion?: string; maxRetries?: number; retryMaxDelaySeconds?: number; + /** Provider-level default reasoning effort; per-request providerOptions (incl. a selected variant) override it. */ + reasoningEffort?: string; + /** Alias for `reasoningEffort`, mirroring the request-level key spelling. */ + reasoning_effort?: string; }; type ResolvedOptions = { @@ -53,6 +57,7 @@ type ResolvedOptions = { ccVersion: string; maxRetries: number; retryMaxDelay: number; + reasoningEffort?: string; }; function headerValue(headers: Record, key: string): string | undefined { @@ -289,8 +294,18 @@ class CommandCodeLanguageModel implements LanguageModelV3 { async doStream(options: LanguageModelV3CallOptions): Promise { const dbg = resolveDebug(options); - const body = transform(options, this.modelId); - debugWhen(dbg, "doStream", `model=${this.modelId}`, `bodyBytes=${Buffer.byteLength(body, "utf8")}`); + const body = transform(options, this.modelId, { + providerId: this.opts.providerId, + reasoningEffort: this.opts.reasoningEffort, + }); + const effort = resolveReasoningEffort(options, this.opts.providerId, this.opts.reasoningEffort); + debugWhen( + dbg, + "doStream", + `model=${this.modelId}`, + `effort=${effort === undefined ? "default" : String(effort)}`, + `bodyBytes=${Buffer.byteLength(body, "utf8")}`, + ); const { response, prefix, events } = await this.fetchWithRetry(body, options, dbg); if (!response.ok || !response.body) { let responseBody = ""; @@ -570,6 +585,7 @@ export function createCommandCode(options: CommandCodeOptions = {}): { ccVersion: options.ccVersion ?? DEFAULT_CC_VERSION, maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES, retryMaxDelay: options.retryMaxDelaySeconds ?? DEFAULT_RETRY_MAX_DELAY, + reasoningEffort: options.reasoningEffort ?? options.reasoning_effort, }; return { languageModel(modelId: string) { diff --git a/src/transform.ts b/src/transform.ts index f000347..56d9876 100644 --- a/src/transform.ts +++ b/src/transform.ts @@ -16,8 +16,27 @@ function stringify(value: unknown): string { } } +/** + * Resolves the reasoning effort for a request: per-request `providerOptions[providerId]` + * (model/agent options and the selected variant, merged by opencode) win over the + * provider-level default. Both key spellings are accepted; the value is forwarded + * unvalidated — an effort upstream does not support fails the request. + */ +export function resolveReasoningEffort( + options: LanguageModelV3CallOptions, + providerId: string = PROVIDER_ID, + fallback?: unknown, +): unknown { + const scoped = options.providerOptions?.[providerId] as Record | undefined; + return scoped?.["reasoning_effort"] ?? scoped?.["reasoningEffort"] ?? fallback; +} + /** AI SDK call options -> CommandCode `/alpha/generate` envelope (JSON string). */ -export function transform(options: LanguageModelV3CallOptions, modelId: string): string { +export function transform( + options: LanguageModelV3CallOptions, + modelId: string, + defaults: { providerId?: string; reasoningEffort?: unknown } = {}, +): string { const systemParts: string[] = []; const messages: Array> = []; @@ -215,8 +234,7 @@ 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 | undefined; - const effort = scoped?.["reasoning_effort"] ?? scoped?.["reasoningEffort"]; + const effort = resolveReasoningEffort(options, defaults.providerId ?? PROVIDER_ID, defaults.reasoningEffort); if (effort !== undefined) params["reasoning_effort"] = effort; const plat = typeof process !== "undefined" ? `${process.platform}-${process.arch}` : "unknown";