-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.ts
More file actions
347 lines (319 loc) · 12 KB
/
Copy pathplugin.ts
File metadata and controls
347 lines (319 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import { readFileSync, existsSync } from "fs";
import { join } from "path";
import { z } from "zod";
import {
generateOpencodeModels,
loadCatalogFromLocalCommandCodeResult,
type ModelEntry,
} from "./src/catalog.js";
import { readCatalogCacheResult, writeCatalogCache, writeStartupSummary } from "./src/startup.js";
import { liveEnv, resolveStateDir, type EnvDeps } from "./src/env.js";
import { causeMessage, errResult, okResult, type LoadResult } from "./src/load-result.js";
import type { CatalogManifest } from "./src/manifest.js";
import { generateV2Models } from "./src/v2models.js";
import { catalogPaths } from "./src/paths.js";
import { ManifestSchema, ModelEntrySchema, PluginFileConfigSchema } from "./src/schemas.js";
const { models: MODELS_PATH, manifest: MANIFEST_PATH, version: VERSION_PATH } = catalogPaths();
// V1 loads the AI SDK package directly. V2 uses OpenCode's native runtime so provider
// settings such as baseURL survive registry materialization.
const V1_PROVIDER_SDK_NPM = "@ai-sdk/openai-compatible";
const V2_PROVIDER_PACKAGE = "@opencode/ai/providers/openai-compatible";
const PROVIDER_API_BASE_URL = "https://api.commandcode.ai/provider/v1";
type PluginFileConfig = z.infer<typeof PluginFileConfigSchema>;
function loadPluginConfig(deps: EnvDeps = liveEnv): PluginFileConfig {
const dir = join(deps.homedir(), ".config", "opencode");
const configPath = [
join(dir, "opencode-commandcode.json"),
join(dir, "commandcode-go-opencode-provider.json"),
].find((p) => existsSync(p));
if (!configPath) return PluginFileConfigSchema.parse({});
let raw: unknown = {};
try {
raw = JSON.parse(readFileSync(configPath, "utf-8")) as unknown;
} catch {
raw = {};
}
const parsed = PluginFileConfigSchema.safeParse(raw);
return parsed.success ? parsed.data : PluginFileConfigSchema.parse({});
}
export type { ModelEntry };
type BundledModels = { models: ModelEntry[]; dropped: number; dropReasons: string[] };
/** Explicit bundled read: parsed models plus the reason when unavailable. */
function loadBundledModels(): LoadResult<BundledModels> {
let raw: string;
try {
raw = readFileSync(MODELS_PATH, "utf-8");
} catch (error) {
return errResult(`bundled models.json unreadable: ${causeMessage(error)}`);
}
let parsed: unknown;
try {
parsed = JSON.parse(raw) as unknown;
} catch (error) {
return errResult(`bundled models.json invalid JSON: ${causeMessage(error)}`);
}
if (!Array.isArray(parsed)) return errResult("bundled models.json is not an array");
const models: ModelEntry[] = [];
const dropReasons: string[] = [];
for (let index = 0; index < parsed.length; index++) {
const result = ModelEntrySchema.safeParse(parsed[index]);
if (result.success) models.push(result.data);
else if (dropReasons.length < 3) {
const detail = result.error.issues.map((issue) => issue.message).join("; ");
dropReasons.push(`entry ${index}: ${detail}`);
}
}
return okResult({ models, dropped: parsed.length - models.length, dropReasons });
}
/** Explicit manifest read: `ok(null)` is a missing file (version falls back). */
function readBundledManifest(): LoadResult<CatalogManifest | null> {
if (!existsSync(MANIFEST_PATH)) return okResult(null);
let parsed: unknown;
try {
parsed = JSON.parse(readFileSync(MANIFEST_PATH, "utf-8")) as unknown;
} catch (error) {
return errResult(`bundled manifest.json unreadable: ${causeMessage(error)}`);
}
const result = ManifestSchema.safeParse(parsed);
if (!result.success) {
const detail = result.error.issues.map((issue) => issue.message).join("; ");
return errResult(`bundled manifest.json invalid: ${detail}`);
}
return okResult(result.data);
}
/** Explicit version read: manifest first, `_version.txt` fallback, else a reason. */
function readBundledVersion(): LoadResult<string | null> {
const manifest = readBundledManifest();
if (manifest.ok && manifest.value?.commandCodeVersion) {
return okResult(manifest.value.commandCodeVersion);
}
if (!existsSync(VERSION_PATH)) return errResult("version file missing");
try {
const first = readFileSync(VERSION_PATH, "utf-8").split("\n")[0]?.trim();
if (!first) return errResult("version file empty");
return okResult(first);
} catch (error) {
return errResult(`version file unreadable: ${causeMessage(error)}`);
}
}
export type CatalogLoad = {
models: ModelEntry[];
catalogSource: "bundled" | "cache" | "opt-in-local";
commandCodeVersion: string | null;
degraded: boolean;
degradedReason: string | null;
};
export function loadCatalogEntries(deps: EnvDeps = liveEnv): CatalogLoad {
const pluginCfg = loadPluginConfig(deps);
const override =
pluginCfg.commandCodePackagePath?.trim() ||
deps.getEnv("COMMANDCODE_PACKAGE_PATH")?.trim() ||
"";
let models: ModelEntry[] = [];
let catalogSource: CatalogLoad["catalogSource"] = "bundled";
let commandCodeVersion: string | null = null;
let degraded = false;
const reasons: string[] = [];
if (override) {
const local = loadCatalogFromLocalCommandCodeResult({ packagePath: override }, deps);
if (local.ok && local.value && local.value.models.length > 0) {
models = local.value.models;
catalogSource = "opt-in-local";
commandCodeVersion = local.value.version;
} else if (!local.ok) {
reasons.push(`local override failed (${local.reason})`);
} else {
reasons.push("local override produced no models");
}
}
if (models.length === 0) {
const bundled = loadBundledModels();
if (bundled.ok) {
models = bundled.value.models;
catalogSource = "bundled";
const version = readBundledVersion();
commandCodeVersion = version.ok ? version.value : null;
const manifest = readBundledManifest();
if (
manifest.ok &&
manifest.value &&
(manifest.value.status === "degraded" || manifest.value.status === "broken")
) {
degraded = true;
reasons.push(
manifest.value.status === "broken"
? "bundled catalog marked broken"
: "bundled catalog has models with no listed price",
);
}
if (bundled.value.dropped > 0) {
degraded = true;
const details =
bundled.value.dropReasons.length > 0 ? `: ${bundled.value.dropReasons.join("; ")}` : "";
reasons.push(
`dropped ${bundled.value.dropped} invalid bundled model ${bundled.value.dropped === 1 ? "entry" : "entries"}${details}`,
);
}
} else {
const cached = readCatalogCacheResult(undefined, deps);
if (cached.ok) {
models = cached.value;
catalogSource = "cache";
degraded = true;
reasons.push(`bundled models.json failed (${bundled.reason}); using last-good cache`);
} else {
degraded = true;
reasons.push(`no bundled catalog (${bundled.reason}) and no cache (${cached.reason})`);
}
}
}
// Override notes only sharpen an already-degraded report; a healthy
// bundled load stays non-degraded exactly as before.
return {
models,
catalogSource,
commandCodeVersion,
degraded,
degradedReason: degraded ? reasons.join("; ") : null,
};
}
function persistCatalogSideEffects(
load: CatalogLoad,
debug: boolean,
deps: EnvDeps = liveEnv,
): void {
if (load.models.length > 0) {
try {
writeCatalogCache(resolveStateDir(deps), load.models);
} catch {
// ignore cache write
}
}
const summary = {
catalogSource: load.catalogSource,
commandCodeVersion: load.commandCodeVersion,
modelCount: load.models.length,
reasoningModelCount: load.models.filter((m) => m.reasoning).length,
degraded: load.degraded,
degradedReason: load.degradedReason,
};
try {
writeStartupSummary(resolveStateDir(deps), summary);
} catch {
// ignore
}
if (debug) {
console.warn("[commandcode]", JSON.stringify(summary));
}
}
/** V1 entrypoint (OpenCode 1.18.29+ also accepts it via `server`). */
export async function server() {
return {
config: async (config: Record<string, unknown>) => {
if (!(config as Record<string, unknown>).provider) {
(config as Record<string, unknown>).provider = { commandcode: {} };
}
const cc = (
(config as Record<string, unknown>).provider as Record<string, Record<string, unknown>>
)?.commandcode as Record<string, unknown> | undefined;
if (!cc) return;
const pluginCfg = loadPluginConfig();
const debug = pluginCfg.debugStartupLogs === true;
if (!cc.npm) cc.npm = V1_PROVIDER_SDK_NPM;
if (!cc.name) cc.name = "Command Code";
if (!cc.env) cc.env = ["COMMANDCODE_API_KEY"];
// V1 resolves `npm` through BunProc.install and calls the first `create*` export, so
// the SDK package must be the OpenAI-compatible one; give it the Provider API URL
// unless the user already configured another baseURL (custom npm stays untouched).
if (cc.npm === V1_PROVIDER_SDK_NPM) {
if (cc.options === undefined) cc.options = {};
if (typeof cc.options === "object" && cc.options !== null) {
const options = cc.options as Record<string, unknown>;
if (!options.baseURL) options.baseURL = PROVIDER_API_BASE_URL;
}
}
if (cc.models) return;
const load = loadCatalogEntries();
persistCatalogSideEffects(load, debug);
cc.models = generateOpencodeModels(load.models);
},
auth: {
provider: "commandcode",
methods: [
{
type: "api",
label: "API Key",
authorize: async (inputs: Record<string, unknown> | undefined) => {
const rawKey = inputs?.key;
if (typeof rawKey !== "string") return { type: "failed" as const };
const key = rawKey.trim();
if (!key) return { type: "failed" as const };
return { type: "success" as const, key };
},
},
],
loader: async (getAuth: () => Promise<{ type: string; key?: string } | null>) => {
try {
const auth = await getAuth();
if (!auth) return {};
if (auth.type === "api" && auth.key) return { apiKey: auth.key };
return {};
} catch {
return {};
}
},
},
};
}
/** V2 setup: provider inventory, models, and API-key integration through transforms. */
async function setup(ctx: any): Promise<void> {
const pluginCfg = loadPluginConfig();
const debug = pluginCfg.debugStartupLogs === true;
const load = loadCatalogEntries();
persistCatalogSideEffects(load, debug);
const v2models = generateV2Models(load.models);
await ctx.provider.transform((editor: any) => {
const existing = editor.get("commandcode");
if (!existing) {
editor.add({
info: {
id: "commandcode",
name: "Command Code",
activation: "auto",
integrationID: "commandcode",
env: ["COMMANDCODE_API_KEY"],
package: V2_PROVIDER_PACKAGE,
settings: {
baseURL: PROVIDER_API_BASE_URL,
},
},
models: v2models,
});
return;
}
editor.update("commandcode", (provider: any) => {
provider.name = provider.name ?? "Command Code";
provider.activation = provider.activation ?? "auto";
provider.integrationID = provider.integrationID ?? "commandcode";
provider.env = provider.env ?? ["COMMANDCODE_API_KEY"];
provider.settings = provider.settings ?? {};
if (typeof provider.settings === "object") {
if (!provider.settings.baseURL) provider.settings.baseURL = PROVIDER_API_BASE_URL;
}
});
editor.models.set("commandcode", v2models);
});
await ctx.integration.transform((editor: any) => {
editor.method.update({
integrationID: "commandcode",
method: { type: "key", label: "API Key" },
});
editor.method.update({
integrationID: "commandcode",
method: { type: "env", names: ["COMMANDCODE_API_KEY"] },
});
});
}
const definition = { id: "commandcode", setup };
// Dual entry: V2 reads default.id/setup, V1 (>=1.18.29) calls default.server().
export default { ...definition, server };