refactor, remove unused, remove deprecated server.py references

This commit is contained in:
nhat.nguyenhong 2026-10-18 11:54:13 +07:00
parent 3a8412f28d
commit 2532df4963
9 changed files with 26 additions and 38 deletions

View File

@ -8,10 +8,6 @@ Instructions for LLM coding agents working in this repository.
CommandCode `/alpha/generate` API. It implements `LanguageModelV3` from `@ai-sdk/provider@3.0.8` 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. 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`. - Language/tooling: TypeScript, ESM, `tsc`.
- Runtime target: opencode's provider loader, `@ai-sdk/provider@3.0.8` (V3 specification). - 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 - No runtime dependencies. `@ai-sdk/provider` is imported with `import type` only; the built
@ -55,7 +51,6 @@ src/constants.ts Defaults, paths, headers, passthrough params, static config bl
scripts/smoke.mjs Live end-to-end check. scripts/smoke.mjs Live end-to-end check.
scripts/quota.mjs Print the live quota headlessly (reads the same config as smoke). scripts/quota.mjs Print the live quota headlessly (reads the same config as smoke).
scripts/sync-models.mjs Catalog -> provider.commandcode-go.models generator (with vision probing). scripts/sync-models.mjs Catalog -> provider.commandcode-go.models generator (with vision probing).
server.py Reference Python proxy (do not modify unless explicitly asked).
``` ```
## Architecture / data flow ## Architecture / data flow
@ -81,8 +76,8 @@ opencode
Type-only imports must use `import type`. Type-only imports must use `import type`.
- Do **not** add comments unless they explain a non-obvious decision. Existing comments document - Do **not** add comments unless they explain a non-obvious decision. Existing comments document
upstream quirks and are intentional; match that spirit, not volume. upstream quirks and are intentional; match that spirit, not volume.
- Keep `transform.ts` output in parity with `server.py` `transform()`. If you change the envelope, - Keep the `transform.ts` envelope stable. If you change it, document the upstream behavior that
explain which `server.py` behavior motivated it. motivated the change.
- Preserve the single public factory `createCommandCode`. `index.ts` re-exports it as both a named - Preserve the single public factory `createCommandCode`. `index.ts` re-exports it as both a named
and the default export. and the default export.
- The package must stay runtime-dependency-free. Do not add a runtime `import` of a package that - The package must stay runtime-dependency-free. Do not add a runtime `import` of a package that
@ -107,15 +102,14 @@ These are load-bearing. Breaking one causes silent failures in opencode.
be omitted from the envelope; upstream rejects the whole request otherwise. be omitted from the envelope; upstream rejects the whole request otherwise.
6. **Usage is nested in V3.** Fill `inputTokens.{total,noCache,cacheRead,cacheWrite}` and 6. **Usage is nested in V3.** Fill `inputTokens.{total,noCache,cacheRead,cacheWrite}` and
`outputTokens.{total,text,reasoning}` — not flat `promptTokens`/`completionTokens`. `outputTokens.{total,text,reasoning}` — not flat `promptTokens`/`completionTokens`.
`inputTokens.total` is input-only (parity with `server.py`); `totalTokens` is input+output. `inputTokens.total` is input-only; `totalTokens` is input+output.
7. **`supportedUrls` is `{}` and stays empty.** CommandsCode URLs are not fetched by the SDK. 7. **`supportedUrls` is `{}` and stays empty.** CommandCode URLs are not fetched by the SDK.
8. **Redact before surfacing errors.** Any upstream error text passed to the client must go through 8. **Redact before surfacing errors.** Any upstream error text passed to the client must go through
`redact()`. `redact()`.
9. **Replay assistant reasoning as a `{type:"reasoning"}` content part.** DeepSeek thinking mode 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 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?}`; `transform.ts`, forward each assistant `reasoning` part as `{type:"reasoning", text, signature?}`;
do not drop it and do not fabricate empty reasoning. `server.py` predates this requirement and is do not drop it and do not fabricate empty reasoning.
not the guide here.
10. **Upstream cost never appears on `finish`.** Per-request USD arrives on `finish-step` 10. **Upstream cost never appears on `finish`.** Per-request USD arrives on `finish-step`
(`usage.raw.cost/market_cost/gateway_cost`, numbers) and `provider-metadata` (`usage.raw.cost/market_cost/gateway_cost`, numbers) and `provider-metadata`
(`providerMetadata.gateway.cost/marketCost`, strings). `finish.totalUsage` carries tokens (`providerMetadata.gateway.cost/marketCost`, strings). `finish.totalUsage` carries tokens
@ -131,7 +125,7 @@ These are load-bearing. Breaking one causes silent failures in opencode.
`provider.commandcode-go.models` in `opencode.json` and never asks a custom `file://` provider to `provider.commandcode-go.models` in `opencode.json` and never asks a custom `file://` provider to
discover models (only internal providers can register `discoverModels`). Refresh the map with discover models (only internal providers can register `discoverModels`). Refresh the map with
`npm run sync-models`; do not expect a discovery hook in `src/` to populate it. `npm run sync-models`; do not expect a discovery hook in `src/` to populate it.
13. **The TUI plugin lives outside the provider entrypoint.** `src/tui.tsx` is loaded from 13. **The TUI plugin lives outside the provider entrypoint.** `src/tui.tsx` is loaded from
**source** (not `dist/`) via a `tui.json` `plugin` entry that must be a **direct `file://` URL **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`), 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` wired by hand: `opencode plugin <path>` cannot install a bare `.tsx` (it needs a `package.json`
@ -174,10 +168,10 @@ These are load-bearing. Breaking one causes silent failures in opencode.
`model.ts`/`log.ts` on every call from the toggle file, so `/cc-*` changes take effect `model.ts`/`log.ts` on every call from the toggle file, so `/cc-*` changes take effect
without restarting opencode. Precedence for `zdr`: `providerOptions.commandcode-go.zdr` > without restarting opencode. Precedence for `zdr`: `providerOptions.commandcode-go.zdr` >
`x-cmd-zdr` header > toggle file. Do not reintroduce load-time consts. `x-cmd-zdr` header > toggle file. Do not reintroduce load-time consts.
16. **Quota is live from the alpha billing API, not `server.py`.** `src/quota.ts` reads 16. **Quota is live from the alpha billing API.** `src/quota.ts` reads
`/alpha/whoami`, `/alpha/billing/credits`, `/alpha/billing/subscriptions`, and `/alpha/whoami`, `/alpha/billing/credits`, `/alpha/billing/subscriptions`, and
`/alpha/usage/summary` (the same endpoints the `cmd` CLI `/usage` uses). `server.py` predates `/alpha/usage/summary` (the same endpoints the `cmd` CLI `/usage` uses). `resetAt` has shipped
these and is not the guide here. `resetAt` has shipped as both seconds and epoch ms — normalize as both seconds and epoch ms — normalize
(>= 1e12 = ms). The monthly meter is **derived** (spend + remaining credits), so it works on any (>= 1e12 = ms). The monthly meter is **derived** (spend + remaining credits), so it works on any
plan; never hardcode a plan→cap table. The TUI resolves the key from `api.state` (provider plan; never hardcode a plan→cap table. The TUI resolves the key from `api.state` (provider
entry, then `config.provider.commandcode-go.options`, then `COMMANDCODE_API_KEY`), expanding entry, then `config.provider.commandcode-go.options`, then `COMMANDCODE_API_KEY`), expanding
@ -207,7 +201,7 @@ These are load-bearing. Breaking one causes silent failures in opencode.
## Change workflow ## Change workflow
1. Read `server.py` for the behavior being ported and note the relevant function. 1. Identify the upstream behavior and the `src/` module that implements it.
2. Make the smallest change in the matching `src/` file. 2. Make the smallest change in the matching `src/` file.
3. `npm run typecheck` — fix all errors. 3. `npm run typecheck` — fix all errors.
4. `npm run build`. 4. `npm run build`.
@ -216,7 +210,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 7. Update `README.md` if options, features, or behavior changed. Keep `AGENTS.md` invariants
current if you discover a new one. current if you discover a new one.
Do not edit `dist/` by hand; it is generated. Do not modify `server.py` unless explicitly asked. Do not edit `dist/` by hand; it is generated.
## Verification ## Verification
@ -245,7 +239,7 @@ replayed). Run it after touching `transform.ts` or the tool-call mapping in `mod
## Do / Don't ## Do / Don't
- **Do** keep the wire envelope identical to `server.py`. - **Do** keep the wire envelope stable; document intentional changes.
- **Do** run typecheck, build, and smoke after every source change. - **Do** run typecheck, build, and smoke after every source change.
- **Do** prefer `{env:COMMANDCODE_API_KEY}` in docs and examples. - **Do** prefer `{env:COMMANDCODE_API_KEY}` in docs and examples.
- **Don't** commit real API keys, `dist/`, `node_modules/`, `dump/`, or logs (all gitignored). - **Don't** commit real API keys, `dist/`, `node_modules/`, `dump/`, or logs (all gitignored).

View File

@ -3,10 +3,8 @@
A native [AI SDK](https://ai-sdk.dev/) provider that connects [opencode](https://opencode.ai) A native [AI SDK](https://ai-sdk.dev/) provider that connects [opencode](https://opencode.ai)
to the **CommandCode** `/alpha/generate` API. to the **CommandCode** `/alpha/generate` API.
It is the TypeScript successor to the `server.py` proxy in this directory. Where the proxy This package implements the `LanguageModelV3` interface directly, so opencode talks to
exposed an OpenAI-compatible `/v1/chat/completions` endpoint that opencode reached with CommandCode with no local proxy in the middle.
`@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) opencode ──► @ai-sdk/provider (LanguageModelV3)
@ -20,14 +18,10 @@ opencode ──► @ai-sdk/provider (LanguageModelV3)
api.commandcode.ai 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 ## Requirements
- **Node.js >= 18** (uses global `fetch`, `ReadableStream`, `TextDecoder`, `structuredClone`). - **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.30). - **opencode >= 1.17** that ships `@ai-sdk/provider@3.0.8` (verified against opencode 1.18.35).
- A CommandCode account and API key with access to the `/alpha/generate` endpoint. - A CommandCode account and API key with access to the `/alpha/generate` endpoint.
## Install and wire into opencode ## Install and wire into opencode
@ -72,8 +66,7 @@ npm run build
> entry of the same id and forwards the catalog `api` URL as `options.baseURL`, which breaks this > 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 > 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 > avoids the merge; list the official provider under `disabled_providers` so it stays out of the
> model picker. If you previously used `provider.commandcode` or `provider.opencc`, rename the key > model picker.
> to `commandcode-go` (the `models` map is unchanged).
Then set the key and restart opencode: Then set the key and restart opencode:

View File

@ -1,4 +1,4 @@
// Shared constants. Ported from server.py so the wire shape stays identical. // Wire-format constants for the CommandCode /alpha/generate API.
// The provider id must not collide with a models.dev catalog id: opencode merges the // 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` // catalog entry for a config-defined provider with the same id and forwards its `api`
@ -18,7 +18,7 @@ export const DEFAULT_MAX_RETRIES = 2;
export const BASE_RETRY_DELAY = 0.5; export const BASE_RETRY_DELAY = 0.5;
export const DEFAULT_RETRY_MAX_DELAY = 60; export const DEFAULT_RETRY_MAX_DELAY = 60;
// Sampling knobs CommandCode accepts (probed individually in server.py). Forwarded verbatim. // Sampling knobs CommandCode accepts. Forwarded verbatim.
export const PASSTHROUGH_PARAMS = [ export const PASSTHROUGH_PARAMS = [
"temperature", "temperature",
"top_p", "top_p",

View File

@ -26,7 +26,7 @@ import { zdrEnabled } from "./toggles.js";
import { transform } from "./transform.js"; import { transform } from "./transform.js";
import { finishReasonFrom, usageFromFinish, costFromFinishStep, costFromProviderMetadata, type FinishEvent, type FinishStepEvent, type ProviderMetadataEvent } from "./usage.js"; import { finishReasonFrom, usageFromFinish, costFromFinishStep, costFromProviderMetadata, type FinishEvent, type FinishStepEvent, type ProviderMetadataEvent } from "./usage.js";
// x-cmd-zdr breaks some models; off by default (server.py never sends it). // x-cmd-zdr breaks some models; off by default.
// Precedence: providerOptions["commandcode-go"].zdr > x-cmd-zdr header > toggle file. // Precedence: providerOptions["commandcode-go"].zdr > x-cmd-zdr header > toggle file.
// "undefined" means the header is omitted entirely. // "undefined" means the header is omitted entirely.
function providerScoped(options: LanguageModelV3CallOptions): Record<string, unknown> | undefined { function providerScoped(options: LanguageModelV3CallOptions): Record<string, unknown> | undefined {

View File

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

View File

@ -8,8 +8,6 @@ import { DEFAULT_MAX_TOKENS, PASSTHROUGH_PARAMS, PROVIDER_ID, STATIC_CONFIG } fr
type ContentPart = Record<string, unknown>; type ContentPart = Record<string, unknown>;
type ToolCallRef = { id: string; name: string };
function environmentInfo(): string { function environmentInfo(): string {
const plat = typeof process !== "undefined" ? `${process.platform}-${process.arch}` : "unknown"; const plat = typeof process !== "undefined" ? `${process.platform}-${process.arch}` : "unknown";
const ver = typeof process !== "undefined" && process.version ? process.version : ""; const ver = typeof process !== "undefined" && process.version ? process.version : "";

View File

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

View File

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

View File

@ -6,6 +6,8 @@
"moduleResolution": "Bundler", "moduleResolution": "Bundler",
"types": ["node"], "types": ["node"],
"strict": true, "strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noUncheckedIndexedAccess": true, "noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true, "verbatimModuleSyntax": true,
"esModuleInterop": true, "esModuleInterop": true,