repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
pi/agent/extensions/web/zai.ts
RawFile outline
- ZaiSearchFreshness line 10
- ZaiRecencyFilter line 12
- ZaiSearchObjectResponse line 14
- title line 15
- content line 16
- link line 17
- media line 18
- icon line 19
- refer line 20
- publish_date line 21
- ZaiSearchResponse line 24
- id line 25
- created line 26
- search_result line 27
- code line 28
- message line 29
- error line 30
- ZaiErrorKind line 33
- ZaiApiError line 45
- constructor line 46
- DEFAULT_ZAI_BASE_URL line 58
- ZAI_PROVIDER_NAMES line 59
- ZAI_API_KEY_ENV line 60
- ZAI_NO_FRESHNESS line 61
- ZAI_FRESHNESS line 62
- FRESHNESS_TO_RECENCY line 64
- ERROR_LABEL line 71
- QUOTA_CODES line 84
- RATE_LIMIT_CODES line 85
- PERMISSION_CODES line 86
- resolveDefaultFreshness line 88
- resolveZaiApiKey line 94
- resolveZaiBaseUrl line 109
- isZaiAvailable line 119
- normalizeApiBaseUrl line 123
- classifyZaiError line 135
- describeZaiError line 148
- makeZaiApiError line 153
- parseZaiError line 160
- zaiSearch line 170
/**
* Z.AI Web Search API client.
* Direct HTTP API, not MCP.
* Docs: https://docs.z.ai/api-reference/tools/web-search
*/
import type { ExtensionContext } from "@mariozechner/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;
media?: string;
icon?: string;
refer?: string;
publish_date?: string;
}
interface ZaiSearchResponse {
id?: string;
created?: number;
search_result?: ZaiSearchObjectResponse[];
code?: number | string;
message?: string;
error?: { code?: number | string; message?: string };
}
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_BASE_URL = "https://api.z.ai";
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 resolveZaiBaseUrl(ctx?: ExtensionContext): string {
const envBase = process.env.ZAI_SEARCH_BASE_URL?.trim() || process.env.ZAI_BASE_URL?.trim();
if (envBase) return envBase;
const model = ctx?.modelRegistry.getAll().find((m) =>
ZAI_PROVIDER_NAMES.includes(m.provider as typeof ZAI_PROVIDER_NAMES[number]),
);
return model?.baseUrl ?? DEFAULT_ZAI_BASE_URL;
}
export async function isZaiAvailable(ctx?: ExtensionContext): Promise<boolean> {
return !!(await resolveZaiApiKey(ctx));
}
function normalizeApiBaseUrl(baseUrl: string): string {
const base = baseUrl.trim().replace(/\/+$/, "");
try {
const url = new URL(base);
if (url.pathname === "/api" || url.pathname.startsWith("/api/")) {
return `${url.origin}/api`;
}
return `${url.origin}${url.pathname}/api`.replace(/\/+api$/, "/api");
} catch {}
return base.endsWith("/api") ? base : `${base}/api`;
}
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 ZaiSearchResponse;
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)}`);
}
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 count = Math.min(Math.max(Math.trunc(options?.count ?? 10), 1), 50);
const body: Record<string, unknown> = {
search_engine: "search-prime",
search_query: query,
count,
};
const freshness = options?.freshness ?? resolveDefaultFreshness();
if (freshness) {
body.search_recency_filter = FRESHNESS_TO_RECENCY[freshness];
}
const url = `${normalizeApiBaseUrl(resolveZaiBaseUrl(ctx))}/paas/v4/web_search`;
const timeoutSignal = AbortSignal.timeout(options?.timeoutMs ?? 30_000);
const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
const response = await fetch(url, {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json",
"Accept-Language": "en-US,en",
},
body: JSON.stringify(body),
signal: requestSignal,
});
if (!response.ok) {
throw await parseZaiError(response);
}
const data = (await response.json()) as ZaiSearchResponse;
if (data.error || data.code !== undefined) {
throw makeZaiApiError(response.status, data.error?.code ?? data.code, data.error?.message ?? data.message);
}
const results = data.search_result ?? [];
return results.map((r) => ({
title: r.title ?? r.link ?? "Untitled",
url: r.link ?? "",
snippet: r.content ?? r.media ?? "",
date: r.publish_date,
})).filter((r) => r.url);
}