This repository was archived by the owner on Aug 21, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
450 lines (422 loc) · 12.6 KB
/
Copy pathindex.ts
File metadata and controls
450 lines (422 loc) · 12.6 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
/**
* OpenCode Command Code Auth Plugin
*
* Enables Command Code models inside OpenCode via:
* 1. Command Code browser login with a local callback
* 2. Local OpenAI-compatible proxy → api.commandcode.ai /alpha/generate
* 3. Dynamic model catalog from the public Command Code API
* 4. Tools/MCP park-resume, attachments, compact, and usage accounting
*
* Register in opencode.json:
* { "plugin": ["@openchamber/opencode-commandcode"] }
*/
import type { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin";
import {
completeCommandBrowserLogin,
getPendingCommandLogin,
resetPendingCommandLogin,
startCommandBrowserLogin,
} from "./auth-login.js";
import {
DEFAULT_MODEL_ID,
EFFORT_HEADER,
LAGUNA_MODEL_ID,
OPENAI_COMPATIBLE_NPM,
PROVIDER_ID,
REQUEST_KIND_HEADER,
SESSION_HEADER,
} from "./constants.js";
import { log } from "./log.js";
import { readCommandCodeApiKeyFromEnv } from "./credentials.js";
import { setMcpServers } from "./mcp-names.js";
import {
encodeCommandModelSelection,
resolveCommandModelSelection,
} from "./model-selection.js";
import {
buildConfigVariants,
buildEffortVariants,
getCommandModels,
refreshCommandModels,
type CommandModel,
} from "./models.js";
import {
getCommandProxyBaseUrl,
getProxyPort,
startProxy,
} from "./proxy.js";
type CommandApiAuth = {
type: "api" | "oauth";
key?: string;
access?: string;
refresh?: string;
expires?: number;
};
function isCommandAuth(auth: unknown): auth is CommandApiAuth {
if (!auth || typeof auth !== "object") return false;
const a = auth as CommandApiAuth;
return a.type === "api" || a.type === "oauth";
}
function authKey(auth: CommandApiAuth | null | undefined): string | null {
if (!auth) return null;
if (typeof auth.key === "string" && auth.key.trim()) return auth.key.trim();
if (typeof auth.access === "string" && auth.access.trim()) {
return auth.access.trim();
}
return null;
}
function zeroCost() {
return {
input: 0,
output: 0,
cache: { read: 0, write: 0 },
};
}
function billedCostUsd(value: unknown): number | undefined {
if (!value || typeof value !== "object") return undefined;
const usage = (value as { usage?: unknown }).usage;
if (!usage || typeof usage !== "object") return undefined;
const raw = (usage as { cost_usd?: unknown }).cost_usd;
const cost = typeof raw === "number" ? raw : typeof raw === "string" ? Number(raw) : NaN;
return Number.isFinite(cost) && cost >= 0 ? cost : undefined;
}
/** Bridge Command Code's exact billed USD into OpenCode's supported billed-cost metadata. */
export function commandCodeMetadataExtractor() {
const metadata = (value: unknown) => {
const cost = billedCostUsd(value);
if (cost === undefined) return undefined;
return { copilot: { totalNanoAiu: Math.round(cost * 100_000_000_000) } };
};
return {
async extractMetadata({ parsedBody }: { parsedBody: unknown }) {
return metadata(parsedBody);
},
createStreamExtractor() {
let result: ReturnType<typeof metadata>;
return {
processChunk(chunk: unknown) {
result = metadata(chunk) ?? result;
},
buildMetadata() {
return result;
},
};
},
};
}
function buildProviderModel(
model: CommandModel,
id: string,
baseURL: string,
): Record<string, unknown> {
const variants = buildEffortVariants(model);
const hasEffort = Object.values(variants).some(
(v) => v && typeof v === "object" && "effort" in v,
);
return {
id,
providerID: PROVIDER_ID,
api: {
id,
url: baseURL,
npm: OPENAI_COMPATIBLE_NPM,
},
name:
id === DEFAULT_MODEL_ID && model.id !== DEFAULT_MODEL_ID
? `Default (${model.name})`
: model.name,
capabilities: {
temperature: true,
reasoning: hasEffort,
attachment: true,
toolcall: true,
input: {
text: true,
audio: false,
image: model.vision,
video: false,
pdf: false,
},
output: {
text: true,
audio: false,
image: false,
video: false,
pdf: false,
},
interleaved: true,
},
modalities: {
input: model.vision ? ["text", "image"] : ["text"],
output: ["text"],
},
cost: model.cost ?? zeroCost(),
limit: {
context: model.contextWindow,
output: model.maxTokens,
},
status: "active",
options: {
includeUsage: true,
},
headers: {},
release_date: "",
variants,
};
}
function buildConfigModelEntry(model: CommandModel): Record<string, unknown> {
const variants = buildConfigVariants(model);
return {
name: model.name,
reasoning: model.reasoning,
tool_call: true,
modalities: {
input: model.vision ? ["text", "image"] : ["text"],
output: ["text"],
},
capabilities: {
tools: true,
input: model.vision ? ["text", "image"] : ["text"],
output: ["text"],
},
limit: {
context: model.contextWindow,
output: model.maxTokens,
},
options: {
includeUsage: true,
},
variants,
cost: model.cost ?? zeroCost(),
};
}
function buildProviderModels(
models: CommandModel[],
): Record<string, unknown> {
const baseURL = getCommandProxyBaseUrl();
const providerModels = Object.fromEntries(
models.map((model) => [
model.id,
buildProviderModel(model, model.id, baseURL),
]),
);
return providerModels;
}
function ensureProviderConfig(
config: Record<string, any>,
models: CommandModel[],
): void {
if (!config.provider || typeof config.provider !== "object") {
config.provider = {};
}
const existing = config.provider[PROVIDER_ID] ?? {};
const existingOptions =
existing.options && typeof existing.options === "object"
? existing.options
: {};
const existingModels =
existing.models && typeof existing.models === "object"
? existing.models
: {};
const baseURL = getCommandProxyBaseUrl();
const seededModels = Object.fromEntries(
models.map((model) => [model.id, buildConfigModelEntry(model)]),
);
config.provider[PROVIDER_ID] = {
...existing,
name:
typeof existing.name === "string" && existing.name.trim()
? existing.name
: "Command Code",
npm: existing.npm ?? OPENAI_COMPATIBLE_NPM,
options: {
baseURL,
apiKey: "command-code-proxy",
includeUsage: true,
metadataExtractor: commandCodeMetadataExtractor(),
...existingOptions,
},
models: {
...seededModels,
...existingModels,
},
};
}
async function resolveAccessToken(
getAuth: () => Promise<unknown>,
): Promise<string | null> {
const auth = await getAuth();
if (isCommandAuth(auth)) {
const key = authKey(auth);
if (key) return key;
}
return readCommandCodeApiKeyFromEnv();
}
async function loadRuntime(
getAuth: () => Promise<unknown>,
provider?: { models?: Record<string, unknown> },
): Promise<{ port: number; providerModels: Record<string, unknown> } | undefined> {
await resolveAccessToken(getAuth);
const models = await refreshCommandModels();
await startProxy(async () => resolveAccessToken(getAuth));
const providerModels = buildProviderModels(models);
if (provider) provider.models = providerModels;
return { port: getProxyPort() ?? 8797, providerModels };
}
/**
* OpenCode plugin that provides Command Code authentication and model access.
*/
export const CommandCodePlugin: Plugin = async (
_input: PluginInput,
): Promise<Hooks> => {
return {
async config(config) {
// Bind proxy first so provider baseURL matches the actual listening port.
await startProxy();
// Always seed the live catalog so the provider is discoverable.
const models = await refreshCommandModels();
ensureProviderConfig(config as Record<string, any>, models);
// Seed native MCP server names (from `mcp:` in opencode config) so the
// proxy can map tool names <server>_<tool> ↔ mcp__<server>__<tool>.
// This is what lets the gateway agent see OpenCode's MCP tools and
// lets OpenCode execute the calls natively via its own MCP clients.
const mcpConfig = (config as Record<string, any>).mcp;
if (mcpConfig && typeof mcpConfig === "object") {
setMcpServers(
Object.entries(mcpConfig as Record<string, unknown>)
.filter(([, entry]) => {
if (!entry || typeof entry !== "object") return true;
return (entry as { enabled?: unknown }).enabled !== false;
})
.map(([name]) => name),
);
}
},
"chat.headers": async (hookInput, output) => {
if (hookInput.model.providerID !== PROVIDER_ID) return;
const messageModel = hookInput.message.model as {
variant?: unknown;
};
const variant =
typeof messageModel.variant === "string"
? messageModel.variant
: undefined;
const selected = resolveCommandModelSelection(
hookInput.model.id,
variant,
);
output.headers[EFFORT_HEADER] = encodeCommandModelSelection(selected);
if (hookInput.sessionID) {
output.headers[SESSION_HEADER] = hookInput.sessionID;
}
if (hookInput.agent === "title") {
output.headers[REQUEST_KIND_HEADER] = "title";
}
},
"chat.params": async (hookInput, output) => {
if (hookInput.model.providerID !== PROVIDER_ID) return;
delete output.options.reasoningEffort;
},
"experimental.provider.small_model": async (hookInput, output) => {
if (hookInput.provider.id !== PROVIDER_ID) return;
output.model = Object.values(hookInput.provider.models)
.find((model) => model.id === LAGUNA_MODEL_ID);
},
provider: {
id: PROVIDER_ID,
async models(provider, ctx) {
const runtime = await loadRuntime(
async () => ctx.auth,
provider,
);
return (runtime?.providerModels ?? {}) as Record<string, any>;
},
},
auth: {
provider: PROVIDER_ID,
async loader(getAuth, provider) {
const runtime = await loadRuntime(getAuth, provider);
if (!runtime) return {};
return {
baseURL: getCommandProxyBaseUrl(),
apiKey: "command-code-proxy",
metadataExtractor: commandCodeMetadataExtractor(),
async fetch(
requestInput: RequestInfo | URL,
init?: RequestInit,
) {
if (init?.headers) {
if (init.headers instanceof Headers) {
init.headers.delete("authorization");
} else if (Array.isArray(init.headers)) {
init.headers = init.headers.filter(
([key]) => key.toLowerCase() !== "authorization",
);
} else {
delete (init.headers as Record<string, string>).authorization;
delete (init.headers as Record<string, string>).Authorization;
}
}
return fetch(requestInput, init);
},
};
},
methods: [
{
type: "oauth",
label: "Login with Command Code",
async authorize() {
let current = getPendingCommandLogin();
if (!current || current.completed) {
current = await startCommandBrowserLogin();
}
return {
url: current.url,
instructions:
"Open the URL and click Authorize. Return here after the browser says you're all set.",
method: "auto" as const,
async callback() {
try {
const tokens = await completeCommandBrowserLogin();
await refreshCommandModels();
return {
type: "success" as const,
refresh: tokens.refresh,
access: tokens.access,
expires: tokens.expires,
};
} catch (err) {
resetPendingCommandLogin();
log.error(
"[opencode-commandcode] Command Code login failed",
err instanceof Error ? err.message : err,
);
return { type: "failed" as const };
}
},
};
},
},
],
},
};
};
export default CommandCodePlugin;
export {
getCommandModels,
listCommandCodeModels,
refreshCommandModels,
invalidateCommandModelCache,
} from "./models.js";
export {
startProxy,
stopProxy,
getCommandProxyBaseUrl,
setStreamGenerateForTests,
} from "./proxy.js";
export {
getSessionUsage,
listSessionUsage,
totalUsageAcrossSessions,
resetUsageStore,
} from "./usage.js";