@telsoncc/opencode-commandcode 1.2.33 → 1.2.34

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +6 -222
  2. package/dist/_version.txt +1 -0
  3. package/dist/index.d.ts +11 -0
  4. package/dist/index.js +19 -0
  5. package/dist/manifest.json +28 -0
  6. package/dist/models.json +3334 -0
  7. package/dist/plugin-opencode2.d.ts +30 -0
  8. package/dist/plugin-opencode2.js +127 -0
  9. package/dist/plugin.d.ts +27 -0
  10. package/dist/plugin.js +192 -0
  11. package/dist/src/auth.d.ts +5 -0
  12. package/dist/src/auth.js +38 -0
  13. package/dist/src/catalog-break.d.ts +12 -0
  14. package/dist/src/catalog-break.js +33 -0
  15. package/dist/src/catalog-release-notes.d.ts +30 -0
  16. package/dist/src/catalog-release-notes.js +106 -0
  17. package/dist/src/catalog.d.ts +160 -0
  18. package/dist/src/catalog.js +786 -0
  19. package/dist/src/convert.d.ts +71 -0
  20. package/dist/src/convert.js +154 -0
  21. package/dist/src/costs-docs.d.ts +13 -0
  22. package/dist/src/costs-docs.js +170 -0
  23. package/dist/src/costs-models-dev.d.ts +68 -0
  24. package/dist/src/costs-models-dev.js +303 -0
  25. package/dist/src/cut-changelog.d.ts +1 -0
  26. package/dist/src/cut-changelog.js +43 -0
  27. package/dist/src/manifest.d.ts +72 -0
  28. package/dist/src/manifest.js +111 -0
  29. package/dist/src/model.d.ts +18 -0
  30. package/dist/src/model.js +138 -0
  31. package/dist/src/opencode2.d.ts +179 -0
  32. package/dist/src/opencode2.js +386 -0
  33. package/dist/src/pack-contract.d.ts +25 -0
  34. package/dist/src/pack-contract.js +42 -0
  35. package/dist/src/publish-policy.d.ts +18 -0
  36. package/dist/src/publish-policy.js +16 -0
  37. package/dist/src/startup.d.ts +18 -0
  38. package/dist/src/startup.js +31 -0
  39. package/dist/src/stream.d.ts +2 -0
  40. package/dist/src/stream.js +203 -0
  41. package/manifest.json +1 -1
  42. package/package.json +12 -7
  43. package/plugin.ts +14 -3
  44. package/src/cut-changelog.ts +6 -1
  45. package/src/opencode2.ts +14 -3
  46. package/src/pack-contract.ts +51 -0
