repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/web/zai.ts
Raw/**
* Z.AI Coding Plan Web Search and Web Reader clients.
* Uses the Coding Plan MCP endpoints, not the paid REST APIs.
* Docs: https://docs.z.ai/devpack/mcp/search-mcp-server
* Docs: https://docs.z.ai/devpack/mcp/reader-mcp-server
*/
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
import type { SearchResult } from "./constants.js";
import { callMcpTool, McpError, type McpToolResult } from "./mcp.js";
import {
type SettingsContext,
type ZaiSearchFreshness,
zaiContentSize,
zaiFreshness,
zaiLocation,
zaiMcpUrl,
} from "./settings.ts";
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 };
}
export class ZaiApiError extends Error {
readonly code?: string | undefined;
readonly status?: number | undefined;
readonly rawMessage: string;
constructor(
message: string,
code?: string,
status?: number,
rawMessage = "unknown error",
) {
super(message);
this.name = "ZaiApiError";
this.code = code;
this.status = status;
this.rawMessage = rawMessage;
}
}
const ZAI_READER_MCP_URL = "https://api.z.ai/api/mcp/web_reader/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 FRESHNESS_TO_RECENCY: Record<ZaiSearchFreshness, ZaiRecencyFilter> = {
day: "oneDay",
week: "oneWeek",
month: "oneMonth",
year: "oneYear",
};
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 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 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 tag = codeText
? ` (${codeText})`
: status !== undefined && status >= 400
? ` (HTTP ${status})`
: "";
return new ZaiApiError(
`Z.AI API error${tag}: ${rawMessage}`,
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)}`,
);
}
// Z.AI tools return JSON encoded up to twice inside the MCP text content.
function decodeNestedJson(text: string): unknown {
let value: unknown = text.trim();
for (let i = 0; i < 3 && typeof value === "string"; i++) {
try {
value = JSON.parse(value);
} catch {
break;
}
}
return value;
}
function decodeSearchItems(text: string): ZaiSearchObjectResponse[] {
const value = decodeNestedJson(text);
if (Array.isArray(value)) return validateZaiItems(value);
if (value && typeof value === "object") {
const record = value as Record<string, unknown>;
if (Array.isArray(record["search_result"]))
return validateZaiItems(record["search_result"]);
if (Array.isArray(record["results"]))
return validateZaiItems(record["results"]);
}
throw new Error("Z.AI search returned unexpected response");
}
function validateZaiItems(value: unknown[]): ZaiSearchObjectResponse[] {
if (
!value.every(
(item) =>
typeof item === "object" && item !== null && !Array.isArray(item),
)
) {
throw new Error("Z.AI search returned malformed results");
}
return value as ZaiSearchObjectResponse[];
}
function mcpResultText(result: McpToolResult, label: string): string {
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) throw new Error(`Z.AI ${label} returned no content`);
return text;
}
function mcpResultToSearchResults(result: McpToolResult): SearchResult[] {
return decodeSearchItems(mcpResultText(result, "search"))
.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);
}
async function requireZaiApiKey(ctx?: ExtensionContext): Promise<string> {
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.",
);
}
return apiKey;
}
async function callZaiTool(options: {
url: string;
apiKey: string;
signal: AbortSignal;
name: string;
arguments: Record<string, unknown>;
}): Promise<McpToolResult> {
return await callMcpTool({
url: options.url,
protocolVersion: "2025-03-26",
headers: { Authorization: `Bearer ${options.apiKey}` },
signal: options.signal,
name: options.name,
arguments: options.arguments,
}).catch(async (error: unknown) => {
if (!(error instanceof McpError)) throw error;
if (error.response) throw await parseZaiError(error.response);
throw makeZaiApiError(error.status, error.code, error.message);
});
}
export async function zaiSearch(
query: string,
ctx: ExtensionContext | undefined,
signal?: AbortSignal,
options?: {
count?: number;
freshness?: ZaiSearchFreshness;
timeoutMs?: number;
},
): Promise<SearchResult[]> {
const apiKey = await requireZaiApiKey(ctx);
// Without a session, project settings stay unread.
const settings: SettingsContext = ctx ?? {
cwd: process.cwd(),
isProjectTrusted: () => false,
};
const freshness = options?.freshness ?? zaiFreshness(settings);
const toolArgs: Record<string, unknown> = {
search_query: query,
content_size: zaiContentSize(settings),
location: zaiLocation(settings),
};
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 result = await callZaiTool({
url: normalizeMcpUrl(zaiMcpUrl(settings)),
apiKey,
signal: requestSignal,
name: "web_search_prime",
arguments: toolArgs,
});
const results = mcpResultToSearchResults(result);
const count = Math.min(
Math.max(Math.trunc(options?.count ?? results.length), 1),
50,
);
return results.slice(0, count);
}
/** Read a public page through Z.AI's reader; the caller owns URL safety and the deadline. */
export async function zaiRead(
url: string,
format: "markdown" | "text",
ctx: ExtensionContext | undefined,
signal: AbortSignal,
): Promise<string> {
const apiKey = await requireZaiApiKey(ctx);
const result = await callZaiTool({
url: ZAI_READER_MCP_URL,
apiKey,
signal,
name: "webReader",
arguments: { url, return_format: format, retain_images: false },
});
const value = decodeNestedJson(mcpResultText(result, "reader"));
const record =
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
const content = record?.["content"];
if (typeof content !== "string")
throw new Error("Z.AI reader returned unexpected response");
return content;
}