repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/web/zai.ts

Raw
File outline
/**
 * Z.AI Coding Plan Web Search client.
 * Uses the Coding Plan MCP endpoint, not the paid REST Web Search API.
 * Docs: https://docs.z.ai/devpack/mcp/search-mcp-server
 */

import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
import type { SearchResult } from "./constants.js";

export type ZaiSearchFreshness = "day" | "week" | "month" | "year";

type ZaiRecencyFilter = "oneDay" | "oneWeek" | "oneMonth" | "oneYear" | "noLimit";

interface ZaiSearchObjectResponse {
  title?: string;
  content?: string;
  link?: string;
  url?: string;
  media?: string;
  icon?: string;
  refer?: string;
  publish_date?: string;
  date?: string;
}

interface ZaiErrorResponse {
  code?: number | string;
  message?: string;
  error?: { code?: number | string; message?: string };
}

interface JsonRpcResponse<T = unknown> {
  jsonrpc?: string;
  id?: string | number | null;
  result?: T;
  error?: { code?: number | string; message?: string; data?: unknown };
}

interface McpInitializeResult {
  protocolVersion?: string;
  capabilities?: Record<string, unknown>;
  serverInfo?: Record<string, unknown>;
}

interface McpToolCallResult {
  content?: Array<{ type?: string; text?: string }>;
  isError?: boolean;
}

export type ZaiErrorKind =
  | "auth"
  | "quota"
  | "rate_limit"
  | "policy"
  | "permission"
  | "endpoint"
  | "params"
  | "server"
  | "account"
  | "unknown";

export class ZaiApiError extends Error {
  constructor(
    message: string,
    public readonly kind: ZaiErrorKind,
    public readonly code?: string,
    public readonly status?: number,
    public readonly rawMessage?: string,
  ) {
    super(message);
    this.name = "ZaiApiError";
  }
}

const DEFAULT_ZAI_MCP_URL = "https://api.z.ai/api/mcp/web_search_prime/mcp";
const ZAI_PROVIDER_NAMES = ["zai", "z-ai", "z.ai", "bigmodel"] as const;
const ZAI_API_KEY_ENV = ["ZAI_API_KEY", "Z_AI_API_KEY"] as const;
const ZAI_NO_FRESHNESS = new Set(["", "none", "nolimit", "no_limit"]);
const ZAI_FRESHNESS = new Set(["day", "week", "month", "year"]);

const FRESHNESS_TO_RECENCY: Record<ZaiSearchFreshness, ZaiRecencyFilter> = {
  day: "oneDay",
  week: "oneWeek",
  month: "oneMonth",
  year: "oneYear",
};

const ERROR_LABEL: Record<ZaiErrorKind, string> = {
  auth: "auth failed",
  quota: "quota/package unavailable",
  rate_limit: "rate/concurrency limit",
  policy: "blocked sensitive/policy content",
  permission: "API permission missing",
  endpoint: "endpoint/base URL not found",
  params: "request parameter error",
  server: "server error",
  account: "account problem",
  unknown: "API error",
};

const QUOTA_CODES = new Set(["1113", "1304", "1308", "1309", "1310", "1311"]);
const RATE_LIMIT_CODES = new Set(["1302", "1303", "1305", "1312"]);
const PERMISSION_CODES = new Set(["1220", "434"]);

function resolveDefaultFreshness(): ZaiSearchFreshness | undefined {
  const value = process.env.ZAI_SEARCH_FRESHNESS?.trim().toLowerCase() ?? "";
  if (ZAI_NO_FRESHNESS.has(value)) return undefined;
  return ZAI_FRESHNESS.has(value) ? value as ZaiSearchFreshness : undefined;
}

export async function resolveZaiApiKey(ctx?: ExtensionContext): Promise<string | undefined> {
  if (ctx) {
    for (const provider of ZAI_PROVIDER_NAMES) {
      const key = await ctx.modelRegistry.getApiKeyForProvider(provider);
      if (key) return key;
    }
  }

  for (const envName of ZAI_API_KEY_ENV) {
    const value = process.env[envName]?.trim();
    if (value) return value;
  }
  return undefined;
}

