repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/web/search.ts
RawFile outline
- SearchSource line 10
- SearchProvider line 12
- source line 13
- label line 14
- search line 15
- SearchFailure line 18
- label line 19
- err line 20
- message line 21
- MAX_ERROR_TEXT line 24
- displayError line 26
- WebSearchOptions line 35
- query line 36
- count line 37
- timeout line 38
- signal line 39
- ctx line 40
- WebSearchOutcome line 43
- results line 44
- source line 45
- searchWeb line 48
- buildProviders line 76
- searchMinimax line 121
- searchDdg line 135
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";
interface SearchProvider {
source: SearchSource;
label: "Codex" | "Z.AI" | "MiniMax" | "DDG";
search(): Promise<SearchResult[]>;
}
interface SearchFailure {
label: SearchProvider["label"];
err: unknown;
message: string;
}
const MAX_ERROR_TEXT = 240;
function displayError(err: unknown): string {
const message = (err instanceof Error ? err.message : String(err))
.replace(/\s+/g, " ")
.trim();
if (!message) return "unknown error";
if (message.length <= MAX_ERROR_TEXT) return message;
return `${message.slice(0, MAX_ERROR_TEXT - 1)}…`;
}
export interface WebSearchOptions {
query: string;
count: number;
timeout: number;
signal?: AbortSignal;
ctx?: ExtensionContext;
}
export interface WebSearchOutcome {
results: SearchResult[];
source: SearchSource;
}
export async function searchWeb(
options: WebSearchOptions,
): Promise<WebSearchOutcome> {
const providers = await buildProviders(options);
const failures: SearchFailure[] = [];
for (const provider of providers) {
try {
return { results: await provider.search(), source: provider.source };
} catch (err) {
failures.push({
label: provider.label,
err,
message: displayError(err),
});
}
}
const summary = failures
.map((failure) => `${failure.label}: ${failure.message}`)
.join(" | ");
throw new AggregateError(
failures.map((failure) => failure.err),
`Search unavailable: ${summary}`,
);
}
async function buildProviders(
options: WebSearchOptions,
): Promise<SearchProvider[]> {
const providers: SearchProvider[] = [];
const ctx = options.ctx;
if (ctx && (await isCodexAvailable(ctx))) {
providers.push({
source: "codex",
label: "Codex",
search: () =>
codexSearch(options.query, 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 (ctx && (await isMinimaxAvailable(ctx))) {
providers.push({
source: "minimax",
label: "MiniMax",
search: () => searchMinimax(options.query, 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.error) throw new Error(parsed.error);
return parsed.results.map((r) => ({
title: r.title,
url: r.url,
snippet: r.snippet,
}));
}