@brainervirus/opencode-commandcode 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.9.0] - 2026-09-26
11
+
10
12
  ## [0.8.0] - 2026-09-26
11
13
 
12
14
  ## [0.7.81] - 2026-09-26
package/README.md CHANGED
@@ -17,12 +17,23 @@ This package is based on **[FanFan4204/opencode-commandcode-provider](https://gi
17
17
  ### What this package adds
18
18
 
19
19
  - Bundled `models.json` is the default runtime catalog (no local CLI scrape).
20
- - CLI cost extraction can fail (as on `command-code@1.38.x`) without dropping models.
21
- - Official docs fill missing costs; remaining paid gaps use [models.dev](https://models.dev) as a reference. Command Code free SKUs stay `$0`.
20
+ - Dual OpenCode entry: V2 `setup` injects the provider plus models via transforms; V1 `server` fills `provider.commandcode` defaults plus models and registers API-key auth (auth stays V1-only).
21
+ - Validation at the boundaries via `src/schemas.ts` (zod): bundled `models.json` / `manifest.json` reads, provider availability payloads, and the plugin config file.
22
+ - CLI cost extraction can fail without dropping models; official docs fill missing costs, remaining paid gaps use [models.dev](https://models.dev) as a reference price at sync time. Command Code free SKUs stay `$0`.
22
23
  - Vision vs text-only comes from the Command Code CLI catalog (`inputModalities` on every SKU). [models.dev](https://models.dev) only adds extra inputs (video/audio/pdf) when it matches.
23
24
  - Reasoning effort **variants** on models that declare `reasoningEfforts`.
24
25
  - Quiet OpenCode startup (diagnostics go to `startup.json`, not stdout).
25
26
 
27
+ ## How it works
28
+
29
+ Each CI sync extracts the model catalog from the latest `command-code` npm bundle, merges costs, and commits versioned artifacts; at startup the plugin loads those artifacts and registers them with OpenCode — never the other way around.
30
+
31
+ - **Extract + filter** — model entries (ids, names, reasoning, `inputModalities`, limits) are evaluated out of the minified CLI bundle (`src/catalog.ts`), then intersected with the callable IDs reported by the provider API.
32
+ - **Costs merge** — per model, first hit wins: CLI bundle costs → official Command Code docs → free SKUs (`$0`) → [models.dev](https://models.dev) reference prices → unmatched placeholder. Anything still unmatched marks the catalog `degraded`. This runs at sync time only; runtime never fetches prices.
33
+ - **Artifacts** — `models.json` (the catalog), `_version.txt` (upstream version), `manifest.json` (counts, per-source cost stats, `healthy`/`degraded`/`broken` status).
34
+ - **V1 injection + V2 transform** — V1 `server()` fills `provider.commandcode` defaults and the models map; V2 `setup()` adds/updates the provider inventory (baseURL, API key binding) and sets models through `ctx.provider.transform`.
35
+ - **Degraded/cache fallbacks** — a `degraded`/`broken` manifest sets the degraded flag with a reason; an unreadable bundled `models.json` falls back to the last-good cache; auth/connect still registers even with an empty catalog.
36
+
26
37
  ## Quick Start
27
38
 
28
39
  ### 1. Install the plugin
@@ -33,33 +44,17 @@ This package is based on **[FanFan4204/opencode-commandcode-provider](https://gi
33
44
  }
34
45
  ```
35
46
 
36
- Pin a version instead of `@latest` if you do not want automatic catalog patches.
47
+ Pin a version instead of `@latest` if you do not want automatic catalog patches. The config key stays `plugin` in OpenCode V2 — there is no `plugins` key.
37
48
 
38
49
  `file://` checkouts are **not** updated by npm; `git pull` after CI commits, or switch to the npm plugin line.
39
50
 
40
- ### 2. Provider transport (Command Code Provider API)
51
+ ### 2. No provider block needed
41
52
 
42
- This plugin supplies model metadata. Point OpenCode at Command Code's documented Provider API:
43
-
44
- ```json
45
- {
46
- "plugin": ["@brainervirus/opencode-commandcode@latest"],
47
- "provider": {
48
- "commandcode": {
49
- "npm": "@ai-sdk/openai-compatible",
50
- "name": "Command Code GOAT",
51
- "env": ["COMMANDCODE_API_KEY"],
52
- "options": {
53
- "baseURL": "https://api.commandcode.ai/provider/v1"
54
- }
55
- }
56
- }
57
- }
58
- ```
53
+ On OpenCode V2 the plugin registers the `commandcode` provider itself (Provider API base URL plus `COMMANDCODE_API_KEY` binding) and its models. On V1 the `server` hook fills the same `provider.commandcode` defaults — `npm: "@ai-sdk/openai-compatible"` plus the Provider API `baseURL`; the plugin package itself is never the SDK `npm` field. Only add a manual `provider.commandcode` entry if you need non-default transport options.
59
54
 
60
55
  ### 3. Connect
61
56
 
62
- Run `/connect` in opencode, search for **Command Code**, and enter your API key, or set `COMMANDCODE_API_KEY`.
57
+ Set `COMMANDCODE_API_KEY`, or on OpenCode V1 run `/connect`, search for **Command Code**, and enter your API key. V2 registers the provider with the env binding; the `/connect` API-key method is V1-only.
63
58
 
64
59
  ### 4. Select a model
65
60
 
@@ -67,6 +62,18 @@ Run `/connect` in opencode, search for **Command Code**, and enter your API key,
67
62
  /models
68
63
  ```
69
64
 
65
+ Catalog patches arrive as plugin updates: `@latest` refreshes in the background and takes effect on the next OpenCode restart. If a new model is missing after an announced sync, restart opencode once.
66
+
67
+ ## Plugin config file
68
+
69
+ Optional, `~/.config/opencode/opencode-commandcode.json` (legacy fallback name `commandcode-go-opencode-provider.json` still loads). Unknown keys are ignored; every field has a default.
70
+
71
+ | Key | Default | Effect |
72
+ |---|---|---|
73
+ | `commandCodePackagePath` | `""` | Maintainer override: extract the catalog from a local `command-code` checkout instead of the bundle. Same as env `COMMANDCODE_PACKAGE_PATH`. |
74
+ | `debugStartupLogs` | `false` | Also mirror the startup summary to stderr. Default is quiet (`startup.json` only). |
75
+ | `disableModelSync` | `false` | Accepted for forward compatibility; currently has no effect. |
76
+
70
77
  ## Optional local CLI override
71
78
 
72
79
  Maintainers only. OpenCode will scrape a local `command-code` install when `COMMANDCODE_PACKAGE_PATH` or `commandCodePackagePath` in `~/.config/opencode/opencode-commandcode.json` is set.
@@ -77,16 +84,24 @@ Maintainers only. OpenCode will scrape a local `command-code` install when `COMM
77
84
  git clone https://github.com/BrainerVirus/opencode-commandcode.git
78
85
  cd opencode-commandcode
79
86
  bun install
80
- bun run check # oxlint + oxfmt + bun test + tsc (same stack as workit)
87
+ bun run check # oxlint + oxfmt --check + bun test tests/unit/ + tsc (the release gate)
81
88
  ```
82
89
 
83
90
  ```bash
84
- bun run sync -- --remote # refresh models.json + manifest.json from command-code@latest
91
+ bun run sync -- --remote # refresh models.json + manifest.json + _version.txt from command-code@latest
92
+ bun run build # bundle src/entry.ts to dist/plugin.js
93
+ bun test tests/unit/ # unit suite (also via bun run test)
94
+ bun run test:integration # live-endpoint tests, not part of the gate
95
+ bun run verify:release-candidate # dry-run pack; manifest and package versions must match
96
+ bun run generate-readme # reports catalog counts only; README is hand-edited
97
+ bun run catalog:ci # entry used by the catalog-sync workflow
85
98
  ```
86
99
 
87
- CI (`.github/workflows/catalog-sync.yml`) opens a PR every 6 hours when Command Code ships a new catalog. That PR, and the post-release `chore/manifest-sync-v*` PR, auto-merge after **check (test)**, **check (typecheck)**, **check (lint)**, **check (format)**, and **check (pack)** are green. `.github/workflows/release.yml` then runs **semantic-release** (npm publish + GitHub Release + tag). Do not push to `main`.
100
+ Entry points: `plugin.ts` owns all config-hook logic (dual default `{ id, setup }` plus `server`); `index.ts` re-exports the plugin plus the `createCommandCode` SDK factory; `src/entry.ts` is bundle glue for `scripts/build-plugin.ts` only — it produces `dist/plugin.js`.
101
+
102
+ CI (`.github/workflows/catalog-sync.yml`) opens a `fix(catalog)` PR every 6 hours when Command Code ships a new catalog; if extraction fails it opens a `catalog-break` issue instead. The PR auto-merges after **check (test)**, **check (typecheck)**, **check (lint)**, **check (format)**, and **check (pack)** are green. `.github/workflows/release.yml` then runs **semantic-release** (npm publish + GitHub Release + tag). Do not push to `main`.
88
103
 
89
- The GitHub Actions secret name is `NPMJS` (same as workit). It is mapped to both `NPM_TOKEN` and `NODE_AUTH_TOKEN`. Use an npm **Automation** token (bypasses 2FA). A login token from `~/.npmrc` fails CI with `EOTP`. Catalog PRs get a real CI run when `RELEASE_SYNC_TOKEN` (or `CATALOG_PUSH_TOKEN`) is a PAT; `GITHUB_TOKEN` can open the PR but GitHub will not start workflows from that event.
104
+ The GitHub Actions secret name is `NPMJS`. It is mapped to both `NPM_TOKEN` and `NODE_AUTH_TOKEN`. Use an npm **Automation** token (bypasses 2FA). A login token from `~/.npmrc` fails CI with `EOTP`. Catalog PRs get a real CI run when `RELEASE_SYNC_TOKEN` is a PAT; `GITHUB_TOKEN` can open the PR but GitHub will not start workflows from that event.
90
105
 
91
106
  ## License
92
107
 
package/manifest.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "generatedAt": "2026-09-26T06:01:17.803Z",
4
- "pluginVersion": "0.8.0",
4
+ "pluginVersion": "0.9.0",
5
5
  "commandCodeVersion": "1.66.0",
6
6
  "commandCodeTarball": "https://registry.npmjs.org/command-code/-/command-code-1.66.0.tgz",
7
7
  "modelCount": 82,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brainervirus/opencode-commandcode",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Command Code API provider for opencode — use Claude, GPT, Gemini, DeepSeek, Qwen, Kimi, GLM, MiniMax, and Step models via Command Code",
5
5
  "keywords": [
6
6
  "ai",
@@ -73,18 +73,21 @@
73
73
  "sync:global": "bun run scripts/sync-models.ts --update-global",
74
74
  "catalog:ci": "bun run scripts/catalog-sync-ci.ts"
75
75
  },
76
+ "dependencies": {
77
+ "zod": "4.6.5"
78
+ },
76
79
  "devDependencies": {
77
80
  "@semantic-release/exec": "7.1.0",
78
- "@semantic-release/github": "12.0.9",
79
- "@semantic-release/npm": "13.1.5",
81
+ "@semantic-release/github": "12.0.10",
82
+ "@semantic-release/npm": "13.2.0",
80
83
  "@semantic-release/release-notes-generator": "14.1.1",
81
- "@types/bun": "1.4.0",
82
- "@types/node": "^25.9.1",
83
- "ai": "6.0.191",
84
- "oxfmt": "0.63.0",
85
- "oxlint": "1.78.0",
84
+ "@types/bun": "1.4.2",
85
+ "@types/node": "25.9.8",
86
+ "ai": "7.0.114",
87
+ "oxfmt": "0.70.0",
88
+ "oxlint": "1.85.0",
86
89
  "semantic-release": "25.0.9",
87
- "typescript": "^6.0.3"
90
+ "typescript": "6.0.3"
88
91
  },
89
92
  "peerDependencies": {
90
93
  "ai": ">=6.0.0"
package/plugin.ts CHANGED
@@ -1,76 +1,112 @@
1
1
  import { readFileSync, existsSync } from "fs";
2
- import { homedir } from "os";
3
2
  import { join } from "path";
3
+ import { z } from "zod";
4
4
  import {
5
5
  generateOpencodeModels,
6
- loadCatalogFromLocalCommandCode,
6
+ loadCatalogFromLocalCommandCodeResult,
7
7
  type ModelEntry,
8
8
  } from "./src/catalog.js";
9
- import {
10
- readCatalogCache,
11
- writeCatalogCache,
12
- writeStartupSummary,
13
- pluginStateDir,
14
- } from "./src/startup.js";
9
+ import { readCatalogCacheResult, writeCatalogCache, writeStartupSummary } from "./src/startup.js";
10
+ import { liveEnv, resolveStateDir, type EnvDeps } from "./src/env.js";
11
+ import { causeMessage, errResult, okResult, type LoadResult } from "./src/load-result.js";
15
12
  import type { CatalogManifest } from "./src/manifest.js";
16
13
  import { generateV2Models } from "./src/v2models.js";
17
14
  import { catalogPaths } from "./src/paths.js";
15
+ import { ManifestSchema, ModelEntrySchema, PluginFileConfigSchema } from "./src/schemas.js";
18
16
 
19
17
  const { models: MODELS_PATH, manifest: MANIFEST_PATH, version: VERSION_PATH } = catalogPaths();
20
18
 
21
- interface PluginFileConfig {
22
- disableModelSync?: boolean;
23
- commandCodePackagePath?: string;
24
- debugStartupLogs?: boolean;
25
- }
19
+ // Transport decision (docs/2026-08-28-ci-catalog/spec.md:20): OpenAI-compatible AI SDK +
20
+ // Provider API; this package is the plugin, never the SDK `npm` field. V1 takes the bare
21
+ // npm name; the `aisdk:` prefix is V2-only.
22
+ const PROVIDER_SDK_NPM = "@ai-sdk/openai-compatible";
23
+ const PROVIDER_API_BASE_URL = "https://api.commandcode.ai/provider/v1";
24
+
25
+ type PluginFileConfig = z.infer<typeof PluginFileConfigSchema>;
26
26
 
27
- function loadPluginConfig(): PluginFileConfig {
28
- const dir = join(homedir(), ".config", "opencode");
27
+ function loadPluginConfig(deps: EnvDeps = liveEnv): PluginFileConfig {
28
+ const dir = join(deps.homedir(), ".config", "opencode");
29
29
  const configPath = [
30
30
  join(dir, "opencode-commandcode.json"),
31
31
  join(dir, "commandcode-go-opencode-provider.json"),
32
32
  ].find((p) => existsSync(p));
33
- if (!configPath) return {};
33
+ if (!configPath) return PluginFileConfigSchema.parse({});
34
+ let raw: unknown = {};
34
35
  try {
35
- return JSON.parse(readFileSync(configPath, "utf-8"));
36
+ raw = JSON.parse(readFileSync(configPath, "utf-8")) as unknown;
36
37
  } catch {
37
- return {};
38
+ raw = {};
38
39
  }
40
+ const parsed = PluginFileConfigSchema.safeParse(raw);
41
+ return parsed.success ? parsed.data : PluginFileConfigSchema.parse({});
39
42
  }
40
43
 
41
44
  export type { ModelEntry };
42
45
 
43
- function loadBundledModels(): ModelEntry[] | null {
46
+ type BundledModels = { models: ModelEntry[]; dropped: number; dropReasons: string[] };
47
+
48
+ /** Explicit bundled read: parsed models plus the reason when unavailable. */
49
+ function loadBundledModels(): LoadResult<BundledModels> {
50
+ let raw: string;
44
51
  try {
45
- return JSON.parse(readFileSync(MODELS_PATH, "utf-8"));
46
- } catch {
47
- return null;
52
+ raw = readFileSync(MODELS_PATH, "utf-8");
53
+ } catch (error) {
54
+ return errResult(`bundled models.json unreadable: ${causeMessage(error)}`);
48
55
  }
56
+ let parsed: unknown;
57
+ try {
58
+ parsed = JSON.parse(raw) as unknown;
59
+ } catch (error) {
60
+ return errResult(`bundled models.json invalid JSON: ${causeMessage(error)}`);
61
+ }
62
+ if (!Array.isArray(parsed)) return errResult("bundled models.json is not an array");
63
+ const models: ModelEntry[] = [];
64
+ const dropReasons: string[] = [];
65
+ for (let index = 0; index < parsed.length; index++) {
66
+ const result = ModelEntrySchema.safeParse(parsed[index]);
67
+ if (result.success) models.push(result.data);
68
+ else if (dropReasons.length < 3) {
69
+ const detail = result.error.issues.map((issue) => issue.message).join("; ");
70
+ dropReasons.push(`entry ${index}: ${detail}`);
71
+ }
72
+ }
73
+ return okResult({ models, dropped: parsed.length - models.length, dropReasons });
49
74
  }
50
75
 
51
- function readBundledManifest(): CatalogManifest | null {
52
- if (!existsSync(MANIFEST_PATH)) return null;
76
+ /** Explicit manifest read: `ok(null)` is a missing file (version falls back). */
77
+ function readBundledManifest(): LoadResult<CatalogManifest | null> {
78
+ if (!existsSync(MANIFEST_PATH)) return okResult(null);
79
+ let parsed: unknown;
53
80
  try {
54
- return JSON.parse(readFileSync(MANIFEST_PATH, "utf-8")) as CatalogManifest;
55
- } catch {
56
- return null;
81
+ parsed = JSON.parse(readFileSync(MANIFEST_PATH, "utf-8")) as unknown;
82
+ } catch (error) {
83
+ return errResult(`bundled manifest.json unreadable: ${causeMessage(error)}`);
84
+ }
85
+ const result = ManifestSchema.safeParse(parsed);
86
+ if (!result.success) {
87
+ const detail = result.error.issues.map((issue) => issue.message).join("; ");
88
+ return errResult(`bundled manifest.json invalid: ${detail}`);
57
89
  }
90
+ return okResult(result.data);
58
91
  }
59
92
 
60
- function readBundledVersion(): string | null {
93
+ /** Explicit version read: manifest first, `_version.txt` fallback, else a reason. */
94
+ function readBundledVersion(): LoadResult<string | null> {
61
95
  const manifest = readBundledManifest();
62
- if (manifest?.commandCodeVersion) return manifest.commandCodeVersion;
63
- if (!existsSync(VERSION_PATH)) return null;
96
+ if (manifest.ok && manifest.value?.commandCodeVersion) {
97
+ return okResult(manifest.value.commandCodeVersion);
98
+ }
99
+ if (!existsSync(VERSION_PATH)) return errResult("version file missing");
64
100
  try {
65
- const parts = readFileSync(VERSION_PATH, "utf-8").split("\n");
66
- const first = parts[0]?.trim();
67
- return first || null;
68
- } catch {
69
- return null;
101
+ const first = readFileSync(VERSION_PATH, "utf-8").split("\n")[0]?.trim();
102
+ if (!first) return errResult("version file empty");
103
+ return okResult(first);
104
+ } catch (error) {
105
+ return errResult(`version file unreadable: ${causeMessage(error)}`);
70
106
  }
71
107
  }
72
108
 
73
- type CatalogLoad = {
109
+ export type CatalogLoad = {
74
110
  models: ModelEntry[];
75
111
  catalogSource: "bundled" | "cache" | "opt-in-local";
76
112
  commandCodeVersion: string | null;
@@ -78,61 +114,93 @@ type CatalogLoad = {
78
114
  degradedReason: string | null;
79
115
  };
80
116
 
81
- function loadCatalogEntries(): CatalogLoad {
82
- const pluginCfg = loadPluginConfig();
117
+ export function loadCatalogEntries(deps: EnvDeps = liveEnv): CatalogLoad {
118
+ const pluginCfg = loadPluginConfig(deps);
83
119
  const override =
84
- pluginCfg.commandCodePackagePath?.trim() || process.env.COMMANDCODE_PACKAGE_PATH?.trim() || "";
120
+ pluginCfg.commandCodePackagePath?.trim() ||
121
+ deps.getEnv("COMMANDCODE_PACKAGE_PATH")?.trim() ||
122
+ "";
85
123
 
86
124
  let models: ModelEntry[] = [];
87
125
  let catalogSource: CatalogLoad["catalogSource"] = "bundled";
88
126
  let commandCodeVersion: string | null = null;
89
127
  let degraded = false;
90
- let degradedReason: string | null = null;
128
+ const reasons: string[] = [];
91
129
 
92
130
  if (override) {
93
- const localCatalog = loadCatalogFromLocalCommandCode({ packagePath: override });
94
- if (localCatalog && localCatalog.models.length > 0) {
95
- models = localCatalog.models;
131
+ const local = loadCatalogFromLocalCommandCodeResult({ packagePath: override }, deps);
132
+ if (local.ok && local.value && local.value.models.length > 0) {
133
+ models = local.value.models;
96
134
  catalogSource = "opt-in-local";
97
- commandCodeVersion = localCatalog.version;
135
+ commandCodeVersion = local.value.version;
136
+ } else if (!local.ok) {
137
+ reasons.push(`local override failed (${local.reason})`);
138
+ } else {
139
+ reasons.push("local override produced no models");
98
140
  }
99
141
  }
100
142
 
101
143
  if (models.length === 0) {
102
144
  const bundled = loadBundledModels();
103
- if (bundled) {
104
- models = bundled;
145
+ if (bundled.ok) {
146
+ models = bundled.value.models;
105
147
  catalogSource = "bundled";
106
- commandCodeVersion = readBundledVersion();
148
+ const version = readBundledVersion();
149
+ commandCodeVersion = version.ok ? version.value : null;
107
150
  const manifest = readBundledManifest();
108
- if (manifest?.status === "degraded" || manifest?.status === "broken") {
151
+ if (
152
+ manifest.ok &&
153
+ manifest.value &&
154
+ (manifest.value.status === "degraded" || manifest.value.status === "broken")
155
+ ) {
109
156
  degraded = true;
110
- degradedReason =
111
- manifest.status === "broken"
157
+ reasons.push(
158
+ manifest.value.status === "broken"
112
159
  ? "bundled catalog marked broken"
113
- : "bundled catalog has models with no listed price";
160
+ : "bundled catalog has models with no listed price",
161
+ );
162
+ }
163
+ if (bundled.value.dropped > 0) {
164
+ degraded = true;
165
+ const details =
166
+ bundled.value.dropReasons.length > 0 ? `: ${bundled.value.dropReasons.join("; ")}` : "";
167
+ reasons.push(
168
+ `dropped ${bundled.value.dropped} invalid bundled model ${bundled.value.dropped === 1 ? "entry" : "entries"}${details}`,
169
+ );
114
170
  }
115
171
  } else {
116
- const cached = readCatalogCache();
117
- if (cached) {
118
- models = cached;
172
+ const cached = readCatalogCacheResult(undefined, deps);
173
+ if (cached.ok) {
174
+ models = cached.value;
119
175
  catalogSource = "cache";
120
176
  degraded = true;
121
- degradedReason = "bundled models.json unreadable; using last-good cache";
177
+ reasons.push(`bundled models.json failed (${bundled.reason}); using last-good cache`);
122
178
  } else {
123
179
  degraded = true;
124
- degradedReason = "no bundled catalog and no cache";
180
+ reasons.push(`no bundled catalog (${bundled.reason}) and no cache (${cached.reason})`);
125
181
  }
126
182
  }
127
183
  }
128
184
 
129
- return { models, catalogSource, commandCodeVersion, degraded, degradedReason };
185
+ // Override notes only sharpen an already-degraded report; a healthy
186
+ // bundled load stays non-degraded exactly as before.
187
+ return {
188
+ models,
189
+ catalogSource,
190
+ commandCodeVersion,
191
+ degraded,
192
+ degradedReason: degraded ? reasons.join("; ") : null,
193
+ };
130
194
  }
131
195
 
132
- function persistCatalogSideEffects(load: CatalogLoad, debug: boolean): void {
196
+ function persistCatalogSideEffects(
197
+ load: CatalogLoad,
198
+ debug: boolean,
199
+ deps: EnvDeps = liveEnv,
200
+ ): void {
133
201
  if (load.models.length > 0) {
134
202
  try {
135
- writeCatalogCache(pluginStateDir(), load.models);
203
+ writeCatalogCache(resolveStateDir(deps), load.models);
136
204
  } catch {
137
205
  // ignore cache write
138
206
  }
@@ -147,7 +215,7 @@ function persistCatalogSideEffects(load: CatalogLoad, debug: boolean): void {
147
215
  degradedReason: load.degradedReason,
148
216
  };
149
217
  try {
150
- writeStartupSummary(pluginStateDir(), summary);
218
+ writeStartupSummary(resolveStateDir(deps), summary);
151
219
  } catch {
152
220
  // ignore
153
221
  }
@@ -171,9 +239,19 @@ export async function server() {
171
239
  const pluginCfg = loadPluginConfig();
172
240
  const debug = pluginCfg.debugStartupLogs === true;
173
241
 
174
- if (!cc.npm) cc.npm = "commandcode-go-opencode-provider";
242
+ if (!cc.npm) cc.npm = PROVIDER_SDK_NPM;
175
243
  if (!cc.name) cc.name = "Command Code";
176
244
  if (!cc.env) cc.env = ["COMMANDCODE_API_KEY"];
245
+ // V1 resolves `npm` through BunProc.install and calls the first `create*` export, so
246
+ // the SDK package must be the OpenAI-compatible one; give it the Provider API URL
247
+ // unless the user already configured another baseURL (custom npm stays untouched).
248
+ if (cc.npm === PROVIDER_SDK_NPM) {
249
+ if (cc.options === undefined) cc.options = {};
250
+ if (typeof cc.options === "object" && cc.options !== null) {
251
+ const options = cc.options as Record<string, unknown>;
252
+ if (!options.baseURL) options.baseURL = PROVIDER_API_BASE_URL;
253
+ }
254
+ }
177
255
 
178
256
  if (cc.models) return;
179
257
 
@@ -227,9 +305,9 @@ async function setup(ctx: any): Promise<void> {
227
305
  id: "commandcode",
228
306
  name: "Command Code",
229
307
  activation: "enabled",
230
- package: "aisdk:@ai-sdk/openai-compatible",
308
+ package: `aisdk:${PROVIDER_SDK_NPM}`,
231
309
  settings: {
232
- baseURL: "https://api.commandcode.ai/provider/v1",
310
+ baseURL: PROVIDER_API_BASE_URL,
233
311
  apiKey: "{env:COMMANDCODE_API_KEY}",
234
312
  },
235
313
  },
@@ -241,8 +319,7 @@ async function setup(ctx: any): Promise<void> {
241
319
  provider.name = provider.name ?? "Command Code";
242
320
  provider.settings = provider.settings ?? {};
243
321
  if (typeof provider.settings === "object") {
244
- if (!provider.settings.baseURL)
245
- provider.settings.baseURL = "https://api.commandcode.ai/provider/v1";
322
+ if (!provider.settings.baseURL) provider.settings.baseURL = PROVIDER_API_BASE_URL;
246
323
  if (!provider.settings.apiKey) provider.settings.apiKey = "{env:COMMANDCODE_API_KEY}";
247
324
  }
248
325
  });
package/src/catalog.ts CHANGED
@@ -2,22 +2,14 @@ import { createRequire } from "module";
2
2
  import { execSync } from "child_process";
3
3
  import { existsSync, readFileSync, statSync } from "fs";
4
4
  import { dirname, join, resolve as resolvePath } from "path";
5
- import { fileURLToPath } from "url";
5
+ import { z } from "zod";
6
+ import { AvailabilityPayloadSchema, ModelEntrySchema } from "./schemas.js";
7
+ import { liveEnv, type EnvDeps } from "./env.js";
8
+ import { causeMessage, errResult, okResult, type LoadResult } from "./load-result.js";
6
9
 
7
10
  export const NPM_PACKAGE = "command-code";
8
11
 
9
- export interface ModelEntry {
10
- id: string;
11
- name: string;
12
- tier: "premium" | "open-source";
13
- reasoning: boolean;
14
- reasoningEfforts?: string[];
15
- tool_call: boolean;
16
- cost: { input: number; output: number; cache_read?: number; cache_write?: number };
17
- limit: { context: number; output: number };
18
- attachment?: boolean;
19
- modalities?: { input: string[]; output: string[] };
20
- }
12
+ export type ModelEntry = z.infer<typeof ModelEntrySchema>;
21
13
 
22
14
  export interface CostEntry {
23
15
  id: string;
@@ -259,18 +251,6 @@ export function extractBestProviderEnum(
259
251
  return fallback;
260
252
  }
261
253
 
262
- export function extractWt(source: string): Record<string, string> {
263
- const best = extractBestProviderEnum(source);
264
- if (!best) throw new Error(`Anchor not found: ANTHROPIC:"anthropic"`);
265
- return best.value;
266
- }
267
-
268
- export function getWtVarName(source: string): string {
269
- const best = extractBestProviderEnum(source);
270
- if (!best) throw new Error("Could not find Wt enum");
271
- return best.name;
272
- }
273
-
274
254
  /** Collect nearby `name="value"` bindings and simple aliases (`tI=Qx`). */
275
255
  export function extractStringBindings(
276
256
  source: string,
@@ -701,17 +681,20 @@ function tryNpmRootGlobal(): ResolvedCommandCodePackage | null {
701
681
  }
702
682
  }
703
683
 
704
- function tryWindowsAppData(): ResolvedCommandCodePackage | null {
705
- const appData = process.env.APPDATA;
684
+ function tryWindowsAppData(deps: EnvDeps = liveEnv): ResolvedCommandCodePackage | null {
685
+ const appData = deps.getEnv("APPDATA");
706
686
  if (!appData) return null;
707
687
  return asPackageRoot(join(appData, "npm", "node_modules", NPM_PACKAGE));
708
688
  }
709
689
 
710
- export function resolveCommandCodePackage(options?: {
711
- packagePath?: string;
712
- }): ResolvedCommandCodePackage | null {
690
+ export function resolveCommandCodePackage(
691
+ options?: {
692
+ packagePath?: string;
693
+ },
694
+ deps: EnvDeps = liveEnv,
695
+ ): ResolvedCommandCodePackage | null {
713
696
  const explicit =
714
- options?.packagePath?.trim() || process.env.COMMANDCODE_PACKAGE_PATH?.trim() || "";
697
+ options?.packagePath?.trim() || deps.getEnv("COMMANDCODE_PACKAGE_PATH")?.trim() || "";
715
698
 
716
699
  if (explicit) {
717
700
  const found = asPackageRoot(explicit);
@@ -722,26 +705,60 @@ export function resolveCommandCodePackage(options?: {
722
705
  tryRequireResolve() ||
723
706
  walkNodeModules(process.cwd()) ||
724
707
  tryNpmRootGlobal() ||
725
- tryWindowsAppData() ||
708
+ tryWindowsAppData(deps) ||
726
709
  null
727
710
  );
728
711
  }
729
712
 
713
+ /**
714
+ * Explicit local-catalog load: `ok(null)` means no package was found to try
715
+ * (opt-in unused or undiscoverable — not a failure), `err` carries the
716
+ * reason an attempted load failed, `ok(result)` is a usable catalog.
717
+ */
718
+ export function loadCatalogFromLocalCommandCodeResult(
719
+ options?: {
720
+ packagePath?: string;
721
+ },
722
+ deps: EnvDeps = liveEnv,
723
+ ): LoadResult<LocalCatalogResult | null> {
724
+ try {
725
+ const resolved = resolveCommandCodePackage(options, deps);
726
+ if (!resolved) return okResult(null);
727
+ let source: string;
728
+ try {
729
+ source = readFileSync(resolved.bundlePath, "utf-8");
730
+ } catch (error) {
731
+ return errResult(
732
+ `local command-code bundle unreadable (${resolved.bundlePath}): ${causeMessage(error)}`,
733
+ );
734
+ }
735
+ let models: ModelEntry[];
736
+ try {
737
+ models = loadCatalogFromBundle(source);
738
+ } catch (error) {
739
+ return errResult(`local command-code catalog failed to evaluate: ${causeMessage(error)}`);
740
+ }
741
+ if (models.length === 0) return errResult("local command-code catalog empty");
742
+ return okResult({
743
+ models,
744
+ version: resolved.version,
745
+ root: resolved.root,
746
+ bundleSource: source,
747
+ });
748
+ } catch (error) {
749
+ return errResult(`local command-code load failed: ${causeMessage(error)}`);
750
+ }
751
+ }
752
+
753
+ /** Compat wrapper: value-or-null for callers that only need fail-open. */
730
754
  export function loadCatalogFromLocalCommandCode(options?: {
731
755
  packagePath?: string;
732
756
  }): LocalCatalogResult | null {
733
- try {
734
- const resolved = resolveCommandCodePackage(options);
735
- if (!resolved) return null;
736
- const source = readFileSync(resolved.bundlePath, "utf-8");
737
- const models = loadCatalogFromBundle(source);
738
- if (models.length === 0) return null;
739
- return { models, version: resolved.version, root: resolved.root, bundleSource: source };
740
- } catch {
741
- return null;
742
- }
757
+ const result = loadCatalogFromLocalCommandCodeResult(options);
758
+ return result.ok ? result.value : null;
743
759
  }
744
760
 
761
+ /** Short OpenCode map / UI key. Wire id stays the catalog `entry.id` (vendor/…). */
745
762
  export function toConfigKey(id: string): string {
746
763
  const slashIdx = id.indexOf("/");
747
764
  const short = slashIdx >= 0 ? id.slice(slashIdx + 1) : id;
@@ -751,6 +768,7 @@ export function toConfigKey(id: string): string {
751
768
  export function generateOpencodeModels(entries: ModelEntry[]): Record<string, unknown> {
752
769
  const models: Record<string, unknown> = {};
753
770
  for (const entry of entries) {
771
+ // Map key = short UI id; `id` on the model = Command Code wire id (same split as V2 modelID).
754
772
  const key = toConfigKey(entry.id);
755
773
  const costObj: Record<string, number> = { input: entry.cost.input, output: entry.cost.output };
756
774
  if (entry.cost.cache_read !== undefined) costObj.cache_read = entry.cost.cache_read;
@@ -788,36 +806,14 @@ export interface FilteredCatalog<T extends { id: string }> {
788
806
  unavailable: string[];
789
807
  }
790
808
 
791
- function isNonEmptyString(value: unknown): value is string {
792
- return typeof value === "string" && value.length > 0;
793
- }
794
-
795
809
  /** Validate the OpenAI-style `{ object: "list", data: [{ id }] }` availability payload. */
796
810
  export function parseAvailabilityIds(payload: unknown): string[] {
797
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
798
- throw new Error("availability response must be an object");
799
- }
800
- const body = payload as Record<string, unknown>;
801
- if (body["object"] !== "list") throw new Error('availability response object must be "list"');
802
- const data = body["data"];
803
- if (!Array.isArray(data) || data.length === 0) {
804
- throw new Error("availability response data must be a non-empty array");
811
+ const parsed = AvailabilityPayloadSchema.safeParse(payload);
812
+ if (!parsed.success) {
813
+ const detail = parsed.error.issues.map((issue) => issue.message).join("; ");
814
+ throw new Error(`invalid availability response: ${detail}`);
805
815
  }
806
- const ids: string[] = [];
807
- const seen = new Set<string>();
808
- for (const item of data) {
809
- if (!item || typeof item !== "object" || Array.isArray(item)) {
810
- throw new Error("availability response items must be objects with a non-empty string id");
811
- }
812
- const id = (item as Record<string, unknown>)["id"];
813
- if (!isNonEmptyString(id)) {
814
- throw new Error("availability response items must be objects with a non-empty string id");
815
- }
816
- if (seen.has(id)) throw new Error(`duplicate availability id: ${id}`);
817
- seen.add(id);
818
- ids.push(id);
819
- }
820
- return ids;
816
+ return parsed.data.data.map((item) => item.id);
821
817
  }
822
818
 
823
819
  /** Retain only candidates whose exact ID is callable; collect sorted excluded IDs. */
@@ -833,7 +829,3 @@ export function filterCatalogByAvailability<T extends { id: string }>(
833
829
  .sort();
834
830
  return { retained, unavailable };
835
831
  }
836
-
837
- export function catalogModuleDir(): string {
838
- return dirname(fileURLToPath(import.meta.url));
839
- }
package/src/env.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { homedir as osHomedir } from "os";
2
+ import { join } from "path";
3
+
4
+ /**
5
+ * Hermetic seam for environment access. Runtime code takes an optional
6
+ * `deps` parameter defaulting to `liveEnv`, so existing call sites behave
7
+ * identically while tests inject fakes instead of juggling `process.env`.
8
+ * Filesystem calls stay direct; only environment reads go through here.
9
+ */
10
+ export type EnvDeps = {
11
+ homedir: () => string;
12
+ getEnv: (key: string) => string | undefined;
13
+ };
14
+
15
+ export const liveEnv: EnvDeps = {
16
+ homedir: () => osHomedir(),
17
+ getEnv: (key) => process.env[key],
18
+ };
19
+
20
+ /** Plugin state directory: explicit override wins, otherwise under home. */
21
+ export function resolveStateDir(deps: EnvDeps = liveEnv): string {
22
+ const override = deps.getEnv("COMMANDCODE_PROVIDER_STATE_DIR")?.trim();
23
+ if (override) return override;
24
+ return join(deps.homedir(), ".local/state/opencode/commandcode-provider");
25
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Explicit load result: a value on success, a human-readable reason when
3
+ * there is none. Load boundaries return this instead of catching everything
4
+ * and yielding `null`, so callers can thread the reason into degraded
5
+ * reporting instead of guessing which read failed.
6
+ */
7
+ export type LoadResult<T> = { ok: true; value: T } | { ok: false; reason: string };
8
+
9
+ export function okResult<T>(value: T): LoadResult<T> {
10
+ return { ok: true, value };
11
+ }
12
+
13
+ export function errResult<T>(reason: string): LoadResult<T> {
14
+ return { ok: false, reason };
15
+ }
16
+
17
+ /** One-line summary of a caught value for embedding in a reason string. */
18
+ export function causeMessage(cause: unknown): string {
19
+ if (cause instanceof Error && cause.message) return cause.message;
20
+ if (typeof cause === "string" && cause) return cause;
21
+ return "unknown error";
22
+ }
package/src/manifest.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { writeFileSync } from "fs";
2
+ import { z } from "zod";
3
+ import { ManifestSchema } from "./schemas.js";
2
4
 
3
5
  export type CatalogStatus = "healthy" | "degraded" | "broken";
4
6
  export type CostCatalogBest = "cli" | "docs" | "thirdParty" | "free" | "fallback" | "missing";
@@ -24,23 +26,7 @@ export type CatalogReview = {
24
26
  unavailable?: UnavailableEntry[];
25
27
  };
26
28
 
27
- export type CatalogManifest = {
28
- schemaVersion: 1;
29
- generatedAt: string;
30
- pluginVersion: string;
31
- commandCodeVersion: string;
32
- commandCodeTarball: string;
33
- modelCount: number;
34
- reasoningModelCount: number;
35
- extraction: {
36
- modelCatalog: "ok" | "failed";
37
- costCatalog: CostCatalogBest;
38
- costCatalogError: string | null;
39
- };
40
- costSources: CostSources;
41
- review?: CatalogReview;
42
- status: CatalogStatus;
43
- };
29
+ export type CatalogManifest = z.infer<typeof ManifestSchema>;
44
30
 
45
31
  export type BuildManifestInput = {
46
32
  pluginVersion: string;
@@ -82,7 +68,6 @@ export function bumpPatch(version: string): string {
82
68
 
83
69
  export function meetsModelCountFloor(modelCount: number, lastSuccessful: number | null): boolean {
84
70
  const floor = Math.max(20, Math.floor((lastSuccessful ?? 20) * 0.5));
85
- // ponytail: when there is no prior catalog, lastSuccessful is null and the floor is 20
86
71
  return modelCount >= (lastSuccessful === null ? 20 : floor);
87
72
  }
88
73
 
@@ -163,10 +148,3 @@ export function countCostSources(input: {
163
148
  }
164
149
  return sources;
165
150
  }
166
-
167
- export function bumpPackageVersionField(pkgJson: string): { json: string; version: string } {
168
- const pkg = JSON.parse(pkgJson) as { version: string };
169
- const version = bumpPatch(pkg.version);
170
- const json = pkgJson.replace(/("version"\s*:\s*")([^"]+)(")/, `$1${version}$3`);
171
- return { json, version };
172
- }
package/src/schemas.ts ADDED
@@ -0,0 +1,103 @@
1
+ import { z } from "zod";
2
+
3
+ /** Canonical catalog model entry. Single source of truth — src/catalog.ts derives its ModelEntry type from here via z.infer; never redeclare the shape there. */
4
+ export const ModelEntrySchema = z.strictObject({
5
+ id: z.string().min(1),
6
+ name: z.string().min(1),
7
+ tier: z.enum(["premium", "open-source"]),
8
+ reasoning: z.boolean(),
9
+ reasoningEfforts: z.array(z.string()).optional(),
10
+ tool_call: z.boolean(),
11
+ cost: z.strictObject({
12
+ input: z.number(),
13
+ output: z.number(),
14
+ cache_read: z.number().optional(),
15
+ cache_write: z.number().optional(),
16
+ }),
17
+ limit: z.strictObject({
18
+ context: z.number().int(),
19
+ output: z.number().int(),
20
+ }),
21
+ attachment: z.boolean().optional(),
22
+ modalities: z
23
+ .strictObject({
24
+ input: z.array(z.string()),
25
+ output: z.array(z.string()),
26
+ })
27
+ .optional(),
28
+ });
29
+
30
+ /** Canonical catalog manifest. Single source of truth — src/manifest.ts derives its CatalogManifest type from here via z.infer; never redeclare the shape there. */
31
+ export const ManifestSchema = z.strictObject({
32
+ schemaVersion: z.literal(1),
33
+ generatedAt: z.string(),
34
+ pluginVersion: z.string(),
35
+ commandCodeVersion: z.string(),
36
+ commandCodeTarball: z.string(),
37
+ modelCount: z.number().int(),
38
+ reasoningModelCount: z.number().int(),
39
+ extraction: z.strictObject({
40
+ modelCatalog: z.enum(["ok", "failed"]),
41
+ costCatalog: z.enum(["cli", "docs", "thirdParty", "free", "fallback", "missing"]),
42
+ costCatalogError: z.string().nullable(),
43
+ }),
44
+ costSources: z.strictObject({
45
+ cli: z.number().int(),
46
+ officialDocs: z.number().int(),
47
+ thirdParty: z.number().int(),
48
+ free: z.number().int(),
49
+ fallback: z.number().int(),
50
+ unmatched: z.number().int(),
51
+ }),
52
+ review: z
53
+ .strictObject({
54
+ thirdParty: z.array(z.string()),
55
+ free: z.array(z.string()),
56
+ unmatched: z.array(z.string()),
57
+ unavailable: z
58
+ .array(
59
+ z.strictObject({
60
+ id: z.string(),
61
+ reason: z.literal("not-listed-by-provider-api"),
62
+ }),
63
+ )
64
+ .optional(),
65
+ })
66
+ .optional(),
67
+ status: z.enum(["healthy", "degraded", "broken"]),
68
+ });
69
+
70
+ /**
71
+ * OpenAI-style `{ object: "list", data: [{ id }] }` availability payload.
72
+ * Items stay lenient (the provider API returns extra per-model fields);
73
+ * duplicate ids are rejected.
74
+ */
75
+ export const AvailabilityPayloadSchema = z
76
+ .object({
77
+ object: z.literal("list"),
78
+ data: z.array(z.object({ id: z.string().min(1) })).min(1),
79
+ })
80
+ .superRefine((payload, ctx) => {
81
+ const seen = new Set<string>();
82
+ for (const item of payload.data) {
83
+ if (seen.has(item.id)) {
84
+ ctx.addIssue({
85
+ code: "custom",
86
+ message: `duplicate availability id: ${item.id}`,
87
+ });
88
+ return;
89
+ }
90
+ seen.add(item.id);
91
+ }
92
+ });
93
+
94
+ /**
95
+ * Plugin file config (`~/.config/opencode/opencode-commandcode.json`).
96
+ * Deliberately lenient: user config files may carry extra keys, so unknown
97
+ * keys are stripped and every field falls back to its default.
98
+ */
99
+ export const PluginFileConfigSchema = z.object({
100
+ disableModelSync: z.boolean().optional().default(false),
101
+ commandCodePackagePath: z.string().optional().default(""),
102
+ debugStartupLogs: z.boolean().optional().default(false),
103
+ });
package/src/startup.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
2
- import { homedir } from "os";
3
2
  import { join } from "path";
4
3
  import type { ModelEntry } from "./catalog.js";
4
+ import { liveEnv, resolveStateDir, type EnvDeps } from "./env.js";
5
+ import { causeMessage, errResult, okResult, type LoadResult } from "./load-result.js";
5
6
 
6
7
  export type { ModelEntry } from "./catalog.js";
7
8
 
@@ -14,22 +15,35 @@ export type StartupSummary = {
14
15
  degradedReason: string | null;
15
16
  };
16
17
 
17
- export function pluginStateDir(): string {
18
- const override = process.env.COMMANDCODE_PROVIDER_STATE_DIR?.trim();
19
- if (override) return override;
20
- return join(homedir(), ".local/state/opencode/commandcode-provider");
18
+ export function pluginStateDir(deps: EnvDeps = liveEnv): string {
19
+ return resolveStateDir(deps);
21
20
  }
22
21
 
23
- export function readCatalogCache(dir = pluginStateDir()): ModelEntry[] | null {
24
- const path = join(dir, "catalog-cache.json");
25
- if (!existsSync(path)) return null;
22
+ /**
23
+ * Explicit cache read: hit yields the models, anything else yields the
24
+ * reason (missing file, empty/invalid content, unreadable JSON).
25
+ */
26
+ export function readCatalogCacheResult(
27
+ dir?: string,
28
+ deps: EnvDeps = liveEnv,
29
+ ): LoadResult<ModelEntry[]> {
30
+ const cacheDir = dir ?? resolveStateDir(deps);
31
+ const path = join(cacheDir, "catalog-cache.json");
32
+ if (!existsSync(path)) return errResult("catalog cache missing");
33
+ let parsed: unknown;
26
34
  try {
27
- const parsed = JSON.parse(readFileSync(path, "utf-8")) as unknown;
28
- if (!Array.isArray(parsed) || parsed.length === 0) return null;
29
- return parsed as ModelEntry[];
30
- } catch {
31
- return null;
35
+ parsed = JSON.parse(readFileSync(path, "utf-8")) as unknown;
36
+ } catch (error) {
37
+ return errResult(`catalog cache unreadable: ${causeMessage(error)}`);
32
38
  }
39
+ if (!Array.isArray(parsed) || parsed.length === 0) return errResult("catalog cache empty");
40
+ return okResult(parsed as ModelEntry[]);
41
+ }
42
+
43
+ /** Compat wrapper: explicit-dir callers that only need value-or-null. */
44
+ export function readCatalogCache(dir?: string, deps: EnvDeps = liveEnv): ModelEntry[] | null {
45
+ const result = readCatalogCacheResult(dir, deps);
46
+ return result.ok ? result.value : null;
33
47
  }
34
48
 
35
49
  export function writeCatalogCache(dir: string, models: ModelEntry[]): void {
package/src/v2models.ts CHANGED
@@ -29,10 +29,12 @@ function v2Output(entry: ModelEntry): string[] {
29
29
  }
30
30
 
31
31
  export function toV2Model(entry: ModelEntry): V2Model {
32
+ // UI / OpenCode selection key stays short (commandcode/deepseek-v4.1-flash).
33
+ // modelID is the Command Code wire id — bare names 400 as unsupported_model.
32
34
  const id = toConfigKey(entry.id);
33
35
  return {
34
36
  id,
35
- modelID: id,
37
+ modelID: entry.id,
36
38
  providerID: "commandcode",
37
39
  name: entry.name,
38
40
  capabilities: {