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
33 changes: 31 additions & 2 deletions src/models.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import { xdgCache } from "xdg-basedir";
import { xdgCache, xdgData } from "xdg-basedir";

const FETCH_TIMEOUT_MS = 10_000;
const CACHE_PATH = join(
xdgCache ?? join(homedir(), ".cache"),
"opencode",
"models.json",
);
const AUTH_PATH = join(
xdgData ?? join(homedir(), ".local", "share"),
"opencode",
"auth.json",
);
const MODELS_DEV_URL = "https://models.dev/api.json";
const DEFAULT_HUB_BASE = "https://hub.coreinfra.ai";
const HUB_URL = `${process.env.COREINFRA_HUB_BASE_URL ?? DEFAULT_HUB_BASE}/hub/api/prices`;
Expand Down Expand Up @@ -88,7 +93,7 @@ type HubResponse = {
};
};

export type ConfigModel = {
type ConfigModel = {
id: string;
name: string;
provider: {
Expand Down Expand Up @@ -165,8 +170,32 @@ export async function fetchModelsDevData(): Promise<ModelsDevData> {
}
}

type AuthStore = { [provider: string]: { type?: string; key?: string } };

// The config hook runs before OpenCode consults our auth.loader, so the key
// has to be resolved independently: first from the environment, then from the
// auth store OpenCode writes for `opencode auth login`. Every failure on the
// store path (missing file, bad JSON, no usable entry) means "no key".
async function resolveHubApiKey(): Promise<string | undefined> {
const fromEnv = process.env.COREINFRA_API_KEY?.trim();
if (fromEnv) return fromEnv;

try {
const raw = await readFile(AUTH_PATH, "utf-8");
const store = JSON.parse(raw) as AuthStore;
const entry = store["coreinfra"];
const key = entry?.type === "api" ? entry.key?.trim() : undefined;
if (key) return key;
} catch {
// best-effort: anything wrong here just means no key
}
return undefined;
}

export async function fetchHubModels(): Promise<HubResponse> {
const apiKey = await resolveHubApiKey();
const res = await fetch(HUB_URL, {
headers: apiKey ? { "X-CoreInfra-Api-Key": apiKey } : undefined,
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) {
Expand Down
136 changes: 128 additions & 8 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ vi.mock("node:fs/promises", () => ({
readFile: vi.fn(),
}));

function mockInput(): PluginInput {
function mockInput() {
const log = vi.fn().mockResolvedValue(undefined);
return {
const input = {
client: {
app: { log },
},
Expand All @@ -20,7 +20,8 @@ function mockInput(): PluginInput {
worktree: "/tmp",
serverUrl: new URL("http://localhost:3000"),
$: {} as PluginInput["$"],
};
} as PluginInput;
return { input, log };
}

const MODELS_DEV_DATA = {
Expand Down Expand Up @@ -166,7 +167,8 @@ describe("config hook", () => {
it("populates config with full capabilities from models.dev", async () => {
await setupFetchMocks();

const hooks: Hooks = await plugin(mockInput());
const { input } = mockInput();
const hooks: Hooks = await plugin(input);
const config = { provider: {} } as Parameters<
NonNullable<Hooks["config"]>
>[0];
Expand Down Expand Up @@ -255,7 +257,8 @@ describe("config hook", () => {
it("uses defaults when models.dev has no matching model", async () => {
await setupFetchMocks({ modelsDevData: {} });

const hooks: Hooks = await plugin(mockInput());
const { input } = mockInput();
const hooks: Hooks = await plugin(input);
const config = { provider: {} } as Parameters<
NonNullable<Hooks["config"]>
>[0];
Expand All @@ -275,7 +278,8 @@ describe("config hook", () => {
it("leaves models empty on fetchModels failure", async () => {
await setupFetchMocks({ fetchError: new Error("network down") });

const hooks: Hooks = await plugin(mockInput());
const { input } = mockInput();
const hooks: Hooks = await plugin(input);
const config = { provider: {} } as Parameters<
NonNullable<Hooks["config"]>
>[0];
Expand All @@ -285,12 +289,127 @@ describe("config hook", () => {
expect(config.provider?.coreinfra?.name).toBe("CoreInfra AI Hub");
expect(config.provider?.coreinfra?.models).toBeUndefined();
});

it("logs the failure without retrying when the hub returns 401", async () => {
vi.stubEnv("COREINFRA_API_KEY", "bad-key");
const { readFile } = await import("node:fs/promises");
vi.mocked(readFile).mockResolvedValue(JSON.stringify(MODELS_DEV_DATA));

const hubCalls: Array<{ headers?: Record<string, string> }> = [];
vi.stubGlobal(
"fetch",
vi.fn().mockImplementation(
(
url: string,
init?: { headers?: Record<string, string> },
): Promise<{
ok: boolean;
status?: number;
statusText?: string;
json: () => Promise<object>;
}> => {
if (url.includes("models.dev")) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve(MODELS_DEV_DATA),
});
}
hubCalls.push({ headers: init?.headers });
if (hubCalls.length === 1) {
return Promise.resolve({
ok: false,
status: 401,
statusText: "Unauthorized",
json: () => Promise.resolve({}),
});
}
return Promise.resolve({
ok: true,
json: () => Promise.resolve(hubResponse()),
});
},
),
);

const { input, log } = mockInput();
const hooks: Hooks = await plugin(input);
const config = { provider: {} } as Parameters<
NonNullable<Hooks["config"]>
>[0];

await hooks.config?.(config);

expect(hubCalls).toHaveLength(1);
expect(hubCalls[0]?.headers).toEqual({ "X-CoreInfra-Api-Key": "bad-key" });

expect(config.provider?.coreinfra?.models).toBeUndefined();

expect(log).toHaveBeenCalledWith(
expect.objectContaining({
body: expect.objectContaining({
level: "error",
message: "fetchModels failed",
extra: {
error: "Failed to fetch CoreInfra prices: 401 Unauthorized",
},
}),
}),
);
});

it("does not retry when the hub accepts the key", async () => {
vi.stubEnv("COREINFRA_API_KEY", "good-key");
const { readFile } = await import("node:fs/promises");
vi.mocked(readFile).mockResolvedValue(JSON.stringify(MODELS_DEV_DATA));

const hubCalls: Array<{ headers?: Record<string, string> }> = [];
vi.stubGlobal(
"fetch",
vi
.fn()
.mockImplementation(
(url: string, init?: { headers?: Record<string, string> }) => {
if (url.includes("models.dev")) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve(MODELS_DEV_DATA),
});
}
hubCalls.push({ headers: init?.headers });
return Promise.resolve({
ok: true,
json: () => Promise.resolve(hubResponse()),
});
},
),
);

const { input, log } = mockInput();
const hooks: Hooks = await plugin(input);
const config = { provider: {} } as Parameters<
NonNullable<Hooks["config"]>
>[0];

await hooks.config?.(config);

expect(hubCalls).toHaveLength(1);
expect(hubCalls[0]?.headers).toEqual({
"X-CoreInfra-Api-Key": "good-key",
});
expect(config.provider?.coreinfra?.models?.["gpt-5.4-nano"]).toBeDefined();
expect(log).not.toHaveBeenCalledWith(
expect.objectContaining({
body: expect.objectContaining({ level: "warn" }),
}),
);
});
});

describe("auth hook", () => {
it("returns apiKey from auth loader", async () => {
await setupFetchMocks({ hubData: { providers: {} } });
const hooks: Hooks = await plugin(mockInput());
const { input } = mockInput();
const hooks: Hooks = await plugin(input);
const getAuth = vi.fn().mockResolvedValue({ type: "api", key: "sk-test" });
const providerArg = {} as Parameters<
NonNullable<Hooks["auth"]>["loader"]
Expand All @@ -301,7 +420,8 @@ describe("auth hook", () => {

it("returns empty object when no auth", async () => {
await setupFetchMocks({ hubData: { providers: {} } });
const hooks: Hooks = await plugin(mockInput());
const { input } = mockInput();
const hooks: Hooks = await plugin(input);
const getAuth = vi.fn().mockResolvedValue(null);
const providerArg = {} as Parameters<
NonNullable<Hooks["auth"]>["loader"]
Expand Down
Loading