Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion opencode-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ The model list is fetched live from Command Code's listing API, split by wire, a

Each model is registered with Command Code's published $/1M rates, so opencode's own cost display works for a subscription provider instead of showing $0. Vision support and reasoning-effort variants come from a generated catalog, because the listing API publishes no capabilities.

Credentials resolve in one order everywhere: `CMD_API_KEY`, then the key `/connect` stored in opencode's credential store, then `~/.commandcode/auth.json` from `cmd login`.
Credentials resolve in one order everywhere: `CMD_API_KEY`, then opencode's credential store (the `commandcode`/`command-code` rows, active first, newest first), then opencode's legacy `auth.json`, then `~/.commandcode/auth.json` from `cmd login`. The store ranks first because a re-connect leaves both files on the key it replaced — and if the API still answers 401, the request is retried with the next candidate rather than failing the turn.

## Install

Expand Down
2 changes: 1 addition & 1 deletion opencode-plugin/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@jeffreyjyz/opencode-command-code",
"version": "0.5.22",
"version": "0.5.23",
"description": "Command Code provider + usage dashboard for opencode: two providers (Anthropic wire for Claude, OpenAI wire for everything else) against api.commandcode.ai, live model list, plan gating, /cmd-usage. Requires the cmduse CLI for usage rendering.",
"type": "module",
"main": "dist/index.js",
Expand Down
139 changes: 127 additions & 12 deletions opencode-plugin/src/key.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,140 @@
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";

// Key resolution order:
// Key resolution order, most likely current first:
// 1. CMD_API_KEY env override (multi-account/testing, mirrors cmduse)
// 2. opencode auth store (populated by /connect via our auth hook)
// 3. Command Code CLI's auth.json (user logged in via `cmd login`)
// 2. opencode's credential store — where /connect writes, active row first
// 3. opencode's legacy v1 auth.json
// 4. Command Code CLI's auth.json (user logged in via `cmd login`)
// 5. the host's auth hook, when one is supplied
//
// The store outranks both files because a re-connect leaves them on the key it
// replaced: reading the files alone is what surfaced
// "Invalid 'Authorization' header or token" on an account whose inference was
// fine. `candidateKeys` returns every key it can find so a refused one costs a
// single request, not a broken provider.

