-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
251 lines (236 loc) · 8.76 KB
/
Copy pathindex.ts
File metadata and controls
251 lines (236 loc) · 8.76 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
import type { Plugin } from "@opencode-ai/plugin";
import { tool } from "@opencode-ai/plugin";
import { API_BASE, whoami } from "./api";
import { resolveKey } from "./key";
import { loadModels } from "./models";
import { plansTable, renderUsage } from "./usage";
const PROVIDER_BASE = `${API_BASE}/provider/v1`;
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 };
};
/** Every Command Code model shares these; hoisted so each record doesn't rebuild them. */
const MODEL_CAPABILITIES: Omit<SdkModel["capabilities"], "interleaved"> = {
temperature: true,
reasoning: true,
attachment: false,
toolcall: true,
input: { text: true, audio: false, image: false, video: false, pdf: false },
output: { text: true, audio: false, image: false, video: false, pdf: false },
};
/** 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,
capabilities: { ...MODEL_CAPABILITIES, interleaved },
cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
limit: { context: m.contextLength || 128_000, output: 32_000 },
status: "active" as const,
options: {},
headers: {},
release_date: "",
...(interleaved !== false ? { interleaved } : {}),
},
]),
);
}
export const CommandCodePlugin: Plugin = 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", "@ai-sdk/anthropic")
: {};
const openDefs = split
? toModelDefs(
split.open,
"command-code-openai",
"@ai-sdk/openai-compatible",
{ field: "reasoning_content" },
)
: {};
const userAnthropic = existing("command-code-anthropic");
cfg.provider["command-code-anthropic"] = {
npm: userAnthropic.npm ?? "@ai-sdk/anthropic",
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 ?? "@ai-sdk/openai-compatible",
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", "@ai-sdk/anthropic");
},
},
tool: {
cmd_usage: tool({
description:
"Fetch live Command Code plan/usage: plan name, monthly credits, 5-hour & weekly windows, billing-period summary. Pass arg=plans for the plan comparison table only.",
args: {
arg: tool.schema
.string()
.optional()
.describe("Optional: 'plans' for the plan table only"),
},
async execute(args) {
if (args.arg === "plans") return plansTable("");
const key = await resolveKey();
return renderUsage(key);
},
}),
},
};
};
export default CommandCodePlugin;