@brainervirus/opencode-commandcode 0.7.81 → 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 +4 -0
- package/README.md +41 -26
- package/index.ts +4 -0
- package/manifest.json +1 -1
- package/package.json +22 -15
- package/plugin.ts +250 -114
- package/src/catalog.ts +65 -73
- package/src/entry.ts +3 -0
- package/src/env.ts +25 -0
- package/src/load-result.ts +22 -0
- package/src/manifest.ts +3 -25
- package/src/paths.ts +43 -0
- package/src/schemas.ts +103 -0
- package/src/startup.ts +27 -13
- package/src/v2models.ts +68 -0
package/CHANGELOG.md
CHANGED
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
|
-
-
|
|
21
|
-
-
|
|
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.
|
|
51
|
+
### 2. No provider block needed
|
|
41
52
|
|
|
42
|
-
|
|
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
|
-
|
|
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 (
|
|
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
|
-
|
|
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
|
|
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/index.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { resolveApiKey } from "./src/auth.js";
|
|
2
2
|
import { CommandCodeLanguageModel } from "./src/model.js";
|
|
3
3
|
|
|
4
|
+
// Re-export the plugin definition so a directory plugin entry (<dir>/index.ts)
|
|
5
|
+
// loads the dual V1+V2 plugin. No cycle: plugin.ts only imports from src/.
|
|
6
|
+
export { default, server } from "./plugin.js";
|
|
7
|
+
|
|
4
8
|
export interface CommandCodeProviderOptions {
|
|
5
9
|
name?: string;
|
|
6
10
|
apiKey?: string;
|
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.
|
|
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.
|
|
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",
|
|
@@ -29,30 +29,34 @@
|
|
|
29
29
|
"url": "git+https://github.com/BrainerVirus/opencode-commandcode.git"
|
|
30
30
|
},
|
|
31
31
|
"files": [
|
|
32
|
-
"
|
|
33
|
-
"plugin.ts",
|
|
32
|
+
"dist/",
|
|
34
33
|
"models.json",
|
|
35
34
|
"manifest.json",
|
|
36
35
|
"_version.txt",
|
|
37
36
|
"README.md",
|
|
38
37
|
"CHANGELOG.md",
|
|
38
|
+
"index.ts",
|
|
39
|
+
"plugin.ts",
|
|
39
40
|
"src/"
|
|
40
41
|
],
|
|
41
42
|
"type": "module",
|
|
42
|
-
"main": "
|
|
43
|
-
"types": "index.ts",
|
|
43
|
+
"main": "./dist/plugin.js",
|
|
44
|
+
"types": "./dist/index.d.ts",
|
|
44
45
|
"exports": {
|
|
45
46
|
".": {
|
|
46
|
-
"
|
|
47
|
+
"types": "./dist/index.d.ts",
|
|
48
|
+
"import": "./dist/plugin.js"
|
|
47
49
|
},
|
|
48
50
|
"./server": {
|
|
49
|
-
"
|
|
51
|
+
"types": "./dist/plugin.d.ts",
|
|
52
|
+
"import": "./dist/plugin.js"
|
|
50
53
|
}
|
|
51
54
|
},
|
|
52
55
|
"publishConfig": {
|
|
53
56
|
"access": "public"
|
|
54
57
|
},
|
|
55
58
|
"scripts": {
|
|
59
|
+
"build": "bun scripts/build-plugin.ts && bunx tsc -p tsconfig.json --emitDeclarationOnly",
|
|
56
60
|
"lint": "oxlint --deny-warnings src scripts plugin.ts index.ts tests",
|
|
57
61
|
"lint:fix": "oxlint --fix src scripts plugin.ts index.ts tests",
|
|
58
62
|
"format": "oxfmt src scripts plugin.ts index.ts tests package.json tsconfig.json release.config.cjs",
|
|
@@ -69,18 +73,21 @@
|
|
|
69
73
|
"sync:global": "bun run scripts/sync-models.ts --update-global",
|
|
70
74
|
"catalog:ci": "bun run scripts/catalog-sync-ci.ts"
|
|
71
75
|
},
|
|
76
|
+
"dependencies": {
|
|
77
|
+
"zod": "4.6.5"
|
|
78
|
+
},
|
|
72
79
|
"devDependencies": {
|
|
73
80
|
"@semantic-release/exec": "7.1.0",
|
|
74
|
-
"@semantic-release/github": "12.0.
|
|
75
|
-
"@semantic-release/npm": "13.
|
|
81
|
+
"@semantic-release/github": "12.0.10",
|
|
82
|
+
"@semantic-release/npm": "13.2.0",
|
|
76
83
|
"@semantic-release/release-notes-generator": "14.1.1",
|
|
77
|
-
"@types/bun": "1.4.
|
|
78
|
-
"@types/node": "
|
|
79
|
-
"ai": "
|
|
80
|
-
"oxfmt": "0.
|
|
81
|
-
"oxlint": "1.
|
|
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",
|
|
82
89
|
"semantic-release": "25.0.9",
|
|
83
|
-
"typescript": "
|
|
90
|
+
"typescript": "6.0.3"
|
|
84
91
|
},
|
|
85
92
|
"peerDependencies": {
|
|
86
93
|
"ai": ">=6.0.0"
|
package/plugin.ts
CHANGED
|
@@ -1,78 +1,231 @@
|
|
|
1
1
|
import { readFileSync, existsSync } from "fs";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { fileURLToPath } from "url";
|
|
2
|
+
import { join } from "path";
|
|
3
|
+
import { z } from "zod";
|
|
5
4
|
import {
|
|
6
5
|
generateOpencodeModels,
|
|
7
|
-
|
|
6
|
+
loadCatalogFromLocalCommandCodeResult,
|
|
8
7
|
type ModelEntry,
|
|
9
8
|
} from "./src/catalog.js";
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
writeStartupSummary,
|
|
14
|
-
pluginStateDir,
|
|
15
|
-
} 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";
|
|
16
12
|
import type { CatalogManifest } from "./src/manifest.js";
|
|
13
|
+
import { generateV2Models } from "./src/v2models.js";
|
|
14
|
+
import { catalogPaths } from "./src/paths.js";
|
|
15
|
+
import { ManifestSchema, ModelEntrySchema, PluginFileConfigSchema } from "./src/schemas.js";
|
|
17
16
|
|
|
18
|
-
const
|
|
19
|
-
const MODELS_PATH = join(__dirname, "models.json");
|
|
20
|
-
const VERSION_PATH = join(__dirname, "_version.txt");
|
|
21
|
-
const MANIFEST_PATH = join(__dirname, "manifest.json");
|
|
17
|
+
const { models: MODELS_PATH, manifest: MANIFEST_PATH, version: VERSION_PATH } = catalogPaths();
|
|
22
18
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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";
|
|
28
24
|
|
|
29
|
-
|
|
30
|
-
|
|
25
|
+
type PluginFileConfig = z.infer<typeof PluginFileConfigSchema>;
|
|
26
|
+
|
|
27
|
+
function loadPluginConfig(deps: EnvDeps = liveEnv): PluginFileConfig {
|
|
28
|
+
const dir = join(deps.homedir(), ".config", "opencode");
|
|
31
29
|
const configPath = [
|
|
32
30
|
join(dir, "opencode-commandcode.json"),
|
|
33
31
|
join(dir, "commandcode-go-opencode-provider.json"),
|
|
34
32
|
].find((p) => existsSync(p));
|
|
35
|
-
if (!configPath) return {};
|
|
33
|
+
if (!configPath) return PluginFileConfigSchema.parse({});
|
|
34
|
+
let raw: unknown = {};
|
|
36
35
|
try {
|
|
37
|
-
|
|
36
|
+
raw = JSON.parse(readFileSync(configPath, "utf-8")) as unknown;
|
|
38
37
|
} catch {
|
|
39
|
-
|
|
38
|
+
raw = {};
|
|
40
39
|
}
|
|
40
|
+
const parsed = PluginFileConfigSchema.safeParse(raw);
|
|
41
|
+
return parsed.success ? parsed.data : PluginFileConfigSchema.parse({});
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
export type { ModelEntry };
|
|
44
45
|
|
|
45
|
-
|
|
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;
|
|
46
51
|
try {
|
|
47
|
-
|
|
48
|
-
} catch {
|
|
49
|
-
return
|
|
52
|
+
raw = readFileSync(MODELS_PATH, "utf-8");
|
|
53
|
+
} catch (error) {
|
|
54
|
+
return errResult(`bundled models.json unreadable: ${causeMessage(error)}`);
|
|
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)}`);
|
|
50
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 });
|
|
51
74
|
}
|
|
52
75
|
|
|
53
|
-
|
|
54
|
-
|
|
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;
|
|
55
80
|
try {
|
|
56
|
-
|
|
57
|
-
} catch {
|
|
58
|
-
return
|
|
81
|
+
parsed = JSON.parse(readFileSync(MANIFEST_PATH, "utf-8")) as unknown;
|
|
82
|
+
} catch (error) {
|
|
83
|
+
return errResult(`bundled manifest.json unreadable: ${causeMessage(error)}`);
|
|
59
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}`);
|
|
89
|
+
}
|
|
90
|
+
return okResult(result.data);
|
|
60
91
|
}
|
|
61
92
|
|
|
62
|
-
|
|
93
|
+
/** Explicit version read: manifest first, `_version.txt` fallback, else a reason. */
|
|
94
|
+
function readBundledVersion(): LoadResult<string | null> {
|
|
63
95
|
const manifest = readBundledManifest();
|
|
64
|
-
if (manifest
|
|
65
|
-
|
|
96
|
+
if (manifest.ok && manifest.value?.commandCodeVersion) {
|
|
97
|
+
return okResult(manifest.value.commandCodeVersion);
|
|
98
|
+
}
|
|
99
|
+
if (!existsSync(VERSION_PATH)) return errResult("version file missing");
|
|
100
|
+
try {
|
|
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)}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export type CatalogLoad = {
|
|
110
|
+
models: ModelEntry[];
|
|
111
|
+
catalogSource: "bundled" | "cache" | "opt-in-local";
|
|
112
|
+
commandCodeVersion: string | null;
|
|
113
|
+
degraded: boolean;
|
|
114
|
+
degradedReason: string | null;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
export function loadCatalogEntries(deps: EnvDeps = liveEnv): CatalogLoad {
|
|
118
|
+
const pluginCfg = loadPluginConfig(deps);
|
|
119
|
+
const override =
|
|
120
|
+
pluginCfg.commandCodePackagePath?.trim() ||
|
|
121
|
+
deps.getEnv("COMMANDCODE_PACKAGE_PATH")?.trim() ||
|
|
122
|
+
"";
|
|
123
|
+
|
|
124
|
+
let models: ModelEntry[] = [];
|
|
125
|
+
let catalogSource: CatalogLoad["catalogSource"] = "bundled";
|
|
126
|
+
let commandCodeVersion: string | null = null;
|
|
127
|
+
let degraded = false;
|
|
128
|
+
const reasons: string[] = [];
|
|
129
|
+
|
|
130
|
+
if (override) {
|
|
131
|
+
const local = loadCatalogFromLocalCommandCodeResult({ packagePath: override }, deps);
|
|
132
|
+
if (local.ok && local.value && local.value.models.length > 0) {
|
|
133
|
+
models = local.value.models;
|
|
134
|
+
catalogSource = "opt-in-local";
|
|
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");
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (models.length === 0) {
|
|
144
|
+
const bundled = loadBundledModels();
|
|
145
|
+
if (bundled.ok) {
|
|
146
|
+
models = bundled.value.models;
|
|
147
|
+
catalogSource = "bundled";
|
|
148
|
+
const version = readBundledVersion();
|
|
149
|
+
commandCodeVersion = version.ok ? version.value : null;
|
|
150
|
+
const manifest = readBundledManifest();
|
|
151
|
+
if (
|
|
152
|
+
manifest.ok &&
|
|
153
|
+
manifest.value &&
|
|
154
|
+
(manifest.value.status === "degraded" || manifest.value.status === "broken")
|
|
155
|
+
) {
|
|
156
|
+
degraded = true;
|
|
157
|
+
reasons.push(
|
|
158
|
+
manifest.value.status === "broken"
|
|
159
|
+
? "bundled catalog marked broken"
|
|
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
|
+
);
|
|
170
|
+
}
|
|
171
|
+
} else {
|
|
172
|
+
const cached = readCatalogCacheResult(undefined, deps);
|
|
173
|
+
if (cached.ok) {
|
|
174
|
+
models = cached.value;
|
|
175
|
+
catalogSource = "cache";
|
|
176
|
+
degraded = true;
|
|
177
|
+
reasons.push(`bundled models.json failed (${bundled.reason}); using last-good cache`);
|
|
178
|
+
} else {
|
|
179
|
+
degraded = true;
|
|
180
|
+
reasons.push(`no bundled catalog (${bundled.reason}) and no cache (${cached.reason})`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
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
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function persistCatalogSideEffects(
|
|
197
|
+
load: CatalogLoad,
|
|
198
|
+
debug: boolean,
|
|
199
|
+
deps: EnvDeps = liveEnv,
|
|
200
|
+
): void {
|
|
201
|
+
if (load.models.length > 0) {
|
|
202
|
+
try {
|
|
203
|
+
writeCatalogCache(resolveStateDir(deps), load.models);
|
|
204
|
+
} catch {
|
|
205
|
+
// ignore cache write
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const summary = {
|
|
210
|
+
catalogSource: load.catalogSource,
|
|
211
|
+
commandCodeVersion: load.commandCodeVersion,
|
|
212
|
+
modelCount: load.models.length,
|
|
213
|
+
reasoningModelCount: load.models.filter((m) => m.reasoning).length,
|
|
214
|
+
degraded: load.degraded,
|
|
215
|
+
degradedReason: load.degradedReason,
|
|
216
|
+
};
|
|
66
217
|
try {
|
|
67
|
-
|
|
68
|
-
const first = parts[0]?.trim();
|
|
69
|
-
return first || null;
|
|
218
|
+
writeStartupSummary(resolveStateDir(deps), summary);
|
|
70
219
|
} catch {
|
|
71
|
-
|
|
220
|
+
// ignore
|
|
221
|
+
}
|
|
222
|
+
if (debug) {
|
|
223
|
+
console.warn("[commandcode]", JSON.stringify(summary));
|
|
72
224
|
}
|
|
73
225
|
}
|
|
74
226
|
|
|
75
|
-
|
|
227
|
+
/** V1 entrypoint (OpenCode 1.18.29+ also accepts it via `server`). */
|
|
228
|
+
export async function server() {
|
|
76
229
|
return {
|
|
77
230
|
config: async (config: Record<string, unknown>) => {
|
|
78
231
|
if (!(config as Record<string, unknown>).provider) {
|
|
@@ -85,86 +238,26 @@ export default async function commandcodePlugin() {
|
|
|
85
238
|
|
|
86
239
|
const pluginCfg = loadPluginConfig();
|
|
87
240
|
const debug = pluginCfg.debugStartupLogs === true;
|
|
88
|
-
const override =
|
|
89
|
-
pluginCfg.commandCodePackagePath?.trim() ||
|
|
90
|
-
process.env.COMMANDCODE_PACKAGE_PATH?.trim() ||
|
|
91
|
-
"";
|
|
92
241
|
|
|
93
|
-
if (!cc.npm) cc.npm =
|
|
242
|
+
if (!cc.npm) cc.npm = PROVIDER_SDK_NPM;
|
|
94
243
|
if (!cc.name) cc.name = "Command Code";
|
|
95
244
|
if (!cc.env) cc.env = ["COMMANDCODE_API_KEY"];
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
if (override) {
|
|
106
|
-
const localCatalog = loadCatalogFromLocalCommandCode({ packagePath: override });
|
|
107
|
-
if (localCatalog && localCatalog.models.length > 0) {
|
|
108
|
-
models = localCatalog.models;
|
|
109
|
-
catalogSource = "opt-in-local";
|
|
110
|
-
commandCodeVersion = localCatalog.version;
|
|
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;
|
|
111
253
|
}
|
|
112
254
|
}
|
|
113
255
|
|
|
114
|
-
if (models
|
|
115
|
-
const bundled = loadBundledModels();
|
|
116
|
-
if (bundled) {
|
|
117
|
-
models = bundled;
|
|
118
|
-
catalogSource = "bundled";
|
|
119
|
-
commandCodeVersion = readBundledVersion();
|
|
120
|
-
const manifest = readBundledManifest();
|
|
121
|
-
if (manifest?.status === "degraded" || manifest?.status === "broken") {
|
|
122
|
-
degraded = true;
|
|
123
|
-
degradedReason =
|
|
124
|
-
manifest.status === "broken"
|
|
125
|
-
? "bundled catalog marked broken"
|
|
126
|
-
: "bundled catalog has models with no listed price";
|
|
127
|
-
}
|
|
128
|
-
} else {
|
|
129
|
-
const cached = readCatalogCache();
|
|
130
|
-
if (cached) {
|
|
131
|
-
models = cached;
|
|
132
|
-
catalogSource = "cache";
|
|
133
|
-
degraded = true;
|
|
134
|
-
degradedReason = "bundled models.json unreadable; using last-good cache";
|
|
135
|
-
} else {
|
|
136
|
-
degraded = true;
|
|
137
|
-
degradedReason = "no bundled catalog and no cache";
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
if (models.length > 0) {
|
|
143
|
-
try {
|
|
144
|
-
writeCatalogCache(pluginStateDir(), models);
|
|
145
|
-
} catch {
|
|
146
|
-
// ignore cache write
|
|
147
|
-
}
|
|
148
|
-
}
|
|
256
|
+
if (cc.models) return;
|
|
149
257
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
catalogSource,
|
|
154
|
-
commandCodeVersion,
|
|
155
|
-
modelCount: models.length,
|
|
156
|
-
reasoningModelCount: models.filter((m) => m.reasoning).length,
|
|
157
|
-
degraded,
|
|
158
|
-
degradedReason,
|
|
159
|
-
};
|
|
160
|
-
try {
|
|
161
|
-
writeStartupSummary(pluginStateDir(), summary);
|
|
162
|
-
} catch {
|
|
163
|
-
// ignore
|
|
164
|
-
}
|
|
165
|
-
if (debug) {
|
|
166
|
-
console.warn("[commandcode]", JSON.stringify(summary));
|
|
167
|
-
}
|
|
258
|
+
const load = loadCatalogEntries();
|
|
259
|
+
persistCatalogSideEffects(load, debug);
|
|
260
|
+
cc.models = generateOpencodeModels(load.models);
|
|
168
261
|
},
|
|
169
262
|
|
|
170
263
|
auth: {
|
|
@@ -195,3 +288,46 @@ export default async function commandcodePlugin() {
|
|
|
195
288
|
},
|
|
196
289
|
};
|
|
197
290
|
}
|
|
291
|
+
|
|
292
|
+
/** V2 setup: provider inventory + models through transforms. Auth stays V1-only for now. */
|
|
293
|
+
async function setup(ctx: any): Promise<void> {
|
|
294
|
+
const pluginCfg = loadPluginConfig();
|
|
295
|
+
const debug = pluginCfg.debugStartupLogs === true;
|
|
296
|
+
const load = loadCatalogEntries();
|
|
297
|
+
persistCatalogSideEffects(load, debug);
|
|
298
|
+
const v2models = generateV2Models(load.models);
|
|
299
|
+
|
|
300
|
+
await ctx.provider.transform((editor: any) => {
|
|
301
|
+
const existing = editor.get("commandcode");
|
|
302
|
+
if (!existing) {
|
|
303
|
+
editor.add({
|
|
304
|
+
info: {
|
|
305
|
+
id: "commandcode",
|
|
306
|
+
name: "Command Code",
|
|
307
|
+
activation: "enabled",
|
|
308
|
+
package: `aisdk:${PROVIDER_SDK_NPM}`,
|
|
309
|
+
settings: {
|
|
310
|
+
baseURL: PROVIDER_API_BASE_URL,
|
|
311
|
+
apiKey: "{env:COMMANDCODE_API_KEY}",
|
|
312
|
+
},
|
|
313
|
+
},
|
|
314
|
+
models: v2models,
|
|
315
|
+
});
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
editor.update("commandcode", (provider: any) => {
|
|
319
|
+
provider.name = provider.name ?? "Command Code";
|
|
320
|
+
provider.settings = provider.settings ?? {};
|
|
321
|
+
if (typeof provider.settings === "object") {
|
|
322
|
+
if (!provider.settings.baseURL) provider.settings.baseURL = PROVIDER_API_BASE_URL;
|
|
323
|
+
if (!provider.settings.apiKey) provider.settings.apiKey = "{env:COMMANDCODE_API_KEY}";
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
editor.models.set("commandcode", v2models);
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const definition = { id: "commandcode", setup };
|
|
331
|
+
|
|
332
|
+
// Dual entry: V2 reads default.id/setup, V1 (>=1.18.29) calls default.server().
|
|
333
|
+
export default { ...definition, server };
|
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 {
|
|
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
|
|
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 =
|
|
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(
|
|
711
|
-
|
|
712
|
-
|
|
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() ||
|
|
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
|
-
|
|
734
|
-
|
|
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
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
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
|
-
|
|
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/entry.ts
ADDED
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/paths.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
|
|
5
|
+
/** Directory of this module, canonicalized so symlinked checkouts, tmpdir
|
|
6
|
+
* aliasing (`/var` vs `/private/var`), and Windows 8.3 short names cannot
|
|
7
|
+
* split the reported locations from the caller's spelling. */
|
|
8
|
+
const moduleDir = (): string => {
|
|
9
|
+
try {
|
|
10
|
+
return realpathSync(path.dirname(fileURLToPath(import.meta.url)));
|
|
11
|
+
} catch {
|
|
12
|
+
return path.dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Resolve the provider package root from any layout, workit-style: source
|
|
18
|
+
* modules live in `src/`, the plugin entry at the package root (`plugin.ts`),
|
|
19
|
+
* and a future bundle in `dist/`. The nearest ancestor with a `package.json`
|
|
20
|
+
* wins, so moving a source file or bundling the entry can never silently
|
|
21
|
+
* point catalog reads at the wrong directory.
|
|
22
|
+
*/
|
|
23
|
+
export const packageRoot = (): string => {
|
|
24
|
+
const dir = moduleDir();
|
|
25
|
+
for (const candidate of [
|
|
26
|
+
path.resolve(dir, ".."),
|
|
27
|
+
path.resolve(dir, "..", ".."),
|
|
28
|
+
path.resolve(dir, "..", "..", ".."),
|
|
29
|
+
]) {
|
|
30
|
+
if (existsSync(path.join(candidate, "package.json"))) return candidate;
|
|
31
|
+
}
|
|
32
|
+
return path.resolve(dir, "..");
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Catalog artifact locations under the resolved package root. */
|
|
36
|
+
export const catalogPaths = (): { models: string; manifest: string; version: string } => {
|
|
37
|
+
const root = packageRoot();
|
|
38
|
+
return {
|
|
39
|
+
models: path.join(root, "models.json"),
|
|
40
|
+
manifest: path.join(root, "manifest.json"),
|
|
41
|
+
version: path.join(root, "_version.txt"),
|
|
42
|
+
};
|
|
43
|
+
};
|
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
|
-
|
|
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
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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
|
-
|
|
28
|
-
|
|
29
|
-
return
|
|
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
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { toConfigKey, type ModelEntry } from "./catalog.js";
|
|
2
|
+
|
|
3
|
+
/** Minimal V2 model shape (structural subset of Model.Info). */
|
|
4
|
+
export interface V2Model {
|
|
5
|
+
id: string;
|
|
6
|
+
modelID: string;
|
|
7
|
+
providerID: string;
|
|
8
|
+
name: string;
|
|
9
|
+
capabilities: { tools: boolean; input: string[]; output: string[] };
|
|
10
|
+
cost: Array<{ input: number; output: number; cache: { read: number; write: number } }>;
|
|
11
|
+
limit: { context: number; output: number };
|
|
12
|
+
variants: Array<{ id: string; settings: Record<string, unknown> }>;
|
|
13
|
+
status: "active";
|
|
14
|
+
enabled: boolean;
|
|
15
|
+
time: { released: number };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function v2Input(entry: ModelEntry): string[] {
|
|
19
|
+
if (entry.modalities?.input && entry.modalities.input.length > 0)
|
|
20
|
+
return [...entry.modalities.input];
|
|
21
|
+
if (entry.attachment === true) return ["text", "image"];
|
|
22
|
+
return ["text"];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function v2Output(entry: ModelEntry): string[] {
|
|
26
|
+
if (entry.modalities?.output && entry.modalities.output.length > 0)
|
|
27
|
+
return [...entry.modalities.output];
|
|
28
|
+
return ["text"];
|
|
29
|
+
}
|
|
30
|
+
|
|
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.
|
|
34
|
+
const id = toConfigKey(entry.id);
|
|
35
|
+
return {
|
|
36
|
+
id,
|
|
37
|
+
modelID: entry.id,
|
|
38
|
+
providerID: "commandcode",
|
|
39
|
+
name: entry.name,
|
|
40
|
+
capabilities: {
|
|
41
|
+
tools: entry.tool_call,
|
|
42
|
+
input: v2Input(entry),
|
|
43
|
+
output: v2Output(entry),
|
|
44
|
+
},
|
|
45
|
+
cost: [
|
|
46
|
+
{
|
|
47
|
+
input: entry.cost.input,
|
|
48
|
+
output: entry.cost.output,
|
|
49
|
+
cache: {
|
|
50
|
+
read: entry.cost.cache_read ?? 0,
|
|
51
|
+
write: entry.cost.cache_write ?? 0,
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
],
|
|
55
|
+
limit: { context: entry.limit.context, output: entry.limit.output },
|
|
56
|
+
variants: (entry.reasoningEfforts ?? []).map((effort) => ({
|
|
57
|
+
id: effort,
|
|
58
|
+
settings: { reasoningEffort: effort },
|
|
59
|
+
})),
|
|
60
|
+
status: "active",
|
|
61
|
+
enabled: true,
|
|
62
|
+
time: { released: 0 },
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function generateV2Models(entries: ModelEntry[]): V2Model[] {
|
|
67
|
+
return entries.map(toV2Model);
|
|
68
|
+
}
|