export function resolveZaiMcpUrl(): string {
  const envUrl = process.env.ZAI_SEARCH_MCP_URL?.trim() || process.env.ZAI_SEARCH_BASE_URL?.trim();
  if (envUrl) return normalizeMcpUrl(envUrl);
  return DEFAULT_ZAI_MCP_URL;
}

export async function isZaiAvailable(ctx?: ExtensionContext): Promise<boolean> {
  return !!(await resolveZaiApiKey(ctx));
}

function normalizeMcpUrl(input: string): string {
  const value = input.trim().replace(/\/+$/, "");
  try {
    const url = new URL(value);
    if (url.pathname.endsWith("/mcp")) return value;
    return `${url.origin}/api/mcp/web_search_prime/mcp`;
  } catch {}
  return value.endsWith("/mcp") ? value : `${value}/api/mcp/web_search_prime/mcp`;
}

function classifyZaiError(code: string | undefined, status: number | undefined, message: string): ZaiErrorKind {
  if (code && /^100[0-4]$/.test(code)) return "auth";
  if (QUOTA_CODES.has(code ?? "")) return "quota";
  if (RATE_LIMIT_CODES.has(code ?? "") || status === 429) return "rate_limit";
  if (code === "1301" || /sensitive|unsafe|policy/i.test(message)) return "policy";
  if (PERMISSION_CODES.has(code ?? "")) return "permission";
  if (status === 404) return "endpoint";
  if (code && /^121\d$|^1261$/.test(code)) return "params";
  if (code && /^111\d$|^112\d$/.test(code)) return "account";
  if (status !== undefined && status >= 500) return "server";
  return "unknown";
}

function describeZaiError(kind: ZaiErrorKind, code: string | undefined, message: string, status?: number): string {
  const tag = code ? ` (${code})` : status ? ` (HTTP ${status})` : "";
  return `Z.AI ${ERROR_LABEL[kind]}${tag}: ${message}`;
}

function makeZaiApiError(status: number | undefined, code: unknown, message: unknown): ZaiApiError {
  const codeText = code === undefined || code === null ? undefined : String(code);
  const rawMessage = typeof message === "string" && message ? message : "unknown error";
  const kind = classifyZaiError(codeText, status, rawMessage);
  return new ZaiApiError(describeZaiError(kind, codeText, rawMessage, status), kind, codeText, status, rawMessage);
}

async function parseZaiError(response: Response): Promise<ZaiApiError> {
  const text = await response.text().catch(() => "");
  if (!text) return makeZaiApiError(response.status, undefined, response.statusText || "request failed");
  try {
    const data = JSON.parse(text) as ZaiErrorResponse;
    return makeZaiApiError(response.status, data.error?.code ?? data.code, data.error?.message ?? data.message ?? response.statusText);
  } catch {}
  return makeZaiApiError(response.status, undefined, `${response.statusText}: ${text.slice(0, 500)}`);
}

function parseSseOrJson<T>(text: string): JsonRpcResponse<T> {
  const trimmed = text.trim();
  if (!trimmed) return {};

  const dataLines = trimmed
    .split(/\r?\n/)
    .filter((line) => line.startsWith("data:"))
    .map((line) => line.slice(5).trim())
    .filter(Boolean);

  if (dataLines.length > 0) {
    for (const dataLine of dataLines) {
      const parsed = JSON.parse(dataLine) as JsonRpcResponse<T>;
      if (parsed.result !== undefined || parsed.error !== undefined) return parsed;
    }
    return JSON.parse(dataLines[dataLines.length - 1]) as JsonRpcResponse<T>;
  }

  return JSON.parse(trimmed) as JsonRpcResponse<T>;
}