@@ -0,0 +1,786 @@
1
+ import { createRequire } from "module";
2
+ import { execSync } from "child_process";
3
+ import { existsSync, readFileSync, statSync } from "fs";
4
+ import { dirname, join, resolve as resolvePath } from "path";
5
+ import { fileURLToPath } from "url";
6
+ export const NPM_PACKAGE = "command-code";
7
+ /**
8
+ * Which wire shape a model is served on. A model that is Messages-only cannot
9
+ * be called through `/chat/completions` — the gateway rejects it with
10
+ * `must be called via /provider/v1/messages` — so the transport has to be
11
+ * resolved per model, not per provider.
12
+ *
13
+ * Falls back to the model family when the catalog carries no
14
+ * `supported_endpoints`: the `claude-*` family is the only Messages-only group
15
+ * the gateway serves, so the heuristic is exact for catalogs that predate the
16
+ * field. Family matching runs on the config key, so a vendor-prefixed id like
17
+ * `anthropic/claude-sonnet-5` resolves the same as a bare one.
18
+ */
19
+ export function modelTransport(entry) {
20
+ const endpoints = entry.supportedEndpoints;
21
+ if (endpoints && endpoints.length > 0) {
22
+ return endpoints.includes("/messages") && !endpoints.includes("/chat/completions")
23
+ ? "messages"
24
+ : "chat";
25
+ }
26
+ return toConfigKey(entry.id).startsWith("claude-") ? "messages" : "chat";
27
+ }
28
+ export const FALLBACK_LIMITS = {
29
+ "claude-haiku-4-5-20251001": { context: 200000, output: 8192 },
30
+ "claude-opus-4-6": { context: 200000, output: 32000 },
31
+ "claude-opus-4-7": { context: 200000, output: 32000 },
32
+ "claude-sonnet-4-6": { context: 200000, output: 16000 },
33
+ "gpt-5.5": { context: 256000, output: 128000 },
34
+ "gpt-5.4": { context: 256000, output: 128000 },
35
+ "gpt-5.3-codex": { context: 256000, output: 128000 },
36
+ "gpt-5.4-mini": { context: 256000, output: 128000 },
37
+ "moonshotai/Kimi-K2.6": { context: 262144, output: 131072 },
38
+ "moonshotai/Kimi-K2.5": { context: 262144, output: 131072 },
39
+ "zai-org/GLM-5": { context: 200000, output: 131072 },
40
+ "zai-org/GLM-5.1": { context: 200000, output: 131072 },
41
+ "MiniMaxAI/MiniMax-M2.5": { context: 1000000, output: 131072 },
42
+ "MiniMaxAI/MiniMax-M2.7": { context: 1000000, output: 131072 },
43
+ "deepseek/deepseek-v4-pro": { context: 1000000, output: 384000 },
44
+ "deepseek/deepseek-v4-flash": { context: 1000000, output: 384000 },
45
+ "Qwen/Qwen3.6-Max-Preview": { context: 1000000, output: 131072 },
46
+ "Qwen/Qwen3.6-Plus": { context: 1000000, output: 131072 },
47
+ "Qwen/Qwen3.7-Max": { context: 1000000, output: 131072 },
48
+ "stepfun/Step-3.5-Flash": { context: 1000000, output: 131072 },
49
+ "google/gemini-3.5-flash": { context: 1000000, output: 65536 },
50
+ "google/gemini-3.1-flash-lite": { context: 1000000, output: 65536 },
51
+ };
52
+ export const HARDCODED_EXTRAS = [
53
+ {
54
+ id: "Qwen/Qwen3.7-Max",
55
+ provider: "vercel-ai-gateway",
56
+ spec: "chatComplete",
57
+ label: "Qwen 3.7 Max",
58
+ name: "Qwen 3.7 Max",
59
+ description: "latest Qwen Max model",
60
+ reasoning: true,
61
+ },
62
+ ];
63
+ export const TIER_MAP = {
64
+ anthropic: "premium",
65
+ openai: "premium",
66
+ baseten: "open-source",
67
+ "vercel-ai-gateway": "open-source",
68
+ openrouter: "open-source",
69
+ "cloudflare-ai-gateway": "open-source",
70
+ };
71
+ const CATALOG_ANCHOR = 'SONNET_4_6:{id:"claude-sonnet-4-6"';
72
+ const COST_ANCHORS = [
73
+ '{id:"anthropic:claude-sonnet-4-',
74
+ '{id:"anthropic:claude-sonnet-5"',
75
+ '{id:"anthropic:claude-sonnet-4-6"',
76
+ ];
77
+ /** Object after `(` (legacy IIFE / enum form): `(Wt={...})` */
78
+ export function findBalancedObject(source, anchor) {
79
+ const anchorIdx = source.indexOf(anchor);
80
+ if (anchorIdx < 0)
81
+ throw new Error(`Anchor not found: ${anchor}`);
82
+ let parenIdx = anchorIdx - 1;
83
+ while (parenIdx >= 0 && source[parenIdx] !== "(")
84
+ parenIdx--;
85
+ if (parenIdx < 0)
86
+ throw new Error(`Could not find opening ( before anchor: ${anchor}`);
87
+ const braceStart = source.indexOf("{", parenIdx);
88
+ if (braceStart < 0)
89
+ throw new Error(`Could not find { after opening (`);
90
+ let depth = 0;
91
+ let end = braceStart;
92
+ for (; end < source.length; end++) {
93
+ if (source[end] === "{")
94
+ depth++;
95
+ else if (source[end] === "}") {
96
+ depth--;
97
+ if (depth === 0)
98
+ break;
99
+ }
100
+ }
101
+ return source.slice(braceStart, end + 1);
102
+ }
103
+ /** All balanced `{...}` spans that contain the anchor, innermost → outermost. */
104
+ export function findEnclosingObjectCandidates(source, anchor, fromIndex = 0) {
105
+ const anchorIdx = source.indexOf(anchor, fromIndex);
106
+ if (anchorIdx < 0)
107
+ throw new Error(`Anchor not found: ${anchor}`);
108
+ const stack = [];
109
+ for (let i = 0; i <= anchorIdx; i++) {
110
+ const ch = source[i];
111
+ if (ch === "{")
112
+ stack.push(i);
113
+ else if (ch === "}")
114
+ stack.pop();
115
+ }
116
+ if (stack.length === 0)
117
+ throw new Error(`Could not find enclosing { for anchor: ${anchor}`);
118
+ const MAX = 2_000_000;
119
+ const out = [];
120
+ // innermost first
121
+ for (let s = stack.length - 1; s >= 0; s--) {
122
+ const start = stack[s];
123
+ if (start === undefined)
124
+ continue;
125
+ let depth = 0;
126
+ let end = start;
127
+ for (; end < source.length; end++) {
128
+ if (source[end] === "{")
129
+ depth++;
130
+ else if (source[end] === "}") {
131
+ depth--;
132
+ if (depth === 0)
133
+ break;
134
+ }
135
+ }
136
+ if (end >= source.length || end < anchorIdx)
137
+ continue;
138
+ if (end + 1 - start > MAX)
139
+ continue;
140
+ out.push(source.slice(start, end + 1));
141
+ }
142
+ if (out.length === 0)
143
+ throw new Error(`Could not close enclosing { for anchor: ${anchor}`);
144
+ return out;
145
+ }
146
+ /** Default: innermost enclosing object (good for plain catalogs). */
147
+ export function findEnclosingObject(source, anchor, fromIndex = 0) {
148
+ const first = findEnclosingObjectCandidates(source, anchor, fromIndex)[0];
149
+ if (!first)
150
+ throw new Error(`Could not find enclosing object for anchor: ${anchor}`);
151
+ return first;
152
+ }
153
+ export function evaluateWithContext(code, context) {
154
+ const keys = Object.keys(context);
155
+ const values = keys.map((k) => context[k]);
156
+ const fn = Function(...keys, `"use strict"; return (${code})`);
157
+ return fn(...values);
158
+ }
159
+ export function normalizeForEval(code) {
160
+ return code
161
+ .replace(/!0/g, "true")
162
+ .replace(/!1/g, "false")
163
+ .replace(/(\d+)e(\d+)/g, (_, m, e) => String(Number(m) * Math.pow(10, Number(e))));
164
+ }
165
+ function getVarNameBefore(source, anchorIdx) {
166
+ const before = source.slice(Math.max(0, anchorIdx - 50), anchorIdx);
167
+ const match = before.match(/\(([A-Za-z_$]+)=\{$/);
168
+ if (match?.[1])
169
+ return match[1];
170
+ const match2 = before.match(/([A-Za-z_$]+)=\{$/);
171
+ if (match2?.[1])
172
+ return match2[1];
173
+ return null;
174
+ }
175
+ /** Prefer provider enums that include gateway/openai keys over UI-only enums. */
176
+ export function extractBestProviderEnum(source) {
177
+ const anchor = 'ANTHROPIC:"anthropic"';
178
+ let from = 0;
179
+ let fallback = null;
180
+ while (from < source.length) {
181
+ const idx = source.indexOf(anchor, from);
182
+ if (idx < 0)
183
+ break;
184
+ try {
185
+ let parenIdx = idx - 1;
186
+ while (parenIdx >= 0 && source[parenIdx] !== "(")
187
+ parenIdx--;
188
+ if (parenIdx < 0) {
189
+ from = idx + 1;
190
+ continue;
191
+ }
192
+ const braceStart = source.indexOf("{", parenIdx);
193
+ if (braceStart < 0 || braceStart > idx) {
194
+ from = idx + 1;
195
+ continue;
196
+ }
197
+ let depth = 0;
198
+ let end = braceStart;
199
+ for (; end < source.length; end++) {
200
+ if (source[end] === "{")
201
+ depth++;
202
+ else if (source[end] === "}") {
203
+ depth--;
204
+ if (depth === 0)
205
+ break;
206
+ }
207
+ }
208
+ const obj = source.slice(braceStart, end + 1);
209
+ const value = evaluateWithContext(normalizeForEval(obj), {});
210
+ const name = getVarNameBefore(source, idx) || "Wt";
211
+ const rich = "OPENAI" in value ||
212
+ "BASETEN" in value ||
213
+ "VERCEL_AI_GATEWAY" in value ||
214
+ Object.values(value).includes("openai");
215
+ const hit = { name, value };
216
+ if (rich)
217
+ return hit;
218
+ if (!fallback)
219
+ fallback = hit;
220
+ }
221
+ catch {
222
+ // try next occurrence
223
+ }
224
+ from = idx + 1;
225
+ }
226
+ return fallback;
227
+ }
228
+ export function extractWt(source) {
229
+ const best = extractBestProviderEnum(source);
230
+ if (!best)
231
+ throw new Error(`Anchor not found: ANTHROPIC:"anthropic"`);
232
+ return best.value;
233
+ }
234
+ export function getWtVarName(source) {
235
+ const best = extractBestProviderEnum(source);
236
+ if (!best)
237
+ throw new Error("Could not find Wt enum");
238
+ return best.name;
239
+ }
240
+ /** Collect nearby `name="value"` bindings and simple aliases (`tI=Qx`). */
241
+ export function extractStringBindings(source, endIdx, window = 12000) {
242
+ const before = source.slice(Math.max(0, endIdx - window), endIdx);
243
+ const bindings = {};
244
+ // \b does not fire before "$" (not a word char); minified bundles use names like
245
+ // $R="vercel-ai-gateway". A lookbehind boundary handles both $ and letter names.
246
+ const strRe = /(?<![A-Za-z0-9_$])([A-Za-z_$][\w$]*)="([^"]*)"/g;
247
+ let m;
248
+ while ((m = strRe.exec(before))) {
249
+ const name = m[1];
250
+ const value = m[2];
251
+ if (name !== undefined && value !== undefined)
252
+ bindings[name] = value;
253
+ }
254
+ for (let pass = 0; pass < 4; pass++) {
255
+ const aliasRe = /(?<![A-Za-z0-9_$])([A-Za-z_$][\w$]*)=([A-Za-z_$][\w$]*)(?![A-Za-z0-9_$])/g;
256
+ while ((m = aliasRe.exec(before))) {
257
+ const alias = m[1];
258
+ const target = m[2];
259
+ if (alias === undefined || target === undefined || bindings[alias] !== undefined)
260
+ continue;
261
+ const resolved = bindings[target];
262
+ if (resolved !== undefined)
263
+ bindings[alias] = resolved;
264
+ }
265
+ }
266
+ return bindings;
267
+ }
268
+ export function extractSpecConstants(source) {
269
+ const anchorIdx = source.indexOf(CATALOG_ANCHOR);
270
+ if (anchorIdx < 0)
271
+ throw new Error("Could not find model catalog anchor");
272
+ const before = source.slice(Math.max(0, anchorIdx - 5000), anchorIdx);
273
+ const chatMatch = before.match(/([A-Za-z_$]+)="chatComplete"/);
274
+ const respMatch = before.match(/([A-Za-z_$]+)="responses"/);
275
+ const chatName = chatMatch?.[1];
276
+ const respName = respMatch?.[1];
277
+ if (!chatName || !respName)
278
+ throw new Error("Could not find spec constants");
279
+ const qtMatch = before.match(/([A-Za-z_$]+)=Vt\[0\]/);
280
+ const qtVar = qtMatch?.[1] ?? "";
281
+ return {
282
+ chatComplete: chatName,
283
+ responses: respName,
284
+ qt: qtVar,
285
+ };
286
+ }
287
+ function buildEvalContext(source, catalogIdx) {
288
+ const ctx = {
289
+ ...extractStringBindings(source, catalogIdx),
290
+ };
291
+ const spec = extractSpecConstants(source);
292
+ ctx[spec.chatComplete] = ctx[spec.chatComplete] ?? "chatComplete";
293
+ ctx[spec.responses] = ctx[spec.responses] ?? "responses";
294
+ const providerEnum = extractBestProviderEnum(source);
295
+ if (providerEnum) {
296
+ ctx[providerEnum.name] = providerEnum.value;
297
+ if (spec.qt && providerEnum.value.VERCEL_AI_GATEWAY) {
298
+ ctx[spec.qt] = providerEnum.value.VERCEL_AI_GATEWAY;
299
+ }
300
+ }
301
+ return ctx;
302
+ }
303
+ function isModelCatalog(value) {
304
+ if (!value || typeof value !== "object" || Array.isArray(value))
305
+ return false;
306
+ const vals = Object.values(value);
307
+ if (vals.length < 2)
308
+ return false;
309
+ let modelish = 0;
310
+ for (const v of vals) {
311
+ if (v &&
312
+ typeof v === "object" &&
313
+ !Array.isArray(v) &&
314
+ typeof v.id === "string" &&
315
+ typeof v.name === "string") {
316
+ modelish++;
317
+ }
318
+ }
319
+ return modelish >= 2;
320
+ }
321
+ export function extractModelCatalog(source, wt, wtName, spec) {
322
+ const catalogIdx = source.indexOf(CATALOG_ANCHOR);
323
+ if (catalogIdx < 0)
324
+ throw new Error("Could not find model catalog anchor");
325
+ const ctx = buildEvalContext(source, catalogIdx);
326
+ if (wt && wtName)
327
+ ctx[wtName] = wt;
328
+ if (spec) {
329
+ ctx[spec.chatComplete] = "chatComplete";
330
+ ctx[spec.responses] = "responses";
331
+ if (spec.qt && wt?.VERCEL_AI_GATEWAY)
332
+ ctx[spec.qt] = wt.VERCEL_AI_GATEWAY;
333
+ }
334
+ const candidates = [];
335
+ try {
336
+ candidates.push(...findEnclosingObjectCandidates(source, CATALOG_ANCHOR, catalogIdx));
337
+ }
338
+ catch {
339
+ // ignore
340
+ }
341
+ try {
342
+ candidates.push(findBalancedObject(source, CATALOG_ANCHOR));
343
+ }
344
+ catch {
345
+ // ignore
346
+ }
347
+ if (candidates.length === 0)
348
+ throw new Error("Could not locate model catalog object");
349
+ let lastError = null;
350
+ for (const raw of candidates) {
351
+ try {
352
+ const value = evaluateWithContext(normalizeForEval(raw), ctx);
353
+ if (isModelCatalog(value))
354
+ return value;
355
+ }
356
+ catch (err) {
357
+ // keep the first real failure (e.g. "$R is not defined") — it names the
358
+ // missing binding; later candidates usually fail on the same cause
359
+ lastError ??= err;
360
+ }
361
+ }
362
+ const detail = lastError instanceof Error ? `: ${lastError.message}` : "";
363
+ throw new Error(`Could not evaluate model catalog${detail}`);
364
+ }
365
+ function isCostMap(value) {
366
+ if (!value || typeof value !== "object" || Array.isArray(value))
367
+ return false;
368
+ const vals = Object.values(value);
369
+ if (vals.length === 0)
370
+ return false;
371
+ // At least one provider bucket should be an array of cost rows
372
+ return vals.some((v) => Array.isArray(v) &&
373
+ v.length > 0 &&
374
+ typeof v[0] === "object" &&
375
+ v[0] !== null &&
376
+ typeof v[0].promptCost === "number");
377
+ }
378
+ export function extractCostData(source, wt, wtName) {
379
+ let anchorIdx = -1;
380
+ let usedAnchor = null;
381
+ for (const anchor of COST_ANCHORS) {
382
+ const idx = source.indexOf(anchor);
383
+ if (idx >= 0) {
384
+ anchorIdx = idx;
385
+ usedAnchor = anchor;
386
+ break;
387
+ }
388
+ }
389
+ if (anchorIdx < 0 || !usedAnchor)
390
+ throw new Error("Could not find cost data anchor");
391
+ const candidates = findEnclosingObjectCandidates(source, usedAnchor, anchorIdx);
392
+ const catalogIdx = source.indexOf(CATALOG_ANCHOR);
393
+ const ctx = buildEvalContext(source, catalogIdx >= 0 ? catalogIdx : anchorIdx);
394
+ if (wt && wtName)
395
+ ctx[wtName] = wt;
396
+ for (const raw of candidates) {
397
+ try {
398
+ const value = evaluateWithContext(normalizeForEval(raw), ctx);
399
+ if (isCostMap(value))
400
+ return value;
401
+ }
402
+ catch {
403
+ // try next enclosing span
404
+ }
405
+ }
406
+ throw new Error("Could not evaluate cost data map");
407
+ }
408
+ export function buildCostMap(costs) {
409
+ const map = new Map();
410
+ for (const arr of Object.values(costs)) {
411
+ for (const entry of arr) {
412
+ const colonIdx = entry.id.indexOf(":");
413
+ const bareId = colonIdx >= 0 ? entry.id.slice(colonIdx + 1) : entry.id;
414
+ map.set(bareId, entry);
415
+ }
416
+ }
417
+ return map;
418
+ }
419
+ export function buildModelEntry(entry, costMap) {
420
+ const provider = entry.provider || "unknown";
421
+ const tier = TIER_MAP[provider] ?? "open-source";
422
+ const costEntry = costMap.get(entry.id);
423
+ let cost;
424
+ if (costEntry) {
425
+ cost = {
426
+ input: costEntry.promptCost,
427
+ output: costEntry.completionCost,
428
+ };
429
+ if (costEntry.cacheHitCost > 0)
430
+ cost.cache_read = costEntry.cacheHitCost;
431
+ if (costEntry.cacheWrite5mCost > 0)
432
+ cost.cache_write = costEntry.cacheWrite5mCost;
433
+ }
434
+ else {
435
+ // ponytail: sync fills real prices (docs → free $0 → models.dev); this is only the unmatched placeholder
436
+ cost = { input: 0.5, output: 2 };
437
+ }
438
+ const fallback = FALLBACK_LIMITS[entry.id];
439
+ const limit = {
440
+ context: entry.contextWindow ?? fallback?.context ?? 200000,
441
+ output: entry.maxOutputTokens ?? fallback?.output ?? 65536,
442
+ };
443
+ const efforts = entry.reasoningEfforts?.length ? [...entry.reasoningEfforts] : undefined;
444
+ const input = entry.inputModalities?.filter((x) => typeof x === "string") ?? [];
445
+ const fromCli = input.length > 0
446
+ ? {
447
+ attachment: input.includes("image"),
448
+ modalities: { input: [...input], output: ["text"] },
449
+ }
450
+ : {};
451
+ return {
452
+ id: entry.id,
453
+ name: entry.name,
454
+ tier,
455
+ reasoning: entry.reasoning || (efforts?.length ?? 0) > 0,
456
+ ...(efforts ? { reasoningEfforts: efforts } : {}),
457
+ tool_call: true,
458
+ cost,
459
+ limit,
460
+ ...fromCli,
461
+ };
462
+ }
463
+ export function disambiguateModelNames(entries) {
464
+ const groups = new Map();
465
+ for (const entry of entries) {
466
+ const group = groups.get(entry.name) ?? [];
467
+ group.push(entry);
468
+ groups.set(entry.name, group);
469
+ }
470
+ for (const group of groups.values()) {
471
+ if (group.length < 2)
472
+ continue;
473
+ for (const entry of group) {
474
+ const suffix = entry.id.split("/").pop() ?? entry.id;
475
+ const normalized = suffix.replace(/[-_]/g, " ");
476
+ if (normalized.toLowerCase().includes("free")) {
477
+ entry.name = `${entry.name} Free`;
478
+ }
479
+ else if (normalized.toLowerCase() !== entry.name.toLowerCase()) {
480
+ entry.name = `${entry.name} (${suffix})`;
481
+ }
482
+ }
483
+ }
484
+ return entries;
485
+ }
486
+ export function sortModelEntries(entries) {
487
+ disambiguateModelNames(entries);
488
+ return entries.sort((a, b) => {
489
+ if (a.tier !== b.tier)
490
+ return a.tier === "premium" ? -1 : 1;
491
+ return a.name.localeCompare(b.name);
492
+ });
493
+ }
494
+ export function loadCatalogFromBundle(source) {
495
+ const models = extractModelCatalog(source);
496
+ let costMap = new Map();
497
+ try {
498
+ costMap = buildCostMap(extractCostData(source));
499
+ }
500
+ catch {
501
+ // ponytail: CLI cost map is optional; buildModelEntry uses unmatched placeholder until sync fills prices
502
+ }
503
+ const entries = [];
504
+ for (const model of Object.values(models)) {
505
+ if (!model || typeof model !== "object" || typeof model.id !== "string")
506
+ continue;
507
+ const entry = buildModelEntry(model, costMap);
508
+ if (entry)
509
+ entries.push(entry);
510
+ }
511
+ for (const extra of HARDCODED_EXTRAS) {
512
+ if (!entries.some((e) => e.id === extra.id)) {
513
+ const entry = buildModelEntry(extra, costMap);
514
+ if (entry)
515
+ entries.push(entry);
516
+ }
517
+ }
518
+ return sortModelEntries(entries);
519
+ }
520
+ function readPackageMeta(root) {
521
+ const pkgPath = join(root, "package.json");
522
+ if (!existsSync(pkgPath))
523
+ return null;
524
+ try {
525
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
526
+ const binPaths = [];
527
+ if (typeof pkg.bin === "string")
528
+ binPaths.push(join(root, pkg.bin));
529
+ else if (pkg.bin && typeof pkg.bin === "object") {
530
+ for (const rel of Object.values(pkg.bin)) {
531
+ if (typeof rel === "string")
532
+ binPaths.push(join(root, rel));
533
+ }
534
+ }
535
+ // Prefer the full CLI bundle. Newer command-code ships dist/index.mjs as a
536
+ // tiny re-export stub; the catalog lives in dist/cli.mjs (or bin target).
537
+ const candidates = [
538
+ join(root, "dist", "cli.mjs"),
539
+ ...binPaths,
540
+ join(root, "dist", "index.mjs"),
541
+ pkg.module ? join(root, pkg.module) : "",
542
+ pkg.main ? join(root, pkg.main) : "",
543
+ ].filter(Boolean);
544
+ let best = null;
545
+ for (const candidate of candidates) {
546
+ if (!existsSync(candidate))
547
+ continue;
548
+ try {
549
+ const size = statSync(candidate).size;
550
+ // Skip tiny launcher stubs (< 4KB) that only re-export another file
551
+ if (size < 4096)
552
+ continue;
553
+ if (!best || size > best.size)
554
+ best = { path: candidate, size };
555
+ }
556
+ catch {
557
+ // ignore unreadable candidate
558
+ }
559
+ }
560
+ if (best) {
561
+ return { version: pkg.version ?? "unknown", bundlePath: best.path };
562
+ }
563
+ }
564
+ catch {
565
+ return null;
566
+ }
567
+ return null;
568
+ }
569
+ function asPackageRoot(path) {
570
+ const resolved = resolvePath(path);
571
+ if (!existsSync(resolved))
572
+ return null;
573
+ // Allow pointing at a file; still prefer the full CLI bundle under the package root
574
+ if (resolved.endsWith(".mjs") || resolved.endsWith(".js")) {
575
+ const root = dirname(dirname(resolved));
576
+ const meta = readPackageMeta(root);
577
+ if (meta)
578
+ return { root, bundlePath: meta.bundlePath, version: meta.version };
579
+ try {
580
+ if (statSync(resolved).size >= 4096) {
581
+ return { root, bundlePath: resolved, version: "unknown" };
582
+ }
583
+ }
584
+ catch {
585
+ return null;
586
+ }
587
+ return null;
588
+ }
589
+ const meta = readPackageMeta(resolved);
590
+ if (!meta)
591
+ return null;
592
+ return { root: resolved, bundlePath: meta.bundlePath, version: meta.version };
593
+ }
594
+ function tryRequireResolve() {
595
+ try {
596
+ const require = createRequire(import.meta.url);
597
+ const pkgJson = require.resolve(`${NPM_PACKAGE}/package.json`);
598
+ return asPackageRoot(dirname(pkgJson));
599
+ }
600
+ catch {
601
+ // try resolving from cwd
602
+ }
603
+ try {
604
+ const require = createRequire(join(process.cwd(), "package.json"));
605
+ const pkgJson = require.resolve(`${NPM_PACKAGE}/package.json`);
606
+ return asPackageRoot(dirname(pkgJson));
607
+ }
608
+ catch {
609
+ return null;
610
+ }
611
+ }
612
+ function walkNodeModules(startDir) {
613
+ let dir = resolvePath(startDir);
614
+ for (let i = 0; i < 12; i++) {
615
+ const candidate = join(dir, "node_modules", NPM_PACKAGE);
616
+ const found = asPackageRoot(candidate);
617
+ if (found)
618
+ return found;
619
+ const parent = dirname(dir);
620
+ if (parent === dir)
621
+ break;
622
+ dir = parent;
623
+ }
624
+ return null;
625
+ }
626
+ function tryNpmRootGlobal() {
627
+ try {
628
+ const root = execSync("npm root -g", {
629
+ encoding: "utf-8",
630
+ stdio: ["ignore", "pipe", "ignore"],
631
+ timeout: 3000,
632
+ }).trim();
633
+ if (!root)
634
+ return null;
635
+ return asPackageRoot(join(root, NPM_PACKAGE));
636
+ }
637
+ catch {
638
+ return null;
639
+ }
640
+ }
641
+ function tryWindowsAppData() {
642
+ const appData = process.env.APPDATA;
643
+ if (!appData)
644
+ return null;
645
+ return asPackageRoot(join(appData, "npm", "node_modules", NPM_PACKAGE));
646
+ }
647
+ export function resolveCommandCodePackage(options) {
648
+ const explicit = options?.packagePath?.trim() || process.env.COMMANDCODE_PACKAGE_PATH?.trim() || "";
649
+ if (explicit) {
650
+ const found = asPackageRoot(explicit);
651
+ if (found)
652
+ return found;
653
+ }
654
+ return (tryRequireResolve() ||
655
+ walkNodeModules(process.cwd()) ||
656
+ tryNpmRootGlobal() ||
657
+ tryWindowsAppData() ||
658
+ null);
659
+ }
660
+ export function loadCatalogFromLocalCommandCode(options) {
661
+ try {
662
+ const resolved = resolveCommandCodePackage(options);
663
+ if (!resolved)
664
+ return null;
665
+ const source = readFileSync(resolved.bundlePath, "utf-8");
666
+ const models = loadCatalogFromBundle(source);
667
+ if (models.length === 0)
668
+ return null;
669
+ return { models, version: resolved.version, root: resolved.root, bundleSource: source };
670
+ }
671
+ catch {
672
+ return null;
673
+ }
674
+ }
675
+ export function toConfigKey(id) {
676
+ const slashIdx = id.indexOf("/");
677
+ const short = slashIdx >= 0 ? id.slice(slashIdx + 1) : id;
678
+ return short.toLowerCase();
679
+ }
680
+ export function generateOpencodeModels(entries) {
681
+ const models = {};
682
+ for (const entry of entries) {
683
+ const key = toConfigKey(entry.id);
684
+ const costObj = { input: entry.cost.input, output: entry.cost.output };
685
+ if (entry.cost.cache_read !== undefined)
686
+ costObj.cache_read = entry.cost.cache_read;
687
+ if (entry.cost.cache_write !== undefined)
688
+ costObj.cache_write = entry.cost.cache_write;
689
+ const model = {
690
+ id: entry.id,
691
+ name: entry.name,
692
+ reasoning: entry.reasoning,
693
+ tool_call: entry.tool_call,
694
+ attachment: entry.attachment ?? false,
695
+ modalities: entry.modalities ?? { input: ["text"], output: ["text"] },
696
+ cost: costObj,
697
+ limit: entry.limit,
698
+ };
699
+ if (entry.reasoningEfforts && entry.reasoningEfforts.length > 0) {
700
+ model.reasoningEfforts = entry.reasoningEfforts;
701
+ const variants = {};
702
+ for (const effort of entry.reasoningEfforts) {
703
+ variants[effort] = { reasoningEffort: effort };
704
+ }
705
+ model.variants = variants;
706
+ }
707
+ models[key] = model;
708
+ }
709
+ return models;
710
+ }
711
+ export const MODELS_API_URL = "https://api.commandcode.ai/provider/v1/models";
712
+ function isNonEmptyString(value) {
713
+ return typeof value === "string" && value.length > 0;
714
+ }
715
+ function parseSupportedEndpoints(value) {
716
+ if (!Array.isArray(value))
717
+ return undefined;
718
+ const endpoints = value.filter((item) => typeof item === "string" && item.length > 0);
719
+ return endpoints.length > 0 ? endpoints : undefined;
720
+ }
721
+ /** Validate the OpenAI-style `{ object: "list", data: [{ id }] }` availability payload. */
722
+ export function parseAvailability(payload) {
723
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
724
+ throw new Error("availability response must be an object");
725
+ }
726
+ const body = payload;
727
+ if (body["object"] !== "list")
728
+ throw new Error('availability response object must be "list"');
729
+ const data = body["data"];
730
+ if (!Array.isArray(data) || data.length === 0) {
731
+ throw new Error("availability response data must be a non-empty array");
732
+ }
733
+ const models = [];
734
+ const seen = new Set();
735
+ for (const item of data) {
736
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
737
+ throw new Error("availability response items must be objects with a non-empty string id");
738
+ }
739
+ const row = item;
740
+ const id = row["id"];
741
+ if (!isNonEmptyString(id)) {
742
+ throw new Error("availability response items must be objects with a non-empty string id");
743
+ }
744
+ if (seen.has(id))
745
+ throw new Error(`duplicate availability id: ${id}`);
746
+ seen.add(id);
747
+ const supportedEndpoints = parseSupportedEndpoints(row["supported_endpoints"]);
748
+ models.push(supportedEndpoints ? { id, supportedEndpoints } : { id });
749
+ }
750
+ return models;
751
+ }
752
+ /** Validate the OpenAI-style `{ object: "list", data: [{ id }] }` availability payload. */
753
+ export function parseAvailabilityIds(payload) {
754
+ return parseAvailability(payload).map((model) => model.id);
755
+ }
756
+ /**
757
+ * Copy `supported_endpoints` from the availability payload onto matching
758
+ * entries. Entries the payload omits, or lists without usable endpoints, are
759
+ * left untouched — a partial payload never strips transport data already on
760
+ * the catalog. Returns how many entries were updated.
761
+ */
762
+ export function applyAvailabilityEndpoints(entries, availability) {
763
+ const byId = new Map(availability.map((model) => [model.id, model.supportedEndpoints]));
764
+ let updated = 0;
765
+ for (const entry of entries) {
766
+ const endpoints = byId.get(entry.id);
767
+ if (!endpoints)
768
+ continue;
769
+ entry.supportedEndpoints = endpoints;
770
+ updated++;
771
+ }
772
+ return updated;
773
+ }
774
+ /** Retain only candidates whose exact ID is callable; collect sorted excluded IDs. */
775
+ export function filterCatalogByAvailability(candidates, availableIds) {
776
+ const available = new Set(availableIds);
777
+ const retained = candidates.filter((entry) => available.has(entry.id));
778
+ const unavailable = candidates
779
+ .filter((entry) => !available.has(entry.id))
780
+ .map((entry) => entry.id)
781
+ .sort();
782
+ return { retained, unavailable };
783
+ }
784
+ export function catalogModuleDir() {
785
+ return dirname(fileURLToPath(import.meta.url));
786
+ }