@brainervirus/opencode-commandcode 0.8.0 → 0.9.1

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/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
- }