@herouucn/opencode-commandcode 0.1.0

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.
package/src/convert.ts ADDED
@@ -0,0 +1,242 @@
1
+ import type { LanguageModelV3CallOptions } from "@ai-sdk/provider";
2
+ import type {
3
+ LanguageModelV3FunctionTool,
4
+ LanguageModelV3Message,
5
+ LanguageModelV3TextPart,
6
+ LanguageModelV3ReasoningPart,
7
+ LanguageModelV3ToolCallPart,
8
+ LanguageModelV3ToolResultPart,
9
+ LanguageModelV3ToolResultOutput,
10
+ } from "@ai-sdk/provider";
11
+
12
+ type CCMessage =
13
+ | { role: "user"; content: string | unknown[] }
14
+ | { role: "assistant"; content: CCAssistantContent[] }
15
+ | { role: "tool"; content: CCToolResultContent[] };
16
+
17
+ type CCAssistantContent =
18
+ | { type: "text"; text: string }
19
+ | { type: "reasoning"; text: string }
20
+ | { type: "tool-call"; toolCallId: string; toolName: string; input: unknown };
21
+
22
+ type CCToolResultContent = {
23
+ type: "tool-result";
24
+ toolCallId: string;
25
+ toolName: string;
26
+ output: { type: "text"; value: string } | { type: "error-text"; value: string };
27
+ };
28
+
29
+ type CCTool = {
30
+ type: "function";
31
+ name: string;
32
+ description?: string;
33
+ input_schema: unknown;
34
+ };
35
+
36
+ interface CCRequestEnvelope {
37
+ config: {
38
+ workingDir: string;
39
+ date: string;
40
+ environment: string;
41
+ structure: unknown[];
42
+ isGitRepo: boolean;
43
+ currentBranch: string;
44
+ mainBranch: string;
45
+ gitStatus: string;
46
+ recentCommits: unknown[];
47
+ };
48
+ memory: string;
49
+ taste: string;
50
+ skills: null;
51
+ permissionMode: string;
52
+ params: {
53
+ model: string;
54
+ messages: CCMessage[];
55
+ tools: CCTool[];
56
+ system: string;
57
+ max_tokens: number;
58
+ stream: true;
59
+ temperature?: number;
60
+ top_p?: number;
61
+ top_k?: number;
62
+ };
63
+ }
64
+
65
+ function hasType(p: unknown, type: string): boolean {
66
+ return typeof p === "object" && p !== null && (p as { type?: string }).type === type;
67
+ }
68
+
69
+ function isTextPart(p: unknown): p is LanguageModelV3TextPart {
70
+ return hasType(p, "text");
71
+ }
72
+
73
+ function isReasoningPart(p: unknown): p is LanguageModelV3ReasoningPart {
74
+ return hasType(p, "reasoning");
75
+ }
76
+
77
+ function isToolCallPart(p: unknown): p is LanguageModelV3ToolCallPart {
78
+ return hasType(p, "tool-call");
79
+ }
80
+
81
+ function isToolResultPart(p: unknown): p is LanguageModelV3ToolResultPart {
82
+ return hasType(p, "tool-result");
83
+ }
84
+
85
+ function extractText(content: unknown): string {
86
+ if (typeof content === "string") return content;
87
+ if (Array.isArray(content)) {
88
+ const textParts = content.filter(isTextPart) as LanguageModelV3TextPart[];
89
+ const nonTextParts = content.filter((p) => !isTextPart(p));
90
+ if (nonTextParts.length > 0 && textParts.length === 0) {
91
+ console.warn(
92
+ `Command Code provider: dropped ${nonTextParts.length} non-text part(s) in user message`,
93
+ );
94
+ }
95
+ return textParts.map((p) => p.text).join("\n");
96
+ }
97
+ return "";
98
+ }
99
+
100
+ function convertToolResultOutput(
101
+ output: LanguageModelV3ToolResultOutput,
102
+ ): CCToolResultContent["output"] {
103
+ switch (output.type) {
104
+ case "text":
105
+ return { type: "text", value: output.value };
106
+ case "error-text":
107
+ return { type: "error-text", value: output.value };
108
+ case "json":
109
+ return { type: "text", value: JSON.stringify(output.value) };
110
+ case "execution-denied":
111
+ return { type: "error-text", value: output.reason ?? "Execution denied" };
112
+ case "error-json":
113
+ return { type: "error-text", value: JSON.stringify(output.value) };
114
+ case "content":
115
+ return {
116
+ type: "text",
117
+ value: output.value
118
+ .map((v: Record<string, unknown>) => ("text" in v ? v.text : JSON.stringify(v)))
119
+ .join("\n"),
120
+ };
121
+ default:
122
+ return { type: "text", value: JSON.stringify(output) };
123
+ }
124
+ }
125
+
126
+ function convertMessage(msg: LanguageModelV3Message): CCMessage | null {
127
+ switch (msg.role) {
128
+ case "user": {
129
+ const text = extractText(msg.content);
130
+ return { role: "user", content: text };
131
+ }
132
+ case "assistant": {
133
+ const parts: CCAssistantContent[] = [];
134
+ for (const part of msg.content) {
135
+ if (isTextPart(part)) {
136
+ parts.push({ type: "text", text: part.text });
137
+ } else if (isReasoningPart(part)) {
138
+ parts.push({ type: "reasoning", text: part.text });
139
+ } else if (isToolCallPart(part)) {
140
+ parts.push({
141
+ type: "tool-call",
142
+ toolCallId: part.toolCallId,
143
+ toolName: part.toolName,
144
+ input: part.input,
145
+ });
146
+ }
147
+ }
148
+ return { role: "assistant", content: parts };
149
+ }
150
+ case "tool": {
151
+ const parts: CCToolResultContent[] = [];
152
+ for (const part of msg.content) {
153
+ if (isToolResultPart(part)) {
154
+ parts.push({
155
+ type: "tool-result",
156
+ toolCallId: part.toolCallId,
157
+ toolName: part.toolName,
158
+ output: convertToolResultOutput(part.output),
159
+ });
160
+ }
161
+ }
162
+ return { role: "tool", content: parts };
163
+ }
164
+ default:
165
+ return null;
166
+ }
167
+ }
168
+
169
+ function convertTools(
170
+ tools:
171
+ | Array<
172
+ | LanguageModelV3FunctionTool
173
+ | {
174
+ type: "provider";
175
+ id: `${string}.${string}`;
176
+ name: string;
177
+ args: Record<string, unknown>;
178
+ }
179
+ >
180
+ | undefined,
181
+ ): CCTool[] {
182
+ if (!tools) return [];
183
+ return tools
184
+ .filter((t): t is LanguageModelV3FunctionTool => t.type === "function")
185
+ .map((t) => ({
186
+ type: "function" as const,
187
+ name: t.name,
188
+ description: t.description,
189
+ input_schema: t.inputSchema,
190
+ }));
191
+ }
192
+
193
+ export function buildRequest(
194
+ modelId: string,
195
+ options: LanguageModelV3CallOptions,
196
+ ): CCRequestEnvelope {
197
+ let systemPrompt = "";
198
+ const messages: CCMessage[] = [];
199
+
200
+ for (const msg of options.prompt) {
201
+ if (msg.role === "system") {
202
+ systemPrompt += (systemPrompt ? "\n\n" : "") + msg.content;
203
+ continue;
204
+ }
205
+ const converted = convertMessage(msg);
206
+ if (converted) messages.push(converted);
207
+ }
208
+
209
+ const params: CCRequestEnvelope["params"] = {
210
+ model: modelId,
211
+ messages,
212
+ tools: convertTools(options.tools),
213
+ system: systemPrompt,
214
+ max_tokens: options.maxOutputTokens ?? 16384,
215
+ stream: true,
216
+ };
217
+
218
+ if (options.temperature !== undefined) params.temperature = options.temperature;
219
+ if (options.topP !== undefined) params.top_p = options.topP;
220
+ if (options.topK !== undefined) params.top_k = options.topK;
221
+
222
+ return {
223
+ config: {
224
+ workingDir: process.cwd() ?? "/",
225
+ date: new Date().toISOString().split("T")[0] ?? "",
226
+ environment: `${process.platform}-${process.arch}`,
227
+ // Stub: opencode does not expose project structure context
228
+ structure: [],
229
+ isGitRepo: false,
230
+ currentBranch: "",
231
+ mainBranch: "",
232
+ gitStatus: "",
233
+ recentCommits: [],
234
+ },
235
+ memory: "",
236
+ // Stub: taste/memory/permissionMode are Command Code CLI features not exposed via provider API
237
+ taste: "",
238
+ skills: null,
239
+ permissionMode: "standard",
240
+ params,
241
+ };
242
+ }
@@ -0,0 +1,179 @@
1
+ import type { ModelEntry } from "./catalog.js";
2
+
3
+ export type DocCostRow = {
4
+ name: string;
5
+ id?: string;
6
+ input: number;
7
+ output: number;
8
+ cache_read?: number;
9
+ cache_write?: number;
10
+ };
11
+
12
+ export function parseMoneyCell(cell: string): number | undefined {
13
+ const trimmed = cell.trim();
14
+ if (!trimmed || trimmed === "—" || trimmed === "-") return undefined;
15
+ if (/^free$/i.test(trimmed)) return 0;
16
+ const amounts = [...trimmed.matchAll(/\$([0-9]+(?:\.[0-9]+)?)/g)].map((m) => Number(m[1]));
17
+ if (amounts.length === 0) return undefined;
18
+ return amounts[amounts.length - 1];
19
+ }
20
+
21
+ type CellRow = { cells: string[]; id?: string };
22
+
23
+ function decodeEntities(text: string): string {
24
+ return text
25
+ .replace(/&amp;/g, "&")
26
+ .replace(/&lt;/g, "<")
27
+ .replace(/&gt;/g, ">")
28
+ .replace(/&quot;/g, '"')
29
+ .replace(/&#39;/g, "'")
30
+ .replace(/&nbsp;/g, " ");
31
+ }
32
+
33
+ function stripTags(html: string): string {
34
+ return decodeEntities(html.replace(/<[^>]+>/g, " "))
35
+ .replace(/\s+/g, " ")
36
+ .trim();
37
+ }
38
+
39
+ function visibleCellText(innerHtml: string): string {
40
+ const trunc = innerHtml.match(/<span class="truncate[^"]*"[^>]*>([^<]*)<\/span>/i);
41
+ if (trunc?.[1]) return decodeEntities(trunc[1]).trim();
42
+ return stripTags(innerHtml);
43
+ }
44
+
45
+ function headerName(cell: string): string {
46
+ return cell.replace(/↕/g, "").replace(/\s+/g, " ").trim().toLowerCase();
47
+ }
48
+
49
+ function colIndex(headers: string[], name: string): number {
50
+ return headers.findIndex((h) => h === name || h.startsWith(`${name} `) || h.startsWith(name));
51
+ }
52
+
53
+ function pipeRows(markdown: string): CellRow[] {
54
+ const rows: CellRow[] = [];
55
+ for (const line of markdown.split("\n")) {
56
+ if (!line.includes("|")) continue;
57
+ const cells = line
58
+ .split("|")
59
+ .map((c) => c.trim())
60
+ .filter((c, i, arr) => !(i === 0 && c === "") && !(i === arr.length - 1 && c === ""));
61
+ if (cells.length) rows.push({ cells });
62
+ }
63
+ return rows;
64
+ }
65
+
66
+ function htmlTableRows(html: string): CellRow[] {
67
+ const rows: CellRow[] = [];
68
+ const tables = html.match(/<table[\s\S]*?<\/table>/gi) ?? [];
69
+ for (const table of tables) {
70
+ const trs = table.match(/<tr[\s\S]*?<\/tr>/gi) ?? [];
71
+ for (const tr of trs) {
72
+ const rawCells = [...tr.matchAll(/<t[dh]\b[\s\S]*?<\/t[dh]>/gi)].map((m) => m[0]);
73
+ if (rawCells.length === 0) continue;
74
+ const cells = rawCells.map((raw) => {
75
+ const inner = raw.replace(/^<t[dh]\b[^>]*>/i, "").replace(/<\/t[dh]>$/i, "");
76
+ return visibleCellText(inner);
77
+ });
78
+ const href = tr.match(/href="\/models\/([^"?#]+)"/i)?.[1];
79
+ rows.push({ cells, ...(href ? { id: href } : {}) });
80
+ }
81
+ }
82
+ return rows;
83
+ }
84
+
85
+ function rowsFromGroup(group: CellRow[]): DocCostRow[] {
86
+ if (group.length === 0) return [];
87
+
88
+ let modelI = 0;
89
+ let inputI = 2;
90
+ let outputI = 3;
91
+ let cacheReadI = 4;
92
+ let cacheWriteI = 5;
93
+ let start = 0;
94
+
95
+ const headerIdx = group.findIndex((r) => /^model\b/i.test(headerName(r.cells[0] ?? "")));
96
+ if (headerIdx >= 0) {
97
+ const headers = group[headerIdx]!.cells.map(headerName);
98
+ const foundInput = colIndex(headers, "input");
99
+ const foundOutput = colIndex(headers, "output");
100
+ if (foundInput >= 0 && foundOutput >= 0) {
101
+ const foundModel = colIndex(headers, "model");
102
+ if (foundModel >= 0) modelI = foundModel;
103
+ inputI = foundInput;
104
+ outputI = foundOutput;
105
+ cacheReadI = colIndex(headers, "cache read");
106
+ cacheWriteI = colIndex(headers, "cache write");
107
+ start = headerIdx + 1;
108
+ }
109
+ }
110
+
111
+ const rows: DocCostRow[] = [];
112
+ for (let i = start; i < group.length; i++) {
113
+ const { cells, id } = group[i]!;
114
+ if (cells.length < 2) continue;
115
+ const first = headerName(cells[0] ?? "");
116
+ if (first === "model" || (cells[0] ?? "").startsWith("---")) continue;
117
+ const input = parseMoneyCell(cells[inputI] ?? "");
118
+ const output = parseMoneyCell(cells[outputI] ?? "");
119
+ if (input === undefined || output === undefined) continue;
120
+ const name = (cells[modelI] ?? "").trim();
121
+ if (!name) continue;
122
+ const row: DocCostRow = { name, input, output };
123
+ if (id) row.id = id;
124
+ if (cacheReadI >= 0) {
125
+ const cacheRead = parseMoneyCell(cells[cacheReadI] ?? "");
126
+ if (cacheRead !== undefined) row.cache_read = cacheRead;
127
+ }
128
+ if (cacheWriteI >= 0) {
129
+ const cacheWrite = parseMoneyCell(cells[cacheWriteI] ?? "");
130
+ if (cacheWrite !== undefined) row.cache_write = cacheWrite;
131
+ }
132
+ rows.push(row);
133
+ }
134
+ return rows;
135
+ }
136
+
137
+ export function parseModelsTable(markdown: string): DocCostRow[] {
138
+ return [...rowsFromGroup(pipeRows(markdown)), ...rowsFromGroup(htmlTableRows(markdown))];
139
+ }
140
+
141
+ export function applyDocCosts(
142
+ models: ModelEntry[],
143
+ rows: DocCostRow[],
144
+ cliIds: Set<string> = new Set(),
145
+ filledIds?: Set<string>,
146
+ ): number {
147
+ const byName = new Map(rows.map((r) => [r.name.toLowerCase(), r]));
148
+ const byId = new Map(rows.filter((r) => r.id).map((r) => [r.id!.toLowerCase(), r]));
149
+ let filled = 0;
150
+ for (const model of models) {
151
+ if (cliIds.has(model.id)) continue;
152
+ const row = byId.get(model.id.toLowerCase()) ?? byName.get(model.name.toLowerCase());
153
+ if (!row) continue;
154
+ model.cost = { input: row.input, output: row.output };
155
+ if (row.cache_read !== undefined) model.cost.cache_read = row.cache_read;
156
+ if (row.cache_write !== undefined) model.cost.cache_write = row.cache_write;
157
+ filledIds?.add(model.id);
158
+ filled++;
159
+ }
160
+ return filled;
161
+ }
162
+
163
+ export async function fetchOfficialModelsMarkdown(): Promise<string> {
164
+ const urls = [
165
+ "https://commandcode.ai/models",
166
+ "https://commandcode.ai/docs/resources/pricing-limits",
167
+ ];
168
+ for (const url of urls) {
169
+ try {
170
+ const resp = await fetch(url);
171
+ if (!resp.ok) continue;
172
+ const text = await resp.text();
173
+ if (parseModelsTable(text).length > 0) return text;
174
+ } catch {
175
+ // try next
176
+ }
177
+ }
178
+ return "";
179
+ }
@@ -0,0 +1,173 @@
1
+ import type { ModelEntry } from "./catalog.js";
2
+
3
+ export const MODELS_DEV_URL = "https://models.dev/api.json";
4
+ export const FREE_COST = { input: 0, output: 0 } as const;
5
+ export const TEXT_ONLY_MODALITIES = { input: ["text"], output: ["text"] } as const;
6
+
7
+ export type ModelsDevRow = {
8
+ id: string;
9
+ name: string;
10
+ cost: { input: number; output: number; cache_read?: number; cache_write?: number };
11
+ attachment?: boolean;
12
+ modalities?: { input: string[]; output: string[] };
13
+ };
14
+
15
+ type ModelsDevModel = {
16
+ id?: string;
17
+ name?: string;
18
+ cost?: { input?: number; output?: number; cache_read?: number; cache_write?: number };
19
+ attachment?: boolean;
20
+ modalities?: { input?: string[]; output?: string[] };
21
+ };
22
+
23
+ type ModelsDevProvider = { models?: Record<string, ModelsDevModel> };
24
+
25
+ function lastSegment(id: string): string {
26
+ const i = id.lastIndexOf("/");
27
+ return i >= 0 ? id.slice(i + 1) : id;
28
+ }
29
+
30
+ export function isFreeSku(model: { id: string; name: string }): boolean {
31
+ if (/-free$/i.test(model.id)) return true;
32
+ return /\bfree\b/i.test(`${model.id} ${model.name}`);
33
+ }
34
+
35
+ export function parseModelsDev(json: string): ModelsDevRow[] {
36
+ const data = JSON.parse(json) as Record<string, ModelsDevProvider>;
37
+ const rows: ModelsDevRow[] = [];
38
+ const seen = new Set<string>();
39
+ for (const provider of Object.keys(data).sort()) {
40
+ const models = data[provider]?.models ?? {};
41
+ for (const model of Object.values(models)) {
42
+ if (!model?.id || model.cost?.input === undefined || model.cost?.output === undefined)
43
+ continue;
44
+ const key = model.id.toLowerCase();
45
+ if (seen.has(key)) continue;
46
+ seen.add(key);
47
+ const cost: ModelsDevRow["cost"] = { input: model.cost.input, output: model.cost.output };
48
+ if (model.cost.cache_read !== undefined) cost.cache_read = model.cost.cache_read;
49
+ if (model.cost.cache_write !== undefined) cost.cache_write = model.cost.cache_write;
50
+ const row: ModelsDevRow = { id: model.id, name: model.name ?? model.id, cost };
51
+ if (typeof model.attachment === "boolean") row.attachment = model.attachment;
52
+ const input = model.modalities?.input?.filter((x) => typeof x === "string");
53
+ const output = model.modalities?.output?.filter((x) => typeof x === "string");
54
+ if (input?.length || output?.length) {
55
+ row.modalities = {
56
+ input: input?.length ? input : [...TEXT_ONLY_MODALITIES.input],
57
+ output: output?.length ? output : [...TEXT_ONLY_MODALITIES.output],
58
+ };
59
+ }
60
+ rows.push(row);
61
+ }
62
+ }
63
+ return rows;
64
+ }
65
+
66
+ function indexRows(rows: ModelsDevRow[]) {
67
+ const byId = new Map<string, ModelsDevRow>();
68
+ const bySegment = new Map<string, ModelsDevRow>();
69
+ const byName = new Map<string, ModelsDevRow>();
70
+ for (const row of rows) {
71
+ const idKey = row.id.toLowerCase();
72
+ if (!byId.has(idKey)) byId.set(idKey, row);
73
+ const segment = lastSegment(row.id).toLowerCase();
74
+ if (!bySegment.has(segment)) bySegment.set(segment, row);
75
+ const nameKey = row.name.toLowerCase();
76
+ if (!byName.has(nameKey)) byName.set(nameKey, row);
77
+ }
78
+ return { byId, bySegment, byName };
79
+ }
80
+
81
+ function findRow(model: ModelEntry, index: ReturnType<typeof indexRows>): ModelsDevRow | undefined {
82
+ return (
83
+ index.byId.get(model.id.toLowerCase()) ??
84
+ index.bySegment.get(lastSegment(model.id).toLowerCase()) ??
85
+ index.byName.get(model.name.toLowerCase())
86
+ );
87
+ }
88
+
89
+ export function applyFreeCosts(
90
+ models: ModelEntry[],
91
+ skipIds: Set<string>,
92
+ filledIds?: Set<string>,
93
+ ): number {
94
+ let filled = 0;
95
+ for (const model of models) {
96
+ if (skipIds.has(model.id) || !isFreeSku(model)) continue;
97
+ model.cost = { ...FREE_COST };
98
+ filledIds?.add(model.id);
99
+ filled++;
100
+ }
101
+ return filled;
102
+ }
103
+
104
+ function textOnly(): { input: string[]; output: string[] } {
105
+ return { input: [...TEXT_ONLY_MODALITIES.input], output: [...TEXT_ONLY_MODALITIES.output] };
106
+ }
107
+
108
+ export function applyModelsDevModalities(models: ModelEntry[], rows: ModelsDevRow[]): number {
109
+ const index = indexRows(rows);
110
+ let filled = 0;
111
+ for (const model of models) {
112
+ const row = findRow(model, index);
113
+ const current = model.modalities;
114
+ if (current && model.attachment !== undefined) {
115
+ const extra = row?.modalities?.input?.filter((x) => !current.input.includes(x)) ?? [];
116
+ if (extra.length > 0) {
117
+ model.modalities = {
118
+ input: [...current.input, ...extra],
119
+ output: [...current.output],
120
+ };
121
+ if (model.modalities.input.includes("image")) model.attachment = true;
122
+ filled++;
123
+ }
124
+ continue;
125
+ }
126
+ if (row && (row.modalities || row.attachment !== undefined)) {
127
+ const modalities = row.modalities
128
+ ? { input: [...row.modalities.input], output: [...row.modalities.output] }
129
+ : textOnly();
130
+ model.modalities = modalities;
131
+ model.attachment = row.attachment ?? modalities.input.includes("image");
132
+ filled++;
133
+ } else {
134
+ model.attachment = false;
135
+ model.modalities = textOnly();
136
+ }
137
+ }
138
+ return filled;
139
+ }
140
+
141
+ export function applyModelsDevCosts(
142
+ models: ModelEntry[],
143
+ rows: ModelsDevRow[],
144
+ skipIds: Set<string>,
145
+ filledIds?: Set<string>,
146
+ ): number {
147
+ const index = indexRows(rows);
148
+ let filled = 0;
149
+ for (const model of models) {
150
+ if (skipIds.has(model.id) || isFreeSku(model)) continue;
151
+ const row = findRow(model, index);
152
+ if (!row) continue;
153
+ model.cost = { input: row.cost.input, output: row.cost.output };
154
+ if (row.cost.cache_read !== undefined) model.cost.cache_read = row.cost.cache_read;
155
+ if (row.cost.cache_write !== undefined) model.cost.cache_write = row.cost.cache_write;
156
+ filledIds?.add(model.id);
157
+ filled++;
158
+ }
159
+ return filled;
160
+ }
161
+
162
+ export async function fetchModelsDevJson(): Promise<string> {
163
+ const resp = await fetch(MODELS_DEV_URL, {
164
+ headers: {
165
+ // ponytail: models.dev returns 403 without a browser-like UA; upgrade if they add a real API token
166
+ "User-Agent":
167
+ "Mozilla/5.0 (compatible; opencode-commandcode/0.5; +https://github.com/BrainerVirus/opencode-commandcode)",
168
+ Accept: "application/json",
169
+ },
170
+ });
171
+ if (!resp.ok) throw new Error(`models.dev returned ${resp.status}`);
172
+ return resp.text();
173
+ }