Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
373 lines (356 loc) · 11.4 KB
/
Copy pathindex.ts
File metadata and controls
373 lines (356 loc) · 11.4 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
// Dual OpenCode entrypoint (one default export carries both APIs):
// v1 (>=1.18.29) calls `server()` and consumes the returned hook map
// v2 (>=2.0.0) decodes `{ id, setup }` and calls `setup(context)`
// The two halves are independent implementations; v2 does not translate v1
// hooks. Both share ./cli.ts: usage rendering is delegated to the cmduse CLI
// (Rust cmduse-core) rather than reimplemented in TS.
import type { Plugin as PluginV1 } from "@opencode-ai/plugin";
import { z } from "zod";
import pkg from "../package.json";
import { whoami } from "./api";
import { modelCost, supportsImage } from "./catalog";
import { runCmduse, runMpc } from "./cli";
import { PROVIDER_BASE } from "./constants/endpoints";
import {
DEFAULT_CONTEXT_LENGTH,
DEFAULT_OUTPUT_TOKENS,
MODEL_CAPABILITIES,
} from "./constants/models";
import {
MPC_TOOL_ARG_DESCRIPTION,
MPC_TOOL_DESCRIPTION,
TOOL_DESCRIPTION,
} from "./constants/providers";
import { resolveKey } from "./key";
import { loadModels } from "./models";
import { commandCodeV2 } from "./v2";
/**
* The runtime provider specifier opencode installs for our models: our own
* package at the exact version, so plugin and provider can never drift (the
* package cache is keyed by the specifier string and never refreshed). v1's
* provider loader imports this module and takes the first export whose name
* starts with `create` — `createCommandCode` below.
*/
const PROVIDER_NPM = `${pkg.name}@${pkg.version}`;
/** Runtime `tool()` in @opencode-ai/plugin is the identity function — the
* host builds tools from plain objects, so we define ours inline and import
* only types from the plugin package. `zod` (a real schema) stays, since the
* host reads `args` to build the tool's input shape. */
function tool<Args extends z.ZodRawShape>(input: {
description: string;
args: Args;
execute: (args: { arg?: string }) => Promise<string>;
}): {
description: string;
args: Args;
execute: (args: { arg?: string }) => Promise<string>;
} {
return input;
}
type SdkModel = {
id: string;
providerID: string;
api: { id: string; url: string; npm: string };
name: string;
capabilities: {
temperature: boolean;
reasoning: boolean;
attachment: boolean;
toolcall: boolean;
input: {
text: boolean;
audio: boolean;
image: boolean;
video: boolean;
pdf: boolean;
};
output: {
text: boolean;
audio: boolean;
image: boolean;
video: boolean;
pdf: boolean;
};
/** A `{field}` object names the wire field reasoning must round-trip
* through (openai-compatible: "reasoning_content"). Without it,
* DeepSeek/GLM/Kimi reject the next request once an assistant turn
* carries no reasoning (compaction, model switch):
* "reasoning_content must be passed back". */
interleaved: boolean | { field: string };
};
cost: {
input: number;
output: number;
cache: { read: number; write: number };
};
limit: { context: number; output: number };
status: "alpha" | "beta" | "deprecated" | "active";
options: Record<string, unknown>;
headers: Record<string, string>;
release_date: string;
/** opencode's config-hook model merge reads top-level `interleaved`;
* its provider.models hook reads `capabilities.interleaved`. Set both. */
interleaved?: boolean | { field: string };
};
/** Published $/1M rates, so opencode prices a subscription provider correctly. */
function costFor(id: string): {
input: number;
output: number;
cache: { read: number; write: number };
} {
const cost = modelCost(id);
return {
input: cost?.input ?? 0,
output: cost?.output ?? 0,
cache: { read: cost?.cacheRead ?? 0, write: cost?.cacheWrite ?? 0 },
};
}
/** Full ModelV2 shapes — the provider.models hook must return complete records. */
function toModelDefs(
models: Array<{ id: string; name: string; contextLength: number }>,
providerID: string,
npm: string,
interleaved: boolean | { field: string } = false,
): Record<string, SdkModel> {
return Object.fromEntries(
models.map((m) => [
m.id,
{
id: m.id,
providerID,
api: { id: m.id, url: PROVIDER_BASE, npm },
name: m.name,
// The listing API has no capabilities, so vision comes from the
// generated modalities table; text-only is the fallback.
capabilities: {
...MODEL_CAPABILITIES,
interleaved,
...(supportsImage(m.id)
? {
attachment: true,
input: {
...MODEL_CAPABILITIES.input,
image: true,
},
}
: {}),
},
cost: costFor(m.id),
limit: {
context: m.contextLength || DEFAULT_CONTEXT_LENGTH,
output: DEFAULT_OUTPUT_TOKENS,
},
status: "active" as const,
options: {},
headers: {},
release_date: "",
...(interleaved !== false ? { interleaved } : {}),
},
]),
);
}
export const CommandCodePlugin: PluginV1 = async (_input) => {
return {
// /connect entry for the Claude lane. The open lane (`command-code`) is
// intended to share the key via the user's existing manual config or via
// options.apiKey injected at startup, so no second /connect entry is
// needed.
auth: {
provider: "command-code-anthropic",
loader: async (getAuth) => {
const auth = await getAuth();
if (auth?.type !== "api") {
throw new Error(
"No API key available. Please run '/connect' and choose Command Code (Anthropic).",
);
}
return { apiKey: auth.key, baseURL: PROVIDER_BASE };
},
methods: [
{
type: "api",
label: "Command Code API key (Claude / Anthropic)",
prompts: [
{
type: "text",
key: "apiKey",
message:
"Command Code API key (create at commandcode.ai/settings/keys)",
},
],
async authorize(inputs) {
const key = inputs?.apiKey?.trim();
if (!key) return { type: "failed" };
try {
const me = await whoami(key);
if (!me.success) return { type: "failed" };
return {
type: "success",
key,
provider: "command-code-anthropic",
};
} catch {
return { type: "failed" };
}
},
},
],
},
// Register the Claude and OpenAI-compatible lanes. The two provider
// ids this plugin owns (`command-code-anthropic`, `command-code-openai`)
// are set here; user-defined entries for the same ids are preserved.
config: async (cfg) => {
cfg.provider ??= {};
type ProviderModels = NonNullable<
NonNullable<(typeof cfg)["provider"]>[string]["models"]
>;
const existing = (
id: string,
): {
models?: ProviderModels;
options?: Record<string, unknown>;
npm?: string;
name?: string;
} =>
(cfg.provider?.[id] ?? {}) as {
models?: ProviderModels;
options?: Record<string, unknown>;
npm?: string;
name?: string;
};
let split: Awaited<ReturnType<typeof loadModels>> | undefined;
let openKey: string | undefined;
// No key at config-hook time is expected for /connect-only users
// (the key lives in the auth store, unreadable here) — the
// provider.models hook below fills models with auth injected.
try {
openKey = await resolveKey();
} catch {}
// But a key we DID resolve followed by a fetch failure is a real
// error (bad key / network) worth surfacing, not swallowing.
if (openKey) {
try {
split = await loadModels(openKey);
} catch (e) {
console.warn("[command-code] model list unavailable:", e);
}
}
// ponytail: config-hook models cover old paths; provider.models hook
// (below) covers >=1.14.49. User-defined models always win the merge.
// upgrade: drop config-hook registration once minimum supported opencode
// is >=1.14.49 (provider.models hook supersedes it).
// Verify 2026-09: `opencode models` (headless) lists command-code-openai/*
// via the config hook, but zero command-code-anthropic/* — the anthropic
// lane is auth-gated (its /connect entry has no stored key headlessly).
// Confirm in the TUI after /connect, not via the CLI listing.
const claudeDefs = split
? toModelDefs(
split.claude,
"command-code-anthropic",
PROVIDER_NPM,
)
: {};
const openDefs = split
? toModelDefs(split.open, "command-code-openai", PROVIDER_NPM, {
field: "reasoning_content",
})
: {};
const userAnthropic = existing("command-code-anthropic");
cfg.provider["command-code-anthropic"] = {
npm: userAnthropic.npm ?? PROVIDER_NPM,
name: userAnthropic.name ?? "Command Code (Anthropic)",
options: { baseURL: PROVIDER_BASE, ...userAnthropic.options },
models: { ...claudeDefs, ...userAnthropic.models },
};
// open lane: opencode only injects stored auth for providers with
// their own /connect entry; share the key via options.apiKey
// resolved at startup (resolves against auth store + CLI auth.json).
// ponytail: the plugin API allows one auth hook + one provider hook,
// both bound to a single provider id, so a /connect-only user with no
// ~/.commandcode/auth.json gets no open-lane models/key here. Fixing
// that needs a second plugin entry (or an upstream multi-provider
// hook); until then the open lane requires cmd login or options.apiKey.
const userOpenai = existing("command-code-openai");
cfg.provider["command-code-openai"] = {
npm: userOpenai.npm ?? PROVIDER_NPM,
name: userOpenai.name ?? "Command Code (OpenAI)",
options: {
baseURL: PROVIDER_BASE,
...(openKey ? { apiKey: openKey } : {}),
...userOpenai.options,
},
models: { ...openDefs, ...userOpenai.models },
};
// /cmd-usage command -> agent calls the cmd_usage tool
cfg.command ??= {};
cfg.command["cmd-usage"] = {
description:
"Show Command Code plan, credits, and usage windows",
template:
"Call the cmd_usage tool and present its markdown output verbatim to the user. If the tool errors, tell the user to run /connect (Command Code (Anthropic)) and retry. $ARGUMENTS",
};
},
// opencode >=1.14.49 resolves the model list here, with auth injected.
provider: {
id: "command-code-anthropic",
models: async (_provider, ctx) => {
const key = await resolveKey(async () => {
const a = ctx.auth;
return a?.type === "api" && a.key
? { key: a.key }
: undefined;
});
const split = await loadModels(key);
return toModelDefs(
split.claude,
"command-code-anthropic",
PROVIDER_NPM,
);
},
},
tool: {
cmd_usage: tool({
description: TOOL_DESCRIPTION,
args: {
arg: z
.string()
.optional()
.describe(
"Optional: 'plans' for the plan table only, or extra cmduse flags",
),
},
// Rendering lives in the cmduse binary (Rust core); this is a thin
// spawn wrapper. Piped stdout is plain text (colors auto-off).
async execute(args) {
const key = await resolveKey();
return runCmduse(args.arg ?? "", {
env: { CMD_API_KEY: key },
});
},
}),
mpc_prices: tool({
description: MPC_TOOL_DESCRIPTION,
args: {
arg: z
.string()
.optional()
.describe(MPC_TOOL_ARG_DESCRIPTION),
},
// Rendering lives in the mpc binary; this is a thin
// spawn wrapper, same as cmd_usage above.
async execute(args) {
const key = await resolveKey();
return runMpc(args.arg ?? "", {
env: { CMD_API_KEY: key },
});
},
}),
},
};
};
export { createCommandCode } from "./provider";
export default {
...commandCodeV2,
/** v1 entrypoint (opencode >=1.18.29 object entrypoints). */
server: CommandCodePlugin,
};