repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/web/zai.test.ts

Raw
File outline
import { afterEach, describe, expect, test } from "bun:test";
import { ZaiApiError, zaiSearch } from "./zai.js";

const originalFetch = globalThis.fetch;
const originalZaiKey = process.env.ZAI_API_KEY;
const originalZaiBase = process.env.ZAI_BASE_URL;
const originalZaiSearchBase = process.env.ZAI_SEARCH_BASE_URL;

afterEach(() => {
  globalThis.fetch = originalFetch;
  if (originalZaiKey === undefined) delete process.env.ZAI_API_KEY;
  else process.env.ZAI_API_KEY = originalZaiKey;
  if (originalZaiBase === undefined) delete process.env.ZAI_BASE_URL;
  else process.env.ZAI_BASE_URL = originalZaiBase;
  if (originalZaiSearchBase === undefined) delete process.env.ZAI_SEARCH_BASE_URL;
  else process.env.ZAI_SEARCH_BASE_URL = originalZaiSearchBase;
  delete process.env.ZAI_SEARCH_FRESHNESS;
});

describe("zaiSearch", () => {
  test("calls direct Web Search API and maps results", async () => {
    process.env.ZAI_API_KEY = "test-key";
    process.env.ZAI_BASE_URL = "https://api.z.ai";

    let requestUrl = "";
    let requestBody: Record<string, unknown> = {};
    globalThis.fetch = (async (input, init) => {
      requestUrl = String(input);
      requestBody = JSON.parse(String(init?.body));
      expect(init?.headers).toMatchObject({ Authorization: "Bearer test-key" });
      return new Response(JSON.stringify({
        id: "search-1",
        created: 123,
        search_result: [{
          title: "Example",
          content: "Summary",
          link: "https://example.com",
          publish_date: "2026-05-09",
        }],
      }), { status: 200, headers: { "Content-Type": "application/json" } });
    }) as typeof fetch;

    const results = await zaiSearch("example", undefined, undefined, { count: 3, freshness: "week" });

    expect(requestUrl).toBe("https://api.z.ai/api/paas/v4/web_search");
    expect(requestBody).toEqual({
      search_engine: "search-prime",
      search_query: "example",
      count: 3,
      search_recency_filter: "oneWeek",
    });
    expect(results).toEqual([{ title: "Example", url: "https://example.com", snippet: "Summary", date: "2026-05-09" }]);
  });

  test("uses ZAI_SEARCH_FRESHNESS default", async () => {
    process.env.ZAI_API_KEY = "test-key";
    process.env.ZAI_SEARCH_FRESHNESS = "month";

    let requestBody: Record<string, unknown> = {};
    globalThis.fetch = (async (_input, init) => {
      requestBody = JSON.parse(String(init?.body));
      return new Response(JSON.stringify({ search_result: [] }), { status: 200 });
    }) as typeof fetch;

    await zaiSearch("example", undefined, undefined, { count: 3 });
    expect(requestBody).toMatchObject({ search_recency_filter: "oneMonth" });
  });

  test("normalizes base URLs that already include /api paths", async () => {
    process.env.ZAI_API_KEY = "test-key";
    process.env.ZAI_BASE_URL = "https://api.z.ai/api/mcp/web_search_prime/mcp";

    let requestUrl = "";
    globalThis.fetch = (async (input) => {
      requestUrl = String(input);
      return new Response(JSON.stringify({ search_result: [] }), { status: 200 });
    }) as typeof fetch;

    await zaiSearch("example", undefined);
    expect(requestUrl).toBe("https://api.z.ai/api/paas/v4/web_search");
  });

  test("ZAI_SEARCH_BASE_URL overrides chat/provider base URL", async () => {
    process.env.ZAI_API_KEY = "test-key";
    process.env.ZAI_BASE_URL = "https://wrong.example.com/api/paas/v4/chat/completions";
    process.env.ZAI_SEARCH_BASE_URL = "https://api.z.ai/api/paas/v4";

    let requestUrl = "";
    globalThis.fetch = (async (input) => {
      requestUrl = String(input);
      return new Response(JSON.stringify({ search_result: [] }), { status: 200 });
    }) as typeof fetch;

    await zaiSearch("example", undefined);
    expect(requestUrl).toBe("https://api.z.ai/api/paas/v4/web_search");
  });

  test("classifies auth errors", async () => {
    process.env.ZAI_API_KEY = "test-key";
    globalThis.fetch = (async () => new Response(
      JSON.stringify({ error: { code: "1002", message: "bad key" } }),
      { status: 401, statusText: "Unauthorized" },
    )) as typeof fetch;

    try {
      await zaiSearch("example", undefined);
      throw new Error("expected failure");
    } catch (err) {
      expect(err).toBeInstanceOf(ZaiApiError);
      expect((err as ZaiApiError).kind).toBe("auth");
      expect((err as ZaiApiError).code).toBe("1002");
      expect((err as Error).message).toBe("Z.AI auth failed (1002): bad key");
    }
  });

  test("classifies quota/package errors", async () => {
    process.env.ZAI_API_KEY = "test-key";
    globalThis.fetch = (async () => new Response(
      JSON.stringify({ error: { code: "1113", message: "Insufficient balance or no resource package. Please recharge." } }),
      { status: 429, statusText: "Too Many Requests" },
    )) as typeof fetch;

    try {
      await zaiSearch("example", undefined);
      throw new Error("expected failure");
    } catch (err) {
      expect(err).toBeInstanceOf(ZaiApiError);
      expect((err as ZaiApiError).kind).toBe("quota");
      expect((err as ZaiApiError).code).toBe("1113");
      expect((err as Error).message).toContain("Z.AI quota/package unavailable (1113)");
    }
  });

  test("classifies endpoint/base URL errors", async () => {
    process.env.ZAI_API_KEY = "test-key";
    globalThis.fetch = (async () => new Response("Not Found", { status: 404, statusText: "Not Found" })) as typeof fetch;

    try {
      await zaiSearch("example", undefined);
      throw new Error("expected failure");
    } catch (err) {
      expect(err).toBeInstanceOf(ZaiApiError);
      expect((err as ZaiApiError).kind).toBe("endpoint");
      expect((err as Error).message).toContain("Z.AI endpoint/base URL not found (HTTP 404)");
    }
  });

  test("classifies policy blocks", async () => {
    process.env.ZAI_API_KEY = "test-key";
    globalThis.fetch = (async () => new Response(
      JSON.stringify({ error: { code: "1301", message: "unsafe or sensitive content" } }),
      { status: 400 },
    )) as typeof fetch;

    try {
      await zaiSearch("example", undefined);
      throw new Error("expected failure");
    } catch (err) {
      expect(err).toBeInstanceOf(ZaiApiError);
      expect((err as ZaiApiError).kind).toBe("policy");
      expect((err as Error).message).toContain("Z.AI blocked sensitive/policy content (1301)");
    }
  });
});