repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
pi/agent/extensions/web/index.ts
RawFile outline
- fmtSize line 44
- fmtChars line 52
- tempDirs line 60
- createTempDir line 62
- ContentKind line 70
- Classification line 72
- kind line 73
- officeFormat line 74
- ClassificationRule line 77
- test line 78
- result line 79
- CLASSIFICATION_RULES line 82
- stripCt line 97
- classifyContentType line 101
- EXTENSION_MAP line 107
- extensionFromContentType line 113
- saveBinaryToTemp line 130
- pdfToText line 137
- officeDocToText line 147
- ImageSummary line 162
- format line 163
- width line 164
- height line 165
- colorspace line 166
- depth line 167
- fileSize line 168
- type line 169
- raw line 170
- EMPTY_IMAGE line 173
- imageMetadata line 175
- MediaSummary line 193
- duration line 194
- codec line 195
- width line 196
- height line 197
- formatName line 198
- bitRate line 199
- raw line 200
- EMPTY_MEDIA line 203
- mediaMetadata line 205
- joinParts line 239
- ContentOutput line 244
- output line 245
- tmpPath line 246
- preview line 247
- meta line 248
- earlyReturn line 250
- errorFetchResult line 256
- processBinary line 260
- processImage line 274
- processMedia line 294
- processPdf line 313
- processOffice line 322
- processJson line 331
- processText line 341
- processHtml line 350
- expandedText line 370
- hintBox line 380
- errorMsg line 385
- error line 386
- webExtension line 390
- renderCall line 460
- renderResult line 466
- url line 472
- kind line 473
- format line 474
- chars line 475
- bodySize line 476
- contentType line 477
- tmpPath line 478
- preview line 479
- binary line 480
- officeFormat line 481
- imageInfo line 482
- mediaInfo line 483
- error line 484
- execute line 598
- setStatus line 602
- clearStatus line 603
- onProgress line 608
- headerLine line 635
- renderCall line 737
- renderResult line 743
- query line 752
- results line 752
- source line 752
- execute line 776
- searchDdg line 850
- renderCall line 911
- renderResult line 919
- execute line 944
/**
* Web Extension for pi
*
* Tools:
* web_fetch — fetch URL, route by Content-Type, extract content via pandoc
* web_search — search MiniMax Coding Plan API (primary) with DDG fallback
* understand_image — analyze images using MiniMax VLM API
*
* Uses Node.js native fetch (HTTP/1.1 via undici) which helps avoid
* bot detection compared to HTTP/2 clients like curl.
*
* Content-Type routing:
* text/html → extract main content → pandoc + lua filter → markdown
* text/*, json, csv → return as-is
* application/pdf → pdftotext -layout
* docx, odt, epub → pandoc direct read
* image/* → identify -verbose (metadata)
* video/audio → ffprobe (metadata)
*/
import type { ExtensionAPI, ExtensionCommandContext } from "@mariozechner/pi-coding-agent";
import { getMarkdownTheme, keyHint } from "@mariozechner/pi-coding-agent";
import { Box, Markdown, Text } from "@mariozechner/pi-tui";
import { Type } from "typebox";
import { DEFAULT_MAX_CHARS, DEFAULT_TIMEOUT_MS, DDG_HTML_URL, type SearchResult } from "./constants.js";
import { fetchUrlStream, fetchSearchHtml } from "./fetch.js";
import { runPandoc, runPandocFile } from "./pandoc.js";
import { extractMainContent } from "./extract.js";
import { createMarkers, wrapUntrusted, type SpotlightMarkers } from "./spotlight.js";
import { parseDdgResults, throttleWait, markSearchTime } from "./ddg.js";
import {
minimaxSearch,
minimaxUnderstandImage,
isMinimaxAvailable,
} from "./minimax.js";
import { spawnToText, checkToolAvailability, TOOL_HINTS } from "./spawn.js";
import { mkdtemp, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
// ── Shared formatters ────────────────────────────────────────────────────
function fmtSize(bytes: number): string {
return bytes >= 1_000_000
? `${(bytes / 1_048_576).toFixed(1)}MB`
: bytes >= 1_000
? `${(bytes / 1_024).toFixed(1)}KB`
: `${bytes}B`;
}
function fmtChars(n: number): string {
return n >= 10_000
? `${(n / 1_000).toFixed(1)}K chars`
: `${n} chars`;
}
// ── Temp file lifecycle ───────────────────────────────────────────────────
const tempDirs = new Set<string>();
async function createTempDir(prefix: string): Promise<string> {
const dir = await mkdtemp(join(tmpdir(), prefix));
tempDirs.add(dir);
return dir;
}
// ── Content-Type classification ──────────────────────────────────────────
type ContentKind = "html" | "text" | "json" | "pdf" | "office" | "image" | "media" | "binary";
interface Classification {
kind: ContentKind;
officeFormat?: string;
}
interface ClassificationRule {
test: (ct: string) => boolean;
result: Classification;
}
const CLASSIFICATION_RULES: ClassificationRule[] = [
{ test: (ct) => ct.includes("text/html") || ct.includes("application/xhtml"), result: { kind: "html" } },
{ test: (ct) => ct.includes("application/json"), result: { kind: "json" } },
{ test: (ct) => ct.includes("application/xml") || ct.includes("application/yaml"), result: { kind: "text" } },
{ test: (ct) => ct.startsWith("text/") || ct.includes("csv") || ct.includes("tsv"), result: { kind: "text" } },
{ test: (ct) => ct.includes("application/pdf"), result: { kind: "pdf" } },
{ test: (ct) => ct.includes("officedocument.wordprocessingml") || ct.includes("msword"), result: { kind: "office", officeFormat: "docx" } },
{ test: (ct) => ct.includes("opendocument.text"), result: { kind: "office", officeFormat: "odt" } },
{ test: (ct) => ct.includes("application/epub"), result: { kind: "office", officeFormat: "epub" } },
{ test: (ct) => ct.includes("application/rtf") || ct.includes("text/richtext"), result: { kind: "office", officeFormat: "rtf" } },
{ test: (ct) => ct.startsWith("image/"), result: { kind: "image" } },
{ test: (ct) => ct.startsWith("video/") || ct.startsWith("audio/") || ct.includes("mpeg") || ct.includes("mp4") || ct.includes("webm") || ct.includes("ogg"), result: { kind: "media" } },
];
/** Strip parameters and lowercase a Content-Type header value. */
function stripCt(ct: string): string {
return ct.toLowerCase().split(";")[0].trim();
}
function classifyContentType(ct: string): Classification {
return CLASSIFICATION_RULES.find((r) => r.test(stripCt(ct)))?.result ?? { kind: "binary" };
}
// ── Extension from media type ────────────────────────────────────────────
const EXTENSION_MAP: Record<string, string> = {
pdf: "pdf", docx: "docx", msword: "doc", odt: "odt", epub: "epub", rtf: "rtf",
png: "png", gif: "gif", webp: "webp", jpeg: "jpg", jpg: "jpg", svg: "svg",
mp4: "mp4", webm: "webm", ogg: "ogg", mp3: "mp3", wav: "wav",
};
function extensionFromContentType(ct: string, url: string): string {
const lower = stripCt(ct);
for (const [needle, ext] of Object.entries(EXTENSION_MAP)) {
if (lower.includes(needle)) return ext;
}
if (lower.startsWith("image/")) return "bin";
if (lower.startsWith("video/")) return "mp4";
if (lower.startsWith("audio/")) return "mp3";
try {
const urlExt = new URL(url).pathname.match(/\.([^.]+)$/)?.[1];
if (urlExt) return urlExt.toLowerCase();
} catch {}
return "bin";
}
// ── Binary/temp helpers ──────────────────────────────────────────────────
async function saveBinaryToTemp(data: Buffer, extension: string): Promise<string> {
const dir = await createTempDir("pi-web-");
const tmpPath = join(dir, `download.${extension}`);
await writeFile(tmpPath, data);
return tmpPath;
}
async function pdfToText(data: Buffer): Promise<{ text: string; tmpPath: string }> {
const hint = await checkToolAvailability("pdftotext", TOOL_HINTS.pdftotext);
if (hint) throw new Error(hint);
const dir = await createTempDir("pi-web-");
const tmpPath = join(dir, "input.pdf");
await writeFile(tmpPath, data);
const text = await spawnToText("pdftotext", ["-layout", tmpPath, "-"]);
return { text, tmpPath };
}
async function officeDocToText(
data: Buffer,
fromFormat: string,
): Promise<{ text: string; tmpPath: string }> {
const hint = await checkToolAvailability("pandoc", TOOL_HINTS.pandoc);
if (hint) throw new Error(hint);
const dir = await createTempDir("pi-web-");
const tmpPath = join(dir, `input.${fromFormat}`);
await writeFile(tmpPath, data);
const text = await runPandocFile(tmpPath, fromFormat, "plain");
return { text, tmpPath };
}
// ── Metadata extraction ──────────────────────────────────────────────────
interface ImageSummary {
format: string;
width: number;
height: number;
colorspace: string;
depth: string;
fileSize: string;
type: string;
raw: string;
}
const EMPTY_IMAGE: ImageSummary = { format: "", width: 0, height: 0, colorspace: "", depth: "", fileSize: "", type: "", raw: "Image detected but identify (ImageMagick) not available or failed." };
async function imageMetadata(filePath: string): Promise<ImageSummary> {
try {
const raw = await spawnToText("identify", ["-verbose", filePath]);
return {
format: raw.match(/Format:\s*(\S+)/i)?.[1] ?? "",
width: parseInt(raw.match(/Geometry:\s*(\d+)x(\d+)/i)?.[1] ?? "0"),
height: parseInt(raw.match(/Geometry:\s*(\d+)x(\d+)/i)?.[2] ?? "0"),
colorspace: raw.match(/Colorspace:\s*(\S+)/i)?.[1] ?? "",
depth: raw.match(/Depth:\s*(\S+)/i)?.[1] ?? "",
fileSize: raw.match(/Filesize:\s*(\S+)/i)?.[1] ?? "",
type: raw.match(/Type:\s*(\S+)/i)?.[1] ?? "",
raw,
};
} catch {
return EMPTY_IMAGE;
}
}
interface MediaSummary {
duration?: string;
codec?: string;
width?: number;
height?: number;
formatName?: string;
bitRate?: string;
raw: string;
}
const EMPTY_MEDIA: MediaSummary = { raw: "Media detected but ffprobe (ffmpeg) not available or failed." };
async function mediaMetadata(filePath: string): Promise<MediaSummary> {
try {
const raw = await spawnToText("ffprobe", ["-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", filePath]);
if (!raw) return { raw: "No media metadata available." };
const data = JSON.parse(raw);
const fmt = data.format ?? {};
const stream = data.streams?.[0] ?? {};
let duration: string | undefined;
if (fmt.duration) {
const secs = Math.floor(parseFloat(fmt.duration));
const h = Math.floor(secs / 3600);
const m = Math.floor((secs % 3600) / 60);
const s = secs % 60;
duration = h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}` : `${m}:${String(s).padStart(2, "0")}`;
}
return {
duration,
codec: stream.codec_name ?? fmt.format_name?.split(",")[0],
width: stream.width,
height: stream.height,
formatName: fmt.format_name,
bitRate: fmt.bit_rate ? `${Math.round(parseInt(fmt.bit_rate) / 1000)}kbps` : undefined,
raw,
};
} catch {
return EMPTY_MEDIA;
}
}
// ── Content processors ───────────────────────────────────────────────────
/** Join truthy strings with a separator, falling back to a default. */
function joinParts(parts: (string | false | undefined)[], fallback: string, sep = ", "): string {
const filtered = parts.filter(Boolean) as string[];
return filtered.length > 0 ? filtered.join(sep) : fallback;
}
interface ContentOutput {
output: string;
tmpPath?: string;
preview?: string;
meta?: Record<string, unknown>;
/** If set, signals an early-return with binary/image/media that skips the normal truncation path. */
earlyReturn?: {
content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;
details: Record<string, unknown>;
};
}
function errorFetchResult(url: string, error: string) {
return { content: [{ type: "text", text: error }], isError: true, details: { url, kind: "error", error } };
}
async function processBinary(body: Buffer, contentType: string, url: string, headerLine: (s: string) => string): Promise<ContentOutput> {
const ext = extensionFromContentType(contentType, url);
const tmpPath = await saveBinaryToTemp(body, ext);
const text = `${headerLine("binary, not decoded")}\nBinary saved to: ${tmpPath}`;
return {
output: text,
tmpPath,
earlyReturn: {
content: [{ type: "text", text }],
details: { url, kind: "binary", contentType, binary: true, tmpPath, bodySize: body.length },
},
};
}
async function processImage(body: Buffer, contentType: string, url: string, headerLine: (s: string) => string): Promise<ContentOutput> {
const ext = extensionFromContentType(contentType, url);
const tmpPath = await saveBinaryToTemp(body, ext);
const meta = await imageMetadata(tmpPath);
const desc = joinParts([meta.format, meta.width && meta.height && `${meta.width}\u00D7${meta.height}`, meta.type, meta.colorspace, meta.depth && `${meta.depth} depth`, meta.fileSize], "image");
return {
output: `${headerLine(`image inline (${desc})`)}\n${desc}`,
tmpPath,
preview: desc,
meta,
earlyReturn: {
content: [
{ type: "text", text: `${headerLine(`image inline (${desc})`)}\n${desc}` },
{ type: "image", data: body.toString("base64"), mimeType: contentType },
],
details: { url, kind: "image", contentType, chars: desc.length, bodySize: body.length, markdown: desc, imageInfo: meta },
},
};
}
async function processMedia(body: Buffer, contentType: string, url: string, maxChars: number, headerLine: (s: string) => string): Promise<ContentOutput> {
const ext = extensionFromContentType(contentType, url);
const tmpPath = await saveBinaryToTemp(body, ext);
const meta = await mediaMetadata(tmpPath);
const desc = joinParts([meta.formatName, meta.codec, meta.duration, meta.width && meta.height && `${meta.width}\u00D7${meta.height}`, meta.bitRate], "media");
const fullOutput = `${headerLine(`ffprobe JSON (${desc})`)}\n${desc}\n\n${meta.raw}`;
const output = fullOutput.length > maxChars ? fullOutput.slice(0, maxChars) + "\n\u2026 (truncated)" : fullOutput;
return {
output,
tmpPath,
preview: desc,
meta,
earlyReturn: {
content: [{ type: "text", text: `${url}\n\n${output}` }],
details: { url, kind: "media", format: "text" as const, chars: fullOutput.length, contentType, bodySize: body.length, tmpPath, mediaInfo: meta, markdown: desc },
},
};
}
async function processPdf(body: Buffer, headerLine: (s: string) => string): Promise<ContentOutput> {
const { text, tmpPath } = await pdfToText(body);
return {
output: `${headerLine(`extracted text via pdftotext, ${fmtChars(text.length)}`)}\n\n${text}`,
tmpPath,
preview: text,
};
}
async function processOffice(body: Buffer, officeFormat: string, headerLine: (s: string) => string): Promise<ContentOutput> {
const { text, tmpPath } = await officeDocToText(body, officeFormat);
return {
output: `${headerLine(`extracted text via pandoc from ${officeFormat.toUpperCase()}, ${fmtChars(text.length)}`)}\n\n${text}`,
tmpPath,
preview: text,
};
}
function processJson(body: Buffer, headerLine: (s: string) => string): ContentOutput {
const raw = body.toString("utf-8");
let formatted: string;
try { formatted = JSON.stringify(JSON.parse(raw), null, 2); } catch { formatted = raw; }
return {
output: `${headerLine(`formatted JSON, ${fmtChars(formatted.length)}`)}\n\n${formatted}`,
preview: formatted,
};
}
function processText(body: Buffer, ctShort: string, headerLine: (s: string) => string): ContentOutput {
const text = body.toString("utf-8");
const sub = ctShort.includes("csv") ? "CSV" : ctShort.includes("tsv") ? "TSV" : "plain text";
return {
output: `${headerLine(`${sub}, ${fmtChars(text.length)}`)}\n\n${text}`,
preview: text,
};
}
async function processHtml(body: Buffer, format: string, headerLine: (s: string) => string): Promise<ContentOutput> {
const hint = await checkToolAvailability("pandoc", TOOL_HINTS.pandoc);
if (hint) throw new Error(hint);
const extracted = extractMainContent(body.toString("utf-8"));
let md: string;
try {
md = await runPandoc(extracted, format);
} catch {
md = await runPandoc(extracted, format, false);
}
const fmtLabel = format === "text" ? "plain text" : format === "json" ? "Pandoc AST JSON" : format === "html" ? "extracted HTML" : "markdown";
return {
output: `${headerLine(`${fmtLabel} via pandoc, ${fmtChars(md.length)}`)}\n\n${md}`,
preview: md,
};
}
/** Render expanded tool text: prefix + each line dimmed. Returns null if content is not text. */
function expandedText(result: { content: Array<{ type: string; text?: string }> }, prefix: string, theme: { fg: (style: string, text: string) => string }): string | null {
const content = result.content[0];
if (content?.type !== "text") return null;
let text = prefix;
for (const line of content.text.split("\n")) {
text += `\n${theme.fg("dim", line)}`;
}
return text;
}
function hintBox(theme: { fg: (style: string, text: string) => string }, style: "warning" | "error", msg: string): Text {
return new Text(theme.fg(style, msg), 0, 0);
}
/** Extract error message from a tool result, falling back to content text or a default. */
function errorMsg(result: { isError?: boolean; details?: Record<string, unknown>; content: Array<{ type: string; text?: string }> }, fallback: string): string {
return (result.details as { error?: string } | undefined)?.error
|| (result.content[0]?.type === "text" ? result.content[0].text : fallback);
}
export default function webExtension(pi: ExtensionAPI) {
// ── Session-scoped spotlight markers ───────────────────────────────────
const spotlightMarkers: SpotlightMarkers = createMarkers();
// ── Cleanup temp files on session shutdown ─────────────────────────────
pi.on("session_shutdown", async () => {
for (const dir of tempDirs) {
await rm(dir, { recursive: true, force: true }).catch(() => {});
}
tempDirs.clear();
});
// ── web_fetch ──────────────────────────────────────────────────────────
pi.registerTool({
name: "web_fetch",
label: "web_fetch",
description: `Fetch a URL and convert content to markdown (or other formats).
Routes by Content-Type:
- HTML → pandoc with lua filter (strips nav/sidebar/ads, fixes code languages)
- Text, JSON, CSV → returned as-is
- PDF → pdftotext
- DOCX/ODT/EPUB/RTF → pandoc direct read
- Images → metadata via ImageMagick identify
- Video/Audio → metadata via ffprobe
Parameters:
- url: URL to fetch
- format: Output format (markdown, text, html, json, raw)
- maxChars: Truncate output to this many characters`,
promptSnippet:
"web_fetch(url, format?, maxChars?): fetch URL and convert to readable format",
parameters: Type.Object({
url: Type.String({ description: "URL to fetch" }),
format: Type.Optional(
Type.Union(
[
Type.Literal("markdown"),
Type.Literal("text"),
Type.Literal("html"),
Type.Literal("json"),
Type.Literal("raw"),
],
{
description:
"Output format: markdown (default, CommonMark), text (plain), html, json (Pandoc AST), raw (original)",
},
),
),
maxChars: Type.Optional(
Type.Number({
description: "Truncate output to this many characters",
minimum: 100,
maximum: 1_000_000,
}),
),
timeout: Type.Optional(
Type.Number({
description: `Timeout in milliseconds (default: ${DEFAULT_TIMEOUT_MS}ms = ${DEFAULT_TIMEOUT_MS / 1000 / 60}min)`,
minimum: 5000,
maximum: 600_000,
}),
),
}),
renderCall(args, theme) {
let text = theme.fg("toolTitle", theme.bold("\u2B07 web_fetch "));
text += theme.fg("accent", args.url);
return new Text(text, 0, 0);
},
renderResult(result, { expanded, isPartial }, theme) {
if (isPartial) {
return hintBox(theme, "warning", "\u2B07 Fetching...");
}
const details = result.details as {
url?: string;
kind?: string;
format?: string;
chars?: number;
bodySize?: number;
contentType?: string;
tmpPath?: string;
preview?: string;
binary?: boolean;
officeFormat?: string;
imageInfo?: ImageSummary;
mediaInfo?: MediaSummary;
error?: string;
} | undefined;
if (result.isError || details?.kind === "error") {
const content = result.content[0];
const msg = (details?.error) || (content?.type === "text" ? content.text : "Fetch failed");
return hintBox(theme, "error", `\u2717 ${msg}`);
}
const kind = details?.kind ?? "text";
const ct = details?.contentType ?? "unknown";
const bodySize = details?.bodySize ?? 0;
const chars = details?.chars ?? 0;
const isRaw = details?.format === "raw";
let header = theme.fg("success", "\u2713 ");
header += theme.fg("accent", fmtSize(bodySize));
header += theme.fg("dim", ` ${stripCt(ct)}`);
if (details?.imageInfo) {
header += theme.fg("dim", ` ${details.imageInfo.width}\u00D7${details.imageInfo.height}`);
}
if (details?.mediaInfo) {
const mi = details.mediaInfo;
const parts: string[] = [];
if (mi.duration) parts.push(mi.duration);
if (mi.width && mi.height) parts.push(`${mi.width}\u00D7${mi.height}`);
if (mi.codec) parts.push(mi.codec);
if (parts.length) header += theme.fg("dim", ` (${parts.join(", ")})`);
}
let llmDesc: string;
if (isRaw) {
llmDesc = `${fmtChars(chars)} of raw content (no conversion)`;
} else {
switch (kind) {
case "html": {
const fmt = details?.format;
const typeLabel = fmt === "text" ? "plain text" : fmt === "json" ? "Pandoc AST JSON" : fmt === "html" ? "extracted HTML" : "markdown";
llmDesc = `${fmtChars(chars)} of ${typeLabel} (extracted via pandoc)`;
break;
}
case "text": {
const sub = ct.includes("csv") ? "CSV text" : ct.includes("tsv") ? "TSV text" : "plain text";
llmDesc = `${fmtChars(chars)} of ${sub}`;
break;
}
case "json":
llmDesc = `${fmtChars(chars)} of formatted JSON`;
break;
case "pdf":
llmDesc = `${fmtChars(chars)} of extracted text (pdftotext)`;
break;
case "office":
llmDesc = `${fmtChars(chars)} of extracted text (pandoc from ${(details?.officeFormat ?? "document").toUpperCase()})`;
break;
case "image":
llmDesc = `image inline (${details?.imageInfo?.format ?? ct.split("/")[1] ?? "?"}) + ${fmtChars(chars)} metadata text`;
break;
case "media": {
const dur = details?.mediaInfo?.duration;
llmDesc = `${fmtChars(chars)} of ffprobe JSON metadata${dur ? ` (${dur})` : ""}`;
break;
}
case "binary":
llmDesc = "file path + content-type only (binary, not decoded)";
break;
default:
llmDesc = `${fmtChars(chars)} of text`;
}
}
header += `\n ${theme.fg("muted", "\u21B3 LLM sees:")} ${theme.fg("dim", llmDesc)}`;
const mdTheme = getMarkdownTheme();
const box = new Box(1, 0, (t) => theme.bg("toolSuccessBg", t));
box.addChild(new Text(header, 1, 0));
if (kind === "image" && details?.imageInfo) {
const ii = details.imageInfo;
let metaMd = `**${ii.format || "Image"}** ${ii.width}\u00D7${ii.height}`;
if (ii.type) metaMd += ` \u00B7 ${ii.type}`;
metaMd += "\n";
if (ii.colorspace) metaMd += `\n- Color: ${ii.colorspace}`;
if (ii.depth) metaMd += `\n- Depth: ${ii.depth}`;
if (ii.fileSize) metaMd += `\n- File size: ${ii.fileSize}`;
box.addChild(new Markdown(metaMd, 1, 1, mdTheme));
return box;
}
if (kind === "media" && details?.mediaInfo) {
const mi = details.mediaInfo;
let metaMd = `**${mi.formatName || "Media"}**`;
if (mi.codec) metaMd += ` \u00B7 ${mi.codec}`;
metaMd += "\n";
if (mi.duration) metaMd += `\n- Duration: ${mi.duration}`;
if (mi.width && mi.height) metaMd += `\n- Resolution: ${mi.width}\u00D7${mi.height}`;
if (mi.bitRate) metaMd += `\n- Bitrate: ${mi.bitRate}`;
box.addChild(new Markdown(metaMd, 1, 1, mdTheme));
return box;
}
if (details?.preview) {
const lines = details.preview.split("\n");
const maxLines = expanded ? lines.length : 30;
const shown = lines.slice(0, maxLines).join("\n");
const truncated = lines.length > maxLines;
box.addChild(new Markdown(shown + (truncated ? `\n\n\u2026 ${lines.length - maxLines} more lines` : ""), 1, 1, mdTheme));
return box;
}
return box;
},
async execute(_toolCallId, params, signal, onUpdate, ctx) {
const format = params.format ?? "markdown";
const maxChars = params.maxChars ?? DEFAULT_MAX_CHARS;
const setStatus = (msg: string) => ctx?.ui?.setStatus("web", msg);
const clearStatus = () => ctx?.ui?.setStatus("web", undefined);
ctx?.ui?.setWorkingMessage(`Fetching ${params.url}`);
onUpdate?.({ content: [{ type: "text", text: `Fetching ${params.url}\u2026` }] });
const onProgress = (loaded: number, total: number) => {
const mb = (loaded / 1_048_576).toFixed(1);
if (total > 0) {
setStatus(`\u2B07 ${mb}/${(total / 1_048_576).toFixed(1)}MB (${Math.round((loaded / total) * 100)}%)`);
} else {
setStatus(`\u2B07 ${mb}MB`);
}
};
// ── Fetch ────────────────────────────────────────────────────
let body: Buffer;
let contentType: string;
try {
const result = await fetchUrlStream(params.url, onProgress, signal);
body = result.body;
contentType = result.contentType;
} catch (err) {
clearStatus();
return errorFetchResult(params.url, `Error fetching ${params.url}: ${(err as Error).message}`);
}
// ── Route by content type ────────────────────────────────────
const { kind, officeFormat } = classifyContentType(contentType);
onUpdate?.({ content: [{ type: "text", text: `Converting ${kind} content\u2026` }] });
const ctShort = stripCt(contentType);
const bodyLen = body.length;
const headerLine = (conversion: string) => `[${ctShort} | ${fmtSize(bodyLen)} | \u2192 ${conversion}]`;
try {
// Raw passthrough
if (format === "raw") {
const output = body.toString("utf-8");
const truncated = output.length > maxChars ? output.slice(0, maxChars) + "\n\u2026 (truncated)" : output;
clearStatus();
return {
content: [{ type: "text", text: wrapUntrusted(`${params.url}\n\n${truncated}`, spotlightMarkers) }],
details: { url: params.url, kind, format, chars: truncated.length, contentType, bodySize: bodyLen },
};
}
// Dispatch to content processor
const processed =
kind === "binary" ? await processBinary(body, contentType, params.url, headerLine) :
kind === "image" ? await processImage(body, contentType, params.url, headerLine) :
kind === "media" ? await processMedia(body, contentType, params.url, maxChars, headerLine) :
kind === "pdf" ? await processPdf(body, headerLine) :
kind === "office" && officeFormat ? await processOffice(body, officeFormat, headerLine) :
kind === "json" ? processJson(body, headerLine) :
kind === "text" ? processText(body, ctShort, headerLine) :
/* html */ await processHtml(body, format, headerLine);
// Early-return path for binary/image/media (already formatted)
if (processed.earlyReturn) {
clearStatus();
return { ...processed.earlyReturn };
}
// Normal path: truncate, wrap, return
let { output } = processed;
if (output.length > maxChars) {
output = output.slice(0, maxChars) + "\n\u2026 (truncated)";
}
clearStatus();
return {
content: [{ type: "text", text: wrapUntrusted(`${params.url}\n\n${output}`, spotlightMarkers) }],
details: {
url: params.url,
kind,
format,
chars: output.length,
contentType,
bodySize: bodyLen,
...(processed.tmpPath && { tmpPath: processed.tmpPath }),
...(officeFormat && { officeFormat }),
...(processed.preview && { preview: processed.preview }),
},
};
} catch (err) {
clearStatus();
return errorFetchResult(params.url, (err as Error).message);
}
},
});
// ── web_search (MiniMax primary, DDG fallback) ─────────────────────────
pi.registerTool({
name: "web_search",
label: "web_search",
description: `Search the web and return structured results.
Uses MiniMax search API when available (requires minimax provider configured in auth.json or models.json).
Falls back to DuckDuckGo HTML when MiniMax is unavailable.
Parameters:
- query: Search query
- count: Number of results (default 5, max 20)
- format: Output format (text or json)
Returns titles, URLs, and snippets.`,
promptSnippet:
"web_search(query, count?, format?): search the web and return results",
parameters: Type.Object({
query: Type.String({ description: "Search query" }),
count: Type.Optional(
Type.Number({
description: "Number of results (default 5, max 20)",
minimum: 1,
maximum: 20,
}),
),
format: Type.Optional(
Type.Union([Type.Literal("text"), Type.Literal("json")], {
description: "Output format: text (default) or json",
}),
),
timeout: Type.Optional(
Type.Number({
description: `Timeout in milliseconds (default: ${DEFAULT_TIMEOUT_MS}ms = ${DEFAULT_TIMEOUT_MS / 1000 / 60}min)`,
minimum: 5000,
maximum: 600_000,
}),
),
}),
renderCall(args, theme) {
let text = theme.fg("toolTitle", theme.bold("\uD83D\uDD0D web_search "));
text += theme.fg("accent", `"${args.query}"`);
return new Text(text, 0, 0);
},
renderResult(result, { expanded, isPartial }, theme) {
if (isPartial) {
return hintBox(theme, "warning", "Searching...");
}
if (result.isError || result.details?.error) {
return hintBox(theme, "error", `\u2717 ${errorMsg(result, "Search failed")}`);
}
const details = result.details as { query?: string; results?: SearchResult[]; source?: string } | undefined;
if (expanded) {
const rendered = expandedText(result, "", theme);
if (rendered !== null) return new Text(rendered, 0, 0);
}
const results = details?.results;
let text = theme.fg("success", "\u2713");
if (results && results.length > 0) {
const top = results.slice(0, 5);
for (const r of top) {
text += `\n${theme.fg("dim", "\u2022 " + r.title)}`;
}
if (results.length > 5) {
text += `\n${theme.fg("muted", `... +${results.length - 5} more`)}`;
}
}
if (details?.source) {
text += ` ${theme.fg("muted", `(${details.source})`)}`;
}
return new Text(text, 0, 0);
},
async execute(_toolCallId, params, signal, onUpdate, ctx) {
const count = Math.min(params.count ?? 5, 20);
const format = params.format ?? "text";
const timeout = params.timeout ?? DEFAULT_TIMEOUT_MS;
ctx?.ui?.setWorkingMessage(`Searching: ${params.query}`);
onUpdate?.({
content: [{ type: "text", text: `Searching for "${params.query}"\u2026` }],
});
let results: SearchResult[];
let source: string;
const useMinimax = ctx ? await isMinimaxAvailable(ctx) : false;
if (useMinimax) {
try {
const response = await minimaxSearch(params.query, ctx!, signal);
results = (response.organic ?? []).map((r) => ({
title: r.title,
url: r.link,
snippet: r.snippet,
date: r.date,
}));
source = "minimax";
} catch (err) {
ctx?.ui?.notify(`MiniMax search failed, falling back to DDG: ${(err as Error).message}`, "warning");
results = await searchDdg(params.query, signal, timeout, ctx);
source = "ddg";
}
} else {
results = await searchDdg(params.query, signal, timeout, ctx);
source = "ddg";
}
if (!results || results.length === 0) {
return {
content: [{ type: "text", text: `No results found for: ${params.query}` }],
details: { query: params.query, results: [], source },
};
}
const sliced = results.slice(0, count);
if (format === "json") {
return {
content: [{ type: "text", text: wrapUntrusted(JSON.stringify({ query: params.query, count: sliced.length, results: sliced, source }, null, 2), spotlightMarkers) }],
details: { query: params.query, results: sliced, source },
};
}
const lines: string[] = [
`Search: ${params.query}`,
`Results: ${sliced.length}${results.length > sliced.length ? ` of ${results.length}` : ""} (${source})`,
"",
];
for (let i = 0; i < sliced.length; i++) {
const r = sliced[i];
lines.push(`[${i + 1}] ${r.title}`);
lines.push(` ${r.url}`);
if (r.snippet) lines.push(` ${r.snippet}`);
if (r.date) lines.push(` Date: ${r.date}`);
lines.push("");
}
return {
content: [{ type: "text", text: wrapUntrusted(lines.join("\n"), spotlightMarkers) }],
details: { query: params.query, results: sliced, source },
};
},
});
// ── DDG search helper ──────────────────────────────────────────────────
async function searchDdg(
query: string,
signal?: AbortSignal,
timeout?: number,
ctx?: ExtensionCommandContext,
): Promise<SearchResult[]> {
const waitMs = throttleWait();
if (waitMs > 0) {
ctx?.ui?.setStatus("web", `\u23F3 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 \u2014 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 }));
}
// ── understand_image ───────────────────────────────────────────────────
pi.registerTool({
name: "understand_image",
label: "understand_image",
description: `Analyze, describe, or extract information from an image using AI vision (MiniMax VLM).
Supports HTTP/HTTPS URLs, local file paths, and base64 data URLs.
Supported formats: JPEG, PNG, WebP (max 20MB).
Parameters:
- prompt: What to analyze or extract from the image
- image_source: URL, local file path, or data URL of the image`,
promptSnippet:
"understand_image(prompt, image_source): analyze an image with AI vision",
parameters: Type.Object({
prompt: Type.String({ description: "The question or analysis request for the image" }),
image_source: Type.String({
description: "Image source \u2014 HTTP/HTTPS URL, local file path (strip @ prefix), or data URL",
}),
}),
renderCall(args, theme) {
let text = theme.fg("toolTitle", theme.bold("\uD83D\uDDBC understand_image "));
const preview = args.prompt.length > 50 ? args.prompt.substring(0, 50) + "..." : args.prompt;
text += theme.fg("muted", `"${preview}"`);
text += " " + theme.fg("dim", args.image_source);
return new Text(text, 0, 0);
},
renderResult(result, { expanded, isPartial }, theme) {
if (isPartial) {
return hintBox(theme, "warning", "Analyzing image...");
}
if (result.isError || result.details?.error) {
return hintBox(theme, "error", `\u2717 ${errorMsg(result, "Image analysis failed")}`);
}
let text = theme.fg("success", "\u2713 Image analyzed");
if (expanded) {
const rendered = expandedText(result, text, theme);
if (rendered !== null) return new Text(rendered, 0, 0);
} else {
const content = result.content[0];
if (content?.type === "text" && content.text) {
text += `\n${theme.fg("dim", content.text.substring(0, 100).replace(/\n/g, " ") + "...")}`;
}
text += ` ${theme.fg("muted", `(${keyHint("expandTools", "to expand")})`)}`;
}
return new Text(text, 0, 0);
},
async execute(_toolCallId, params, signal, onUpdate, ctx) {
const { prompt, image_source } = params;
if (!prompt) return { content: [{ type: "text", text: "Error: prompt is required" }], isError: true, details: { error: "prompt is required" } };
if (!image_source) return { content: [{ type: "text", text: "Error: image_source is required" }], isError: true, details: { error: "image_source is required" } };
if (!ctx) return { content: [{ type: "text", text: "Error: no extension context available" }], isError: true, details: { error: "no extension context available" } };
ctx?.ui?.setWorkingMessage("Analyzing image...");
onUpdate?.({ content: [{ type: "text", text: "Analyzing image\u2026" }] });
try {
const content = await minimaxUnderstandImage(prompt, image_source, ctx, signal);
return { content: [{ type: "text", text: content }], details: { prompt, image_source } };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return { content: [{ type: "text", text: `Image analysis failed: ${errorMessage}` }], isError: true, details: { error: errorMessage } };
}
},
});
}