export async function resolveKey(
/** Providers opencode may hold the Command Code key under: v2's integration
* id and the v1 provider id. */
const STORE_PROVIDERS = ["commandcode", "command-code"];

type StoredRow = { key: string; provider: string; active: number; updated: number };

/** `$HOME` per call, so a test (or a shell) can point the lookup elsewhere;
* `os.homedir()` alone answers from the passwd entry. */
function home(): string {
return process.env.HOME ?? homedir();
}

/** `$XDG_DATA_HOME/opencode`, else `~/.local/share/opencode`. */
function opencodeHome(): string {
const base = process.env.XDG_DATA_HOME ?? join(home(), ".local", "share");
return join(base, "opencode");
}

/** Rows of opencode's `credential` table, best first. An absent store, a v1
* store without the table, or a runtime without `node:sqlite` all read as
* "no key here" rather than an error: the files below are the fallback. */
async function storeRows(): Promise<StoredRow[]> {
const path = process.env.OPENCODE_DB ?? join(opencodeHome(), "opencode.db");
let db: { prepare(sql: string): { all(): unknown[] }; close(): void } | undefined;
try {
const sqlite = (await import("node:sqlite")) as unknown as {
DatabaseSync: new (
path: string,
options?: { readOnly?: boolean },
) => {
prepare(sql: string): { all(): unknown[] };
close(): void;
};
};
db = new sqlite.DatabaseSync(path, { readOnly: true });
} catch {
return [];
}
try {
const providers = STORE_PROVIDERS.map((p) => `'${p}'`).join(", ");
const rows = db
.prepare(
`SELECT value, integration_id, active, time_updated FROM credential \
WHERE integration_id IN (${providers})`,
)
.all() as unknown[];
const out: StoredRow[] = [];
for (const row of rows) {
const { value, integration_id, active, time_updated } = row as Record<string, unknown>;
if (typeof value !== "string" || typeof integration_id !== "string") continue;
let key: unknown;
try {
key = (JSON.parse(value) as { key?: unknown }).key;
} catch {
continue;
}
if (typeof key !== "string" || key === "") continue;
out.push({
key,
provider: integration_id,
active: typeof active === "number" ? active : 0,
updated: typeof time_updated === "number" ? time_updated : 0,
});
}
const rank = (provider: string) => {
const index = STORE_PROVIDERS.indexOf(provider);
return index === -1 ? STORE_PROVIDERS.length : index;
};
return out.sort(
(a, b) =>
b.active - a.active || rank(a.provider) - rank(b.provider) || b.updated - a.updated,
);
} catch {
return [];
} finally {
try {
db?.close();
} catch {}
}
}

/** A key out of a JSON file: `${provider}.key` for opencode's file, `apiKey`
* for the CLI's. */
async function fileKey(path: string): Promise<string[]> {
try {
const value = JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>;
const keys: string[] = [];
for (const provider of STORE_PROVIDERS) {
const entry = value[provider] as { key?: unknown } | undefined;
if (typeof entry?.key === "string" && entry.key) keys.push(entry.key);
}
if (typeof value.apiKey === "string" && value.apiKey) keys.push(value.apiKey);
return keys;
} catch {
return [];
}
}

/** Every key this machine can offer, best first, no duplicates. */
export async function candidateKeys(
getAuth?: () => Promise<{ key: string } | undefined>,
): Promise<string> {
): Promise<string[]> {
const keys: string[] = [];
const env = process.env.CMD_API_KEY;
if (env) return env;
if (env) keys.push(env);
for (const row of await storeRows()) keys.push(row.key);
keys.push(...(await fileKey(join(opencodeHome(), "auth.json"))));
keys.push(...(await fileKey(join(home(), ".commandcode", "auth.json"))));
try {
const auth = await getAuth?.();
if (auth?.key) return auth.key;
} catch {}
try {
const text = await readFile(`${homedir()}/.commandcode/auth.json`, "utf8");
const v = JSON.parse(text);
if (typeof v.apiKey === "string" && v.apiKey) return v.apiKey;
if (auth?.key) keys.push(auth.key);
} catch {}
return [...new Set(keys)];
}

export async function resolveKey(
getAuth?: () => Promise<{ key: string } | undefined>,
): Promise<string> {
const [first] = await candidateKeys(getAuth);
if (first) return first;
throw new Error(
"No Command Code API key found. Run /connect, choose Command Code, and paste your key (or `cmd login` in a terminal, or set CMD_API_KEY).",
);
Expand Down
46 changes: 42 additions & 4 deletions opencode-plugin/src/provider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ export interface CommandCodeProviderOptions {
headers?: Record<string, string>;
/** Reasoning effort the host wants (`providerOptions.commandcode.reasoning`). */
reasoningEffort?: string;
/** Other keys to try when the API refuses `apiKey` with 401: a re-connect
* leaves a stale key in a host setting, and one refused request beats a
* provider that cannot answer at all. */
keys?: () => Promise<string[]>;
/** Injected for tests. */
fetch?: typeof fetch;
}
Expand Down Expand Up @@ -81,6 +85,41 @@ export function createCommandCode(
): CommandCodeProvider {
const baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
const doFetch = options.fetch ?? fetch;
// The key that last worked. The host may keep handing us a superseded one
// from its own settings, so a success elsewhere wins for the rest of the
// process instead of paying a 401 on every turn.
let workingKey: string | undefined;

/** POST with failover: `apiKey`, the last key that worked, then whatever
* `keys()` can find. Only a 401 moves to the next candidate — a 429/5xx is
* the same rejection for every key. */
async function post(
url: string,
init: RequestInit,
): Promise<{ response: Response; detail: string }> {
const supplied = await options.keys?.().catch(() => []);
const keys = [workingKey, options.apiKey, ...(supplied ?? [])].filter(
(key): key is string => typeof key === "string",
);
const candidates = keys.length > 0 ? [...new Set(keys)] : [""];
let detail = "";
let response: Response | undefined;
for (const key of candidates) {
response = await doFetch(url, {
...init,
headers: {
...(init.headers as Record<string, string>),
Authorization: `Bearer ${key}`,
},
});
if (response.status !== 401) {
if (key) workingKey = key;
return { response, detail: "" };
}
detail = await response.text().catch(() => "");
}
return { response: response as Response, detail };
}

function model(modelId: string): LanguageModelV3 {
const lane = laneOf(modelId);
Expand All @@ -99,21 +138,20 @@ export function createCommandCode(
reasoningEffort: effortFrom(callOptions) ?? options.reasoningEffort,
images: images(modelId),
});
const response = await doFetch(`${baseURL}${endpoint(lane)}`, {
const { response, detail } = await post(`${baseURL}${endpoint(lane)}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${options.apiKey ?? ""}`,
...(options.headers ?? {}),
...(callOptions.headers ?? {}),
},
body: JSON.stringify(body),
signal: callOptions.abortSignal,
});
if (!response.ok || !response.body) {
const detail = await response.text().catch(() => "");
const text = detail || (await response.text().catch(() => ""));
throw new Error(
`command-code ${lane} ${response.status}: ${detail.slice(0, 300)}`,
`command-code ${lane} ${response.status}: ${text.slice(0, 300)}`,
);
}

Expand Down
6 changes: 5 additions & 1 deletion opencode-plugin/src/v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import {
PLUGIN_ID,
TOOL_DESCRIPTION,
} from "./constants/providers";
import { resolveKey } from "./key";
import { candidateKeys, resolveKey } from "./key";
import { type CmdModel, isClaude, loadModels } from "./models";
import { idsDiffer, readModelsCache, writeModelsCache } from "./modelsCache";
import { createCommandCode } from "./provider";
Expand Down Expand Up @@ -236,6 +236,10 @@ export const commandCodeV2: PluginNs.Plugin = {
? options.baseURL
: PROVIDER_BASE,
headers: options.headers as Record<string, string> | undefined,
// A host setting can carry the key a re-connect replaced;
// hand the transport every candidate so a 401 costs one
// request instead of the whole turn.
keys: () => candidateKeys(),
},
images,
);
Expand Down
106 changes: 106 additions & 0 deletions opencode-plugin/test/key.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { afterEach, describe, expect, test } from "bun:test";
import { Database } from "bun:sqlite";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { candidateKeys, resolveKey } from "../src/key";

// A re-connect through /connect writes the live key into opencode's store and
// leaves `~/.commandcode/auth.json` on the one it replaced. Reading the files
// alone is what answered "Invalid 'Authorization' header or token" on an
// account whose inference worked, so the store has to rank first.

const saved = {
home: process.env.HOME,
data: process.env.XDG_DATA_HOME,
db: process.env.OPENCODE_DB,
key: process.env.CMD_API_KEY,
};

afterEach(() => {
const restore = (name: string, value: string | undefined) => {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
};
restore("HOME", saved.home);
restore("XDG_DATA_HOME", saved.data);
restore("OPENCODE_DB", saved.db);
restore("CMD_API_KEY", saved.key);
});

/** A temp home holding an opencode store with `rows`. */
function fixture(rows: Array<[provider: string, key: string, active: number, updated: number]>) {
const home = mkdtempSync(join(tmpdir(), "cmd-key-"));
const opencode = join(home, ".local", "share", "opencode");
mkdirSync(opencode, { recursive: true });
const db = new Database(join(opencode, "opencode.db"));
db.run(
"CREATE TABLE credential (id TEXT PRIMARY KEY, integration_id TEXT, label TEXT NOT NULL, value TEXT NOT NULL, active INTEGER, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL)",
);
for (const [provider, key, active, updated] of rows) {
db.run(
"INSERT INTO credential (id, integration_id, label, value, active, time_created, time_updated) VALUES (?, ?, 'x', ?, ?, ?, ?)",
[
`cred_${provider}_${updated}`,
provider,
JSON.stringify({ type: "api", key }),
active,
updated,
updated,
],
);
}
db.close();
process.env.HOME = home;
delete process.env.XDG_DATA_HOME;
delete process.env.OPENCODE_DB;
delete process.env.CMD_API_KEY;
return { home, opencode };
}

describe("key candidates", () => {
test("the active store row outranks the inactive one and the CLI file", async () => {
const { home } = fixture([
["commandcode", "user_dead", 0, 200],
["commandcode", "user_live", 1, 100],
]);
mkdirSync(join(home, ".commandcode"), { recursive: true });
writeFileSync(
join(home, ".commandcode", "auth.json"),
JSON.stringify({ apiKey: "user_cli" }),
);
const keys = await candidateKeys();
expect(keys).toEqual(["user_live", "user_dead", "user_cli"]);
expect(await resolveKey()).toBe("user_live");
rmSync(home, { recursive: true, force: true });
});

test("CMD_API_KEY wins, and a store without the table falls through", async () => {
const home = mkdtempSync(join(tmpdir(), "cmd-key-empty-"));
const opencode = join(home, ".local", "share", "opencode");
mkdirSync(opencode, { recursive: true });
new Database(join(opencode, "opencode.db")).close();
process.env.HOME = home;
delete process.env.XDG_DATA_HOME;
delete process.env.OPENCODE_DB;
process.env.CMD_API_KEY = "env_key";
expect(await candidateKeys()).toEqual(["env_key"]);
rmSync(home, { recursive: true, force: true });
});

test("opencode's legacy auth.json is read before the CLI's", async () => {
const { home, opencode } = fixture([]);
writeFileSync(
join(opencode, "auth.json"),
JSON.stringify({ "command-code": { type: "api", key: "v1_key" } }),
);
mkdirSync(join(home, ".commandcode"), { recursive: true });
writeFileSync(
join(home, ".commandcode", "auth.json"),
JSON.stringify({ apiKey: "cli_key" }),
);
expect(await candidateKeys()).toEqual(["v1_key", "cli_key"]);
expect(await resolveKey()).toBe("v1_key");
rmSync(home, { recursive: true, force: true });
});
});
Loading
Loading