async function postJsonRpc<T>(
  url: string,
  apiKey: string,
  payload: Record<string, unknown>,
  signal: AbortSignal,
  sessionId?: string,
): Promise<{ data: JsonRpcResponse<T>; sessionId?: string }> {
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${apiKey}`,
      "Content-Type": "application/json",
      "Accept": "application/json, text/event-stream",
      ...(sessionId ? { "mcp-session-id": sessionId } : {}),
    },
    body: JSON.stringify(payload),
    signal,
  });

  if (!response.ok) {
    throw await parseZaiError(response);
  }

  const text = await response.text();
  if (!text.trim()) return { data: {}, sessionId: response.headers.get("mcp-session-id") ?? undefined };

  let data: JsonRpcResponse<T>;
  try {
    data = parseSseOrJson<T>(text);
  } catch {
    throw makeZaiApiError(response.status, undefined, `Malformed MCP response: ${text.slice(0, 500)}`);
  }

  if (data.error) {
    throw makeZaiApiError(response.status, data.error.code, data.error.message);
  }

  return { data, sessionId: response.headers.get("mcp-session-id") ?? undefined };
}

async function initializeMcpSession(url: string, apiKey: string, signal: AbortSignal): Promise<string | undefined> {
  const { sessionId } = await postJsonRpc<McpInitializeResult>(url, apiKey, {
    jsonrpc: "2.0",
    id: 1,
    method: "initialize",
    params: {
      protocolVersion: "2025-03-26",
      capabilities: {},
      clientInfo: { name: "pi-web-extension", version: "0.1.0" },
    },
  }, signal);

  await postJsonRpc(url, apiKey, {
    jsonrpc: "2.0",
    method: "notifications/initialized",
    params: {},
  }, signal, sessionId);

  return sessionId;
}

function decodeSearchItems(text: string): ZaiSearchObjectResponse[] {
  let value: unknown = text.trim();

  for (let i = 0; i < 3 && typeof value === "string"; i++) {
    try {
      value = JSON.parse(value);
    } catch {
      break;
    }
  }

  if (Array.isArray(value)) return value as ZaiSearchObjectResponse[];
  if (value && typeof value === "object") {
    const record = value as { search_result?: ZaiSearchObjectResponse[]; results?: ZaiSearchObjectResponse[] };
    if (Array.isArray(record.search_result)) return record.search_result;
    if (Array.isArray(record.results)) return record.results;
  }

  return [];
}

function mcpResultToSearchResults(result: McpToolCallResult): SearchResult[] {
  const text = result.content?.find((item) => item.type === "text" && item.text)?.text
    ?? result.content?.find((item) => item.text)?.text;

  if (result.isError) {
    throw makeZaiApiError(200, undefined, text ?? "MCP tool returned an error");
  }
  if (!text) return [];

  return decodeSearchItems(text).map((r) => ({
    title: r.title ?? r.link ?? r.url ?? "Untitled",
    url: r.link ?? r.url ?? "",
    snippet: r.content ?? r.media ?? "",
    date: r.publish_date ?? r.date,
  })).filter((r) => r.url);
}

export async function zaiSearch(
  query: string,
  ctx: ExtensionContext | undefined,
  signal?: AbortSignal,
  options?: { count?: number; freshness?: ZaiSearchFreshness; timeoutMs?: number },
): Promise<SearchResult[]> {
  const apiKey = await resolveZaiApiKey(ctx);
  if (!apiKey) {
    throw new Error("Z.AI API key not configured. Set ZAI_API_KEY or configure a zai provider.");
  }

  const freshness = options?.freshness ?? resolveDefaultFreshness();
  const toolArgs: Record<string, unknown> = {
    search_query: query,
    content_size: process.env.ZAI_SEARCH_CONTENT_SIZE?.trim() || "medium",
    location: process.env.ZAI_SEARCH_LOCATION?.trim() || "us",
  };
  if (freshness) toolArgs.search_recency_filter = FRESHNESS_TO_RECENCY[freshness];

  const timeoutSignal = AbortSignal.timeout(options?.timeoutMs ?? 30_000);
  const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
  const url = resolveZaiMcpUrl();
  const sessionId = await initializeMcpSession(url, apiKey, requestSignal);

  const { data } = await postJsonRpc<McpToolCallResult>(url, apiKey, {
    jsonrpc: "2.0",
    id: 2,
    method: "tools/call",
    params: {
      name: "web_search_prime",
      arguments: toolArgs,
    },
  }, requestSignal, sessionId);

  const results = mcpResultToSearchResults(data.result ?? {});
  const count = Math.min(Math.max(Math.trunc(options?.count ?? results.length), 1), 50);
  return results.slice(0, count);
}