repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/web/search.ts
RawFile outline
- SearchSource line 10
- Notify line 12
- SearchProvider line 14
- source line 15
- label line 16
- search line 17
- WebSearchOptions line 20
- query line 21
- count line 22
- timeout line 23
- signal line 24
- ctx line 25
- notify line 26
- WebSearchOutcome line 29
- results line 30
- source line 31
- searchWeb line 34
- buildProviders line 56
- searchMinimax line 100
- searchDdg line 114
- fallbackNotice line 159
- zaiNotice line 173
- code line 174
- kind line 175
- minimaxNotice line 192
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
import { codexSearch, isCodexAvailable } from "./codex.js";
import type { SearchResult } from "./constants.js";
import { DDG_HTML_URL } from "./constants.js";
import { markSearchTime, parseDdgResults, throttleWait } from "./ddg.js";
import { fetchSearchHtml } from "./fetch.js";
import { isMinimaxAvailable, minimaxSearch } from "./minimax.js";
import { isZaiAvailable, zaiSearch } from "./zai.js";
export type SearchSource = "codex" | "zai" | "minimax" | "ddg";
type Notify = (message: string, level: "warning" | "info") => void;
interface SearchProvider {
source: SearchSource;
label: "Codex" | "Z.AI" | "MiniMax" | "DDG";
search(): Promise<SearchResult[]>;
}
export interface WebSearchOptions {
query: string;
count: number;
timeout: number;
signal?: AbortSignal;
ctx?: ExtensionContext;
notify?: Notify;
}
export interface WebSearchOutcome {
results: SearchResult[];
source: SearchSource;
}
export async function searchWeb(
options: WebSearchOptions,
): Promise<WebSearchOutcome> {
const providers = await buildProviders(options);
for (let i = 0; i < providers.length; i++) {
const provider = providers[i];
try {
return { results: await provider.search(), source: provider.source };
} catch (err) {
const next = providers[i + 1];
if (!next) throw err;
options.notify?.(
fallbackNotice(provider.label, err, next.label),
"warning",
);
}
}
return { results: [], source: "ddg" };
}
async function buildProviders(
options: WebSearchOptions,
): Promise<SearchProvider[]> {
const providers: SearchProvider[] = [];
if (options.ctx && (await isCodexAvailable(options.ctx))) {
providers.push({
source: "codex",
label: "Codex",
search: () =>
codexSearch(options.query, options.ctx!, options.signal, options.count),
});
}
if (await isZaiAvailable(options.ctx)) {
providers.push({
source: "zai",
label: "Z.AI",
search: () =>
zaiSearch(options.query, options.ctx, options.signal, {
count: options.count,
timeoutMs: options.timeout,
}),
});
}
if (options.ctx && (await isMinimaxAvailable(options.ctx))) {
providers.push({
source: "minimax",
label: "MiniMax",
search: () => searchMinimax(options.query, options.ctx!, options.signal),
});
}
providers.push({
source: "ddg",
label: "DDG",
search: () =>
searchDdg(options.query, options.signal, options.timeout, options.ctx),
});
return providers;
}
async function searchMinimax(
query: string,
ctx: ExtensionContext,
signal?: AbortSignal,
): Promise<SearchResult[]> {
const response = await minimaxSearch(query, ctx, signal);
return (response.organic ?? []).map((r) => ({
title: r.title,
url: r.link,
snippet: r.snippet,
date: r.date,
}));
}
async function searchDdg(
query: string,
signal?: AbortSignal,
timeout?: number,
ctx?: ExtensionContext,
): Promise<SearchResult[]> {
const waitMs = throttleWait();
if (waitMs > 0) {
ctx?.ui?.setStatus(
"web",
`⏳ DDG rate limit: ${(waitMs / 1000).toFixed(1)}s`,
);
await new Promise((r) => setTimeout(r, waitMs));
ctx?.ui?.setStatus("web", undefined);
}
const html = await fetchSearchHtml(
`${DDG_HTML_URL}?q=${encodeURIComponent(query)}`,
signal,
timeout,
);
markSearchTime();
const parsed = parseDdgResults(html);
if (parsed.diagnostics.captcha) {
ctx?.ui?.notify("DDG captcha detected — try again later", "warning");
}
const d = parsed.diagnostics;
if (d.rawBlockCount > 0 || d.resultsSkipped > 0) {
ctx?.ui?.notify(
`DDG: ${d.resultsFound} results from ${d.rawBlockCount} blocks` +
(d.resultsSkipped > 0 ? ` (${d.resultsSkipped} deduped)` : ""),
"info",
);
}
if (parsed.error) throw new Error(parsed.error);
return parsed.results.map((r) => ({
title: r.title,
url: r.url,
snippet: r.snippet,
}));
}
function fallbackNotice(
provider: SearchProvider["label"],
err: unknown,
nextProvider: SearchProvider["label"],
): string {
const suffix = `trying ${nextProvider}`;
const msg = err instanceof Error ? err.message : String(err);
if (provider === "Z.AI") return zaiNotice(err, suffix, msg);
if (provider === "MiniMax") return minimaxNotice(msg, suffix);
if (provider === "Codex") return `Codex search failed; ${suffix}: ${msg}`;
return `${provider} search failed; ${suffix}: ${msg}`;
}
function zaiNotice(err: unknown, suffix: string, msg: string): string {
const code = (err as { code?: string } | undefined)?.code;
const kind = (err as { kind?: string } | undefined)?.kind;
const codeText = code ? ` (${code})` : "";
if (kind === "quota")
return `Z.AI quota/package unavailable${codeText}; ${suffix}`;
if (kind === "auth") return `Z.AI auth failed${codeText}; ${suffix}`;
if (kind === "rate_limit")
return `Z.AI rate/concurrency limit${codeText}; ${suffix}`;
if (kind === "policy")
return `Z.AI blocked sensitive/policy content${codeText}; ${suffix}`;
if (kind === "permission")
return `Z.AI API permission missing${codeText}; ${suffix}`;
if (kind === "endpoint") return `Z.AI endpoint/base URL not found; ${suffix}`;
return `Z.AI search failed; ${suffix}: ${msg}`;
}
function minimaxNotice(msg: string, suffix: string): string {
if (/\b1027\b/.test(msg) || /output\s+new_?sensitive/i.test(msg)) {
return `MiniMax blocked search result/snippet as sensitive (1027 output); ${suffix}`;
}
if (/\b1026\b/.test(msg) || /input\s+new_?sensitive/i.test(msg)) {
return `MiniMax blocked search query as sensitive (1026 input); ${suffix}`;
}
return `MiniMax search failed; ${suffix}: ${msg}`;
}