This repository was archived by the owner on Aug 21, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathmodels.ts
More file actions
218 lines (196 loc) · 6.43 KB
/
Copy pathmodels.ts
File metadata and controls
218 lines (196 loc) · 6.43 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
/**
* Command Code model catalog fetched from the public provider API.
* Request-time lookups use the last successful snapshot; async lifecycle hooks
* refresh it without making the local CLI a runtime dependency.
*/
import {
EFFORT_LEVELS,
type CommandEffort,
DEFAULT_MODEL_ID,
LAGUNA_MODEL_ID,
} from "./constants.js";
import {
discoverCommandModels,
fallbackCommandModels,
type DiscoveredModelMeta,
type ModelCostRates,
} from "./model-discover.js";
import { log } from "./log.js";
export type { ModelCostRates };
export type CommandModel = {
id: string;
name: string;
resolvedId: string;
reasoning: boolean;
contextWindow: number;
maxTokens: number;
/** Vision / image input support on the upstream model. */
vision: boolean;
/** Free-tier badge. */
free?: boolean;
/** Supported effort levels from Command Code (empty → model decides). */
efforts?: CommandEffort[];
/** Advertised $/1M token rates (OpenCode `model.cost`). */
cost?: ModelCostRates;
};
const CATALOG_TTL_MS = 30 * 60 * 1000;
let cachedModels: CommandModel[] | null = null;
let cachedAt = 0;
let refreshInFlight: Promise<CommandModel[]> | null = null;
export const GENERATED_VARIANT_KEYS = [
"none",
"minimal",
"low",
"medium",
"high",
"xhigh",
"max",
] as const;
/** Placeholder so OpenCode keeps the provider visible while logged out. */
export const LOGIN_PLACEHOLDER_MODELS: CommandModel[] = [
{
id: "login",
name: "Sign in to Command Code",
resolvedId: "login",
reasoning: false,
contextWindow: 256_000,
maxTokens: 8_192,
vision: false,
},
];
function metaToModel(meta: DiscoveredModelMeta): CommandModel {
return {
id: meta.id,
name: meta.name,
resolvedId: meta.id,
reasoning: meta.reasoning || meta.efforts.length > 0,
contextWindow: meta.contextWindow,
maxTokens: meta.maxTokens,
vision: meta.vision,
free: meta.free || undefined,
efforts: meta.efforts.length ? meta.efforts : undefined,
cost: meta.cost,
};
}
function normalizeCatalog(models: CommandModel[]): CommandModel[] {
const unique = new Map<string, CommandModel>();
for (const model of models) {
const key = model.resolvedId.toLowerCase();
if (!unique.has(key)) unique.set(key, model);
}
return [...unique.values()].sort((a, b) => {
const rank = (m: CommandModel) =>
m.resolvedId === LAGUNA_MODEL_ID ? 0 : m.free ? 1 : 2;
return rank(a) - rank(b) || a.name.localeCompare(b.name);
});
}
export function invalidateCommandModelCache(): void {
cachedModels = null;
cachedAt = 0;
}
/** Force a fresh discovery from the public Command Code model API. */
export async function refreshCommandModels(options?: {
fetchFn?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
url?: string;
}): Promise<CommandModel[]> {
if (refreshInFlight) return refreshInFlight;
refreshInFlight = (async () => {
try {
const discovered = await discoverCommandModels(options);
cachedModels = normalizeCatalog(discovered.map(metaToModel));
cachedAt = Date.now();
log.info("[opencode-commandcode] model catalog refreshed", { count: cachedModels.length });
return cachedModels;
} catch (error) {
if (cachedModels) {
log.warn("[opencode-commandcode] model catalog refresh failed; keeping cached catalog", error instanceof Error ? error.message : error);
return cachedModels;
}
cachedModels = normalizeCatalog(fallbackCommandModels().map(metaToModel));
cachedAt = Date.now();
log.warn("[opencode-commandcode] model catalog unavailable; using fallback", error instanceof Error ? error.message : error);
return cachedModels;
} finally {
refreshInFlight = null;
}
})();
return refreshInFlight;
}
/**
* Current catalog snapshot for synchronous request translation.
*/
export function getCommandModels(): CommandModel[] {
if (!cachedModels) {
cachedModels = normalizeCatalog(fallbackCommandModels().map(metaToModel));
}
if (Date.now() - cachedAt >= CATALOG_TTL_MS && !refreshInFlight) {
void refreshCommandModels();
}
return cachedModels;
}
/** Snapshot alias used by older call sites / tests. */
export function listCommandCodeModels(): CommandModel[] {
return getCommandModels();
}
export function isLoginPlaceholderModel(id: string): boolean {
return id === "login";
}
export function resolveCommandModelId(modelId: string): string {
const cleaned = modelId.replace(/^command-code\//, "").trim();
if (!cleaned || cleaned === DEFAULT_MODEL_ID || cleaned === "laguna") {
return LAGUNA_MODEL_ID;
}
const models = getCommandModels();
const exact = models.find(
(m) => m.id === cleaned || m.resolvedId === cleaned,
);
if (exact) return exact.resolvedId;
if (!cleaned.includes("/")) {
const bySuffix = models.find((m) =>
m.resolvedId.toLowerCase().endsWith(`/${cleaned.toLowerCase()}`),
);
if (bySuffix) return bySuffix.resolvedId;
}
// Case-insensitive full id match
const ci = models.find(
(m) => m.resolvedId.toLowerCase() === cleaned.toLowerCase(),
);
if (ci) return ci.resolvedId;
// Pass through unknown ids to the gateway (BYO / newly listed models).
return cleaned;
}
export function findCommandModel(modelId: string): CommandModel | undefined {
const cleaned = modelId.replace(/^command-code\//, "").trim();
const models = getCommandModels();
const resolved = resolveCommandModelId(cleaned);
return (
models.find((m) => m.id === cleaned || m.resolvedId === cleaned) ||
models.find((m) => m.resolvedId === resolved) ||
models.find((m) => m.resolvedId.toLowerCase() === resolved.toLowerCase())
);
}
export function buildEffortVariants(
model: CommandModel,
): Record<string, { effort: CommandEffort } | { disabled: true }> {
if (isLoginPlaceholderModel(model.id)) return {};
const supported =
model.efforts && model.efforts.length > 0
? model.efforts
: model.reasoning
? [...EFFORT_LEVELS]
: [];
if (supported.length === 0) return {};
const variants: Record<
string,
{ effort: CommandEffort } | { disabled: true }
> = Object.fromEntries(supported.map((effort) => [effort, { effort }]));
for (const key of GENERATED_VARIANT_KEYS) {
if (!(key in variants)) variants[key] = { disabled: true };
}
return variants;
}
export function buildConfigVariants(
model: CommandModel,
): Record<string, { effort: CommandEffort } | { disabled: true }> {
return buildEffortVariants(model);
}