Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

8.8 KB
Raw Blame
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import plugin from "../src/index.js";
import { collectCatalog } from "../src/catalog.js";

const MODELS_URL = "https://gw.example.com/v1/models";
const COMBOS_URL = "https://gw.example.com/api/combos";

function silence() {
  const warns: string[] = [];
  const origWarn = console.warn;
  const origLog = console.log;
  console.warn = (...args: unknown[]) => {
    warns.push(String(args[0]));
  };
  console.log = () => {};
  return {
    warns,
    restore() {
      console.warn = origWarn;
      console.log = origLog;
    },
  };
}

function setup(options: Record<string, unknown>, reload?: () => Promise<void>) {
  const added: unknown[] = [];
  const ctx = {
    options,
    provider: {
      transform: (cb: (editor: { add: (input: unknown) => void }) => void) => {
        cb({ add: (input: unknown) => added.push(input) });
        return Promise.resolve({ dispose: async () => {} });
      },
      ...(reload ? { reload } : {}),
    },
    model: {
      transform: () => Promise.resolve({ dispose: async () => {} }),
    },
    integration: {
      transform: () => Promise.resolve({ dispose: async () => {} }),
    },
  };
  return { added, ctx };
}

function stubDraft() {
  const published = new Map<string, Record<string, unknown>>();
  const draft = {
    provider: { update: (_id: string, fn: (p: Record<string, unknown>) => void) => fn({}) },
    model: {
      update: (pid: string, mid: string, fn: (m: Record<string, unknown>) => void) => {
        const entry: Record<string, unknown> = { id: mid, providerID: pid };
        fn(entry);
        published.set(pid + "/" + mid, entry);
      },
    },
  };
  return { draft, published };
}

describe("plugin-v2 managementReadToken wiring (F1)", () => {
  it("combos fetch uses managementReadToken while models use apiKey", async () => {
    const seen = new Map<string, string>();
    const origFetch = globalThis.fetch;
    globalThis.fetch = (async (url: unknown, init?: { headers?: Record<string, string> }) => {
      const href = String(url);
      seen.set(href, String(init?.headers?.Authorization ?? ""));
      if (href.includes("/api/combos")) {
        return { ok: true, status: 200, statusText: "OK", json: async () => ({ combos: [] }) };
      }
      return {
        ok: true,
        status: 200,
        statusText: "OK",
        json: async () => ({ data: [{ id: "m1", capabilities: { tool_calling: true } }] }),
      };
    }) as typeof fetch;
    const guard = silence();
    try {
      const { added, ctx } = setup({
        baseURL: "https://gw.example.com",
        providerId: "omniroute",
        apiKey: "chat-key",
        managementReadToken: "mgmt-key",
      });
      await (plugin as unknown as { setup: (ctx: unknown) => Promise<void> }).setup(ctx);
      const ids = (added as Array<{ models: Array<{ id: string }> }>).flatMap((a) =>
        a.models.map((m) => m.id)
      );
      assert.ok(ids.includes("m1"));
      assert.equal(seen.get(COMBOS_URL), "Bearer mgmt-key");
      assert.equal(seen.get(MODELS_URL), "Bearer chat-key");
    } finally {
      globalThis.fetch = origFetch;
      guard.restore();
    }
  });

  it("combos fetch falls back to apiKey when managementReadToken is absent", async () => {
    const seen = new Map<string, string>();
    const origFetch = globalThis.fetch;
    globalThis.fetch = (async (url: unknown, init?: { headers?: Record<string, string> }) => {
      const href = String(url);
      seen.set(href, String(init?.headers?.Authorization ?? ""));
      if (href.includes("/api/combos")) {
        return { ok: true, status: 200, statusText: "OK", json: async () => ({ combos: [] }) };
      }
      return {
        ok: true,
        status: 200,
        statusText: "OK",
        json: async () => ({ data: [{ id: "m1", capabilities: { tool_calling: true } }] }),
      };
    }) as typeof fetch;
    const guard = silence();
    try {
      const { ctx } = setup({
        baseURL: "https://gw.example.com",
        providerId: "omniroute",
        apiKey: "chat-key",
      });
      await (plugin as unknown as { setup: (ctx: unknown) => Promise<void> }).setup(ctx);
      assert.equal(seen.get(COMBOS_URL), "Bearer chat-key");
    } finally {
      globalThis.fetch = origFetch;
      guard.restore();
    }
  });

  it("collectCatalog routes combosFetcher to managementReadToken, models to apiKey", async () => {
    const calls: Array<[string, string]> = [];
    const collected = await collectCatalog(
      {
        providerId: "omniroute",
        baseURL: "https://gw.example.com",
        apiKey: "chat-key",
        managementReadToken: "mgmt-key",
        timeoutMs: 1000,
        modelCacheTtlMs: 300000,
        usableOnly: false,
      },
      {
        fetcher: async (_baseURL, token) => {
          calls.push(["models", token]);
          return [{ id: "m1", capabilities: { tool_calling: true } }];
        },
        combosFetcher: async (_baseURL, token) => {
          calls.push(["combos", token]);
          return [];
        },
      }
    );
    const res = collected.counts;
    assert.deepEqual(res, { models: 1, combos: 0 });
    assert.deepEqual(calls, [
      ["models", "chat-key"],
      ["combos", "mgmt-key"],
    ]);
  });
});

