From 2532df4963037f9b4c2e2d0989b43be9c4c5db02 Mon Sep 17 00:00:00 2001 From: "nhat.nguyenhong" Date: Sun, 18 Oct 2026 11:54:13 +0700 Subject: [PATCH] refactor, remove unused, remove deprecated server.py references --- AGENTS.md | 30 ++++++++++++------------------ README.md | 15 ++++----------- src/constants.ts | 4 ++-- src/model.ts | 2 +- src/redact.ts | 3 +-- src/transform.ts | 2 -- src/usage.ts | 4 ++-- tsconfig.json | 2 ++ tsconfig.tui.json | 2 ++ 9 files changed, 26 insertions(+), 38 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6e57b54..627d975 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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` 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 @@ -55,7 +51,6 @@ src/constants.ts Defaults, paths, headers, passthrough params, static config bl 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). -server.py Reference Python proxy (do not modify unless explicitly asked). ``` ## Architecture / data flow @@ -81,8 +76,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 `transform.ts` output in parity with `server.py` `transform()`. If you change the envelope, - explain which `server.py` behavior motivated it. +- Keep the `transform.ts` envelope stable. If you change it, document the upstream behavior that + motivated the change. - 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 @@ -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. 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 (parity with `server.py`); `totalTokens` is input+output. -7. **`supportedUrls` is `{}` and stays empty.** CommandsCode URLs are not fetched by the SDK. + `inputTokens.total` is input-only; `totalTokens` is input+output. +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 `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. `server.py` predates this requirement and is - not the guide here. + do not drop it and do not fabricate empty reasoning. 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 @@ -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 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 ` 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 without restarting opencode. Precedence for `zdr`: `providerOptions.commandcode-go.zdr` > `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/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 + `/alpha/usage/summary` (the same endpoints the `cmd` CLI `/usage` uses). `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 @@ -207,7 +201,7 @@ These are load-bearing. Breaking one causes silent failures in opencode. ## 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. 3. `npm run typecheck` — fix all errors. 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 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 @@ -245,7 +239,7 @@ replayed). Run it after touching `transform.ts` or the tool-call mapping in `mod ## 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** prefer `{env:COMMANDCODE_API_KEY}` in docs and examples. - **Don't** commit real API keys, `dist/`, `node_modules/`, `dump/`, or logs (all gitignored). diff --git a/README.md b/README.md index 328513c..05f50d7 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,8 @@ A native [AI SDK](https://ai-sdk.dev/) provider that connects [opencode](https://opencode.ai) to the **CommandCode** `/alpha/generate` API. -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. +This package implements the `LanguageModelV3` interface directly, so opencode talks to +CommandCode with no local proxy in the middle. ``` opencode ──► @ai-sdk/provider (LanguageModelV3) @@ -20,14 +18,10 @@ 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.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. ## 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 > 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. If you previously used `provider.commandcode` or `provider.opencc`, rename the key -> to `commandcode-go` (the `models` map is unchanged). +> model picker. Then set the key and restart opencode: diff --git a/src/constants.ts b/src/constants.ts index 1cc5a37..15a8310 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -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 // 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 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 = [ "temperature", "top_p", diff --git a/src/model.ts b/src/model.ts index 814a58a..9e08a92 100644 --- a/src/model.ts +++ b/src/model.ts @@ -26,7 +26,7 @@ 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). +// 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. function providerScoped(options: LanguageModelV3CallOptions): Record | undefined { diff --git a/src/redact.ts b/src/redact.ts index 87aa0e1..84876a9 100644 --- a/src/redact.ts +++ b/src/redact.ts @@ -1,5 +1,4 @@ -// 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 +// Credential redaction. Upstream error bodies can echo the caller's credentials and are // forwarded to the client, so scrub them first. const REDACT: Array<[RegExp, string]> = [ diff --git a/src/transform.ts b/src/transform.ts index 9b5d13d..9725bae 100644 --- a/src/transform.ts +++ b/src/transform.ts @@ -8,8 +8,6 @@ import { DEFAULT_MAX_TOKENS, PASSTHROUGH_PARAMS, PROVIDER_ID, STATIC_CONFIG } fr type ContentPart = Record; -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 : ""; diff --git a/src/usage.ts b/src/usage.ts index 130e1a4..35e17d7 100644 --- a/src/usage.ts +++ b/src/usage.ts @@ -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 (parity with server.py); totalTokens is input+output. + // inputTokens.total is input-only; totalTokens is input+output. const total = tu.totalTokens ?? input + output; 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 { const raw = evt.rawFinishReason; const reason = evt.finishReason; diff --git a/tsconfig.json b/tsconfig.json index 881a476..704cfed 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,6 +5,8 @@ "module": "NodeNext", "moduleResolution": "NodeNext", "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, "declaration": true, "outDir": "dist", "rootDir": "src", diff --git a/tsconfig.tui.json b/tsconfig.tui.json index faf9105..52d0298 100644 --- a/tsconfig.tui.json +++ b/tsconfig.tui.json @@ -6,6 +6,8 @@ "moduleResolution": "Bundler", "types": ["node"], "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, "noUncheckedIndexedAccess": true, "verbatimModuleSyntax": true, "esModuleInterop": true,