describe("plugin-v2 fail-closed models (F2)", () => {
  it("empty models fetch on 2nd refresh keeps the last-known catalog", async () => {
    const { mkdtempSync } = await import("node:fs");
    const { tmpdir } = await import("node:os");
    const { join } = await import("node:path");
    const dir = mkdtempSync(join(tmpdir(), "omniroute-f2-"));
    const prevDataDir = process.env.OPENCODE_DATA_DIR;
    process.env.OPENCODE_DATA_DIR = dir;
    let modelsCall = 0;
    const origFetch = globalThis.fetch;
    globalThis.fetch = (async (url: unknown) => {
      const href = String(url);
      if (href.includes("/api/combos")) {
        return { ok: true, status: 200, statusText: "OK", json: async () => ({ combos: [] }) };
      }
      modelsCall += 1;
      if (modelsCall === 1) {
        return {
          ok: true,
          status: 200,
          statusText: "OK",
          json: async () => ({ data: [{ id: "m1", capabilities: { tool_calling: true } }] }),
        };
      }
      return { ok: false, status: 500, statusText: "Error", json: async () => ({}) };
    }) as typeof fetch;
    const guard = silence();
    try {
      const firstAdded: unknown[] = [];
      const firstCtx = {
        options: {
          baseURL: "https://gw.example.com",
          providerId: "f2-keep",
          apiKey: "k-f2",
          modelCacheTtlMs: 1,
        },
        provider: {
          transform: (cb: (editor: { add: (input: unknown) => void }) => void) => {
            cb({ add: (input: unknown) => firstAdded.push(input) });
            return Promise.resolve({ dispose: async () => {} });
          },
          reload: async () => {},
        },
        model: { transform: () => Promise.resolve({ dispose: async () => {} }) },
        integration: { transform: () => Promise.resolve({ dispose: async () => {} }) },
      };
      await (plugin as unknown as { setup: (ctx: unknown) => Promise<void> }).setup(firstCtx);
      const firstIds = (firstAdded as Array<{ models: Array<{ id: string }> }>).flatMap((a) =>
        a.models.map((m) => m.id)
      );
      assert.ok(firstIds.includes("m1"), "first refresh must publish m1");
      const { setTimeout: sleep } = await import("node:timers/promises");
      await sleep(5);
      const secondAdded: unknown[] = [];
      const secondCtx = {
        options: {
          baseURL: "https://gw.example.com",
          providerId: "f2-keep",
          apiKey: "k-f2",
          modelCacheTtlMs: 1,
        },
        provider: {
          transform: (cb: (editor: { add: (input: unknown) => void }) => void) => {
            cb({ add: (input: unknown) => secondAdded.push(input) });
            return Promise.resolve({ dispose: async () => {} });
          },
          reload: async () => {},
        },
        model: { transform: () => Promise.resolve({ dispose: async () => {} }) },
        integration: { transform: () => Promise.resolve({ dispose: async () => {} }) },
      };
      await (plugin as unknown as { setup: (ctx: unknown) => Promise<void> }).setup(secondCtx);
      if (prevDataDir === undefined) delete process.env.OPENCODE_DATA_DIR;
      else process.env.OPENCODE_DATA_DIR = prevDataDir;
      const secondIds = (secondAdded as Array<{ models: Array<{ id: string }> }>).flatMap((a) =>
        a.models.map((m) => m.id)
      );
      assert.ok(secondIds.includes("m1"), "empty models fetch must reuse last-known catalog");
      assert.ok(
        guard.warns.some((w) => w.includes("keeping last-known catalog")),
        `expected keep-last-known warn, got: ${JSON.stringify(guard.warns)}`
      );
    } finally {
      globalThis.fetch = origFetch;
      guard.restore();
    }
  });
});