repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/web/index.ts

Raw
File outline
/**
 * 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 "@sinclair/typebox";
import { DEFAULT_MAX_CHARS, DEFAULT_TIMEOUT_MS, DDG_HTML_URL } 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, type ParseDiagnostics } 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";

// ── 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;
}

// ── Binary format helpers ─────────────────────────────────────────────────

function extensionFromContentType(ct: string, url: string): string {
  const lower = ct.toLowerCase().split(";")[0].trim();
  if (lower.includes("pdf")) return "pdf";
  if (lower.includes("docx") || lower.includes("officedocument.wordprocessingml")) return "docx";
  if (lower.includes("msword")) return "doc";
  if (lower.includes("odt") || lower.includes("opendocument.text")) return "odt";
  if (lower.includes("epub")) return "epub";
  if (lower.includes("rtf") || lower.includes("richtext")) return "rtf";
  if (lower.startsWith("image/")) {
    if (lower.includes("png")) return "png";
    if (lower.includes("gif")) return "gif";
    if (lower.includes("webp")) return "webp";
    if (lower.includes("svg")) return "svg";
    return "bin";
  }
  if (lower.startsWith("video/")) return "mp4";
  if (lower.startsWith("audio/")) return "mp3";
  // Fallback to URL extension
  try {
    const u = new URL(url);
    const lastSeg = u.pathname.split("/").pop() ?? "";
    const dotExt = lastSeg.match(/\.([^.]+)$/)?.[1];
    if (dotExt) return dotExt.toLowerCase();
  } catch {}
  return "bin";
}

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 ext = fromFormat === "docx" ? "docx"
    : fromFormat === "odt" ? "odt"
    : fromFormat === "epub" ? "epub"
    : fromFormat === "rtf" ? "rtf"
    : "docx";
  const dir = await createTempDir("pi-web-");
  const tmpPath = join(dir, `input.${ext}`);
  await writeFile(tmpPath, data);
  const text = await runPandocFile(tmpPath, fromFormat, "plain");
  return { text, tmpPath };
}

interface ImageSummary {
  format: string;
  width: number;
  height: number;
  colorspace: string;
  depth: string;
  fileSize: string;
  type: string;
  raw: string;
}

async function imageMetadata(filePath: string): Promise<ImageSummary> {
  try {
    const raw = await spawnToText("identify", ["-verbose", filePath]);
    const width = parseInt(raw.match(/Geometry:\s*(\d+)x(\d+)/i)?.[1] ?? "0");
    const height = parseInt(raw.match(/Geometry:\s*(\d+)x(\d+)/i)?.[2] ?? "0");
    const format = raw.match(/Format:\s*(\S+)/i)?.[1] ?? "";
    const colorspace = raw.match(/Colorspace:\s*(\S+)/i)?.[1] ?? "";
    const depth = raw.match(/Depth:\s*(\S+)/i)?.[1] ?? "";
    const fileSize = raw.match(/Filesize:\s*(\S+)/i)?.[1] ?? "";
    const type = raw.match(/Type:\s*(\S+)/i)?.[1] ?? "";
    return { format, width, height, colorspace, depth, fileSize, type, raw };
  } catch {
    return { format: "", width: 0, height: 0, colorspace: "", depth: "", fileSize: "", type: "", raw: "Image detected but identify (ImageMagick) not available or failed." };
  }
}

interface MediaSummary {
  duration?: string;
  codec?: string;
  width?: number;
  height?: number;
  formatName?: string;
  bitRate?: string;
  raw: string;
}

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 { raw: "Media detected but ffprobe (ffmpeg) not available or failed." };
  }
}

// ── Content-Type router ───────────────────────────────────────────────────

function classifyContentType(ct: string): {
  kind: "html" | "text" | "json" | "pdf" | "office" | "image" | "media" | "binary";
  officeFormat?: string;
} {
  const lower = ct.toLowerCase().split(";")[0].trim();

  if (lower.includes("text/html") || lower.includes("application/xhtml")) {
    return { kind: "html" };
  }
  if (lower.includes("application/json")) {
    return { kind: "json" };
  }
  if (lower.includes("application/xml") || lower.includes("application/yaml")) {
    return { kind: "text" };
  }
  if (lower.startsWith("text/") || lower.includes("csv") || lower.includes("tsv")) {
    return { kind: "text" };
  }
  if (lower.includes("application/pdf")) {
    return { kind: "pdf" };
  }
  if (lower.includes("officedocument.wordprocessingml") || lower.includes("msword")) {
    return { kind: "office", officeFormat: "docx" };
  }
  if (lower.includes("opendocument.text")) {
    return { kind: "office", officeFormat: "odt" };
  }
  if (lower.includes("application/epub")) {
    return { kind: "office", officeFormat: "epub" };
  }
  if (lower.includes("application/rtf") || lower.includes("text/richtext")) {
    return { kind: "office", officeFormat: "rtf" };
  }
  if (lower.startsWith("image/")) {
    return { kind: "image" };
  }
  if (
    lower.startsWith("video/") ||
    lower.startsWith("audio/") ||
    lower.includes("mpeg") ||
    lower.includes("mp4") ||
    lower.includes("webm") ||
    lower.includes("ogg")
  ) {
    return { kind: "media" };
  }
  return { kind: "binary" };
}

// ── Shared search types ───────────────────────────────────────────────────

interface UnifiedSearchResult {
  title: string;
  url: string;
  snippet: string;
  date?: string;
}

// ── Extension ─────────────────────────────────────────────────────────────

export default function webExtension(pi: ExtensionAPI) {

  // ── Session-scoped spotlight markers ───────────────────────────────────
  // Generated once per session so attackers cannot predict them.
  // All external content (fetch + search) is wrapped before sending to LLM.
  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("⬇ web_fetch "));
      text += theme.fg("accent", args.url);
      return new Text(text, 0, 0);
    },

    renderResult(result, { expanded, isPartial }, theme) {
      if (isPartial) {
        return new Text(theme.fg("warning", "⬇ Fetching..."), 0, 0);
      }

      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;

      // Show error state if isError flag is set OR if kind is "error"
      if (result.isError || details?.kind === "error") {
        const content = result.content[0];
        const msg = (details?.error) || (content?.type === "text" ? content.text : "Fetch failed");
        return new Text(theme.fg("error", `✗ ${msg}`), 0, 0);
      }

      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";

      // ── Formatters ───────────────────────────────────────────────
      const fmtSize = (bytes: number): string =>
        bytes >= 1_000_000
          ? `${(bytes / 1_048_576).toFixed(1)}MB`
          : bytes >= 1_000
            ? `${(bytes / 1_024).toFixed(1)}KB`
            : `${bytes}B`;

      const fmtChars = (n: number): string =>
        n >= 10_000
          ? `${(n / 1_000).toFixed(1)}K chars`
          : `${n} chars`;

      // ── Header ───────────────────────────────────────────────────
      let header = theme.fg("success", "✓ ");
      header += theme.fg("accent", fmtSize(bodySize));
      header += theme.fg("dim", ` ${ct.split(";")[0].trim()}`);

      // Type-specific annotations
      if (details?.imageInfo) {
        header += theme.fg("dim", ` ${details.imageInfo.width}×${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}×${mi.height}`);
        if (mi.codec) parts.push(mi.codec);
        if (parts.length) header += theme.fg("dim", ` (${parts.join(", ")})`);
      }

      // ── "LLM sees" line ──────────────────────────────────────────
      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", "↳ LLM sees:")} ${theme.fg("dim", llmDesc)}`;

      // ── Render content (always visible) ──────────────────────────
      const mdTheme = getMarkdownTheme();
      const box = new Box(1, 0, (t) => theme.bg("toolSuccessBg", t));
      box.addChild(new Text(header, 1, 0));

      // Image — structured metadata panel + inline image
      if (kind === "image" && details?.imageInfo) {
        const ii = details.imageInfo;
        let metaMd = `**${ii.format || "Image"}** ${ii.width}×${ii.height}`;
        if (ii.type) metaMd += ` · ${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;
      }

      // Media — structured metadata panel
      if (kind === "media" && details?.mediaInfo) {
        const mi = details.mediaInfo;
        let metaMd = `**${mi.formatName || "Media"}**`;
        if (mi.codec) metaMd += ` · ${mi.codec}`;
        metaMd += "\n";
        if (mi.duration) metaMd += `\n- Duration: ${mi.duration}`;
        if (mi.width && mi.height) metaMd += `\n- Resolution: ${mi.width}×${mi.height}`;
        if (mi.bitRate) metaMd += `\n- Bitrate: ${mi.bitRate}`;
        box.addChild(new Markdown(metaMd, 1, 1, mdTheme));
        return box;
      }

      // All text-like content — render via Markdown
      if (details?.preview) {
        // Compact: first ~30 lines. Expanded: full content.
        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… ${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 timeout = params.timeout ?? DEFAULT_TIMEOUT_MS;
      const statusKey = "web";

      const setStatus = (msg: string) => {
        ctx?.ui?.setStatus(statusKey, msg);
      };
      const clearStatus = () => {
        ctx?.ui?.setStatus(statusKey, undefined);
      };

      ctx?.ui?.setWorkingMessage(`Fetching ${params.url}`);
      onUpdate?.({
        content: [{ type: "text", text: `Fetching ${params.url}…` }],
      });

      const onProgress = (loaded: number, total: number) => {
        const mb = (loaded / (1024 * 1024)).toFixed(1);
        if (total > 0) {
          const totalMb = (total / (1024 * 1024)).toFixed(1);
          const pct = Math.round((loaded / total) * 100);
          setStatus(`⬇ ${mb}/${totalMb}MB (${pct}%)`);
        } else {
          setStatus(`⬇ ${mb}MB`);
        }
      };

      let body: Buffer;
      let contentType: string;
      try {
        const result = await fetchUrlStream(params.url, onProgress, signal);
        body = result.body;
        contentType = result.contentType;
      } catch (err) {
        clearStatus();
        const errorMsg = `Error fetching ${params.url}: ${(err as Error).message}`;
        return {
          content: [{ type: "text", text: errorMsg }],
          isError: true,
          details: { url: params.url, kind: "error", error: errorMsg },
        };
      }

      const { kind, officeFormat } = classifyContentType(contentType);

      onUpdate?.({
        content: [{ type: "text", text: `Converting ${kind} content…` }],
      });

      let output: string;
      let tmpPath: string | undefined;
      let previewContent: string | undefined;

      // ── Helpers for building output ────────────────────────────────
      const fmtSize = (bytes: number): string =>
        bytes >= 1_000_000
          ? `${(bytes / 1_048_576).toFixed(1)}MB`
          : bytes >= 1_000
            ? `${(bytes / 1_024).toFixed(1)}KB`
            : `${bytes}B`;

      const fmtChars = (n: number): string =>
        n >= 10_000
          ? `${(n / 1_000).toFixed(1)}K chars`
          : `${n} chars`;

      const ctShort = contentType.split(";")[0].trim();
      const bodyLen = body.length;

      // Build a summary header line that the LLM sees
      const headerLine = (conversion: string): string =>
        `[${ctShort} | ${fmtSize(bodyLen)} | → ${conversion}]`;

      if (format === "raw") {
        output = body.toString("utf-8");
      } else if (kind === "binary") {
        const ext = extensionFromContentType(contentType, params.url);
        tmpPath = await saveBinaryToTemp(body, ext);
        clearStatus();
        return {
          content: [{
            type: "text",
            text: `${headerLine("binary, not decoded")}\nBinary saved to: ${tmpPath}`,
          }],
          details: { url: params.url, kind: "binary", contentType, binary: true, tmpPath, bodySize: bodyLen },
        };
      } else if (kind === "image") {
        const ext = extensionFromContentType(contentType, params.url);
        tmpPath = await saveBinaryToTemp(body, ext);
        const meta = await imageMetadata(tmpPath);
        // Compact metadata for LLM
        const parts: string[] = [];
        if (meta.format) parts.push(meta.format);
        if (meta.width && meta.height) parts.push(`${meta.width}×${meta.height}`);
        if (meta.type) parts.push(meta.type);
        if (meta.colorspace) parts.push(meta.colorspace);
        if (meta.depth) parts.push(`${meta.depth} depth`);
        if (meta.fileSize) parts.push(meta.fileSize);
        const imageDesc = parts.length > 0 ? parts.join(", ") : "image";
        const header = headerLine(`image inline (${imageDesc})`);
        clearStatus();
        return {
          content: [
            { type: "text", text: `${header}\n${imageDesc}` },
            { type: "image", data: body.toString("base64"), mimeType: contentType },
          ],
          details: { url: params.url, kind: "image", contentType, chars: imageDesc.length, bodySize: bodyLen, markdown: imageDesc, imageInfo: meta },
        };
      } else if (kind === "media") {
        const ext = extensionFromContentType(contentType, params.url);
        tmpPath = await saveBinaryToTemp(body, ext);
        const meta = await mediaMetadata(tmpPath);
        // Compact metadata for LLM
        const parts: string[] = [];
        if (meta.formatName) parts.push(meta.formatName);
        if (meta.codec) parts.push(meta.codec);
        if (meta.duration) parts.push(meta.duration);
        if (meta.width && meta.height) parts.push(`${meta.width}×${meta.height}`);
        if (meta.bitRate) parts.push(meta.bitRate);
        const mediaDesc = parts.length > 0 ? parts.join(", ") : "media";
        const header = headerLine(`ffprobe JSON (${mediaDesc})`);
        output = `${mediaDesc}`;
        // Store raw JSON as separate field for LLM consumption
        const fullOutput = `${header}\n${mediaDesc}\n\n${meta.raw}`;
        if (fullOutput.length > maxChars) {
          const truncated = fullOutput.slice(0, maxChars) + "\n… (truncated)";
          clearStatus();
          return {
            content: [{ type: "text", text: `${params.url}\n\n${truncated}` }],
            details: { url: params.url, kind: "media", format, chars: fullOutput.length, contentType, bodySize: bodyLen, tmpPath, mediaInfo: meta, markdown: output },
          };
        }
        clearStatus();
        return {
          content: [{ type: "text", text: `${params.url}\n\n${fullOutput}` }],
          details: { url: params.url, kind: "media", format, chars: fullOutput.length, contentType, bodySize: bodyLen, tmpPath, mediaInfo: meta, markdown: output },
        };
      } else if (kind === "pdf") {
        const result = await pdfToText(body);
        tmpPath = result.tmpPath;
        output = `${headerLine(`extracted text via pdftotext, ${fmtChars(result.text.length)}`)}\n\n${result.text}`;
        previewContent = result.text;
      } else if (kind === "office" && officeFormat) {
        const result = await officeDocToText(body, officeFormat);
        tmpPath = result.tmpPath;
        output = `${headerLine(`extracted text via pandoc from ${officeFormat.toUpperCase()}, ${fmtChars(result.text.length)}`)}\n\n${result.text}`;
        previewContent = result.text;
      } else if (kind === "json") {
        const text = body.toString("utf-8");
        let formatted: string;
        try {
          formatted = JSON.stringify(JSON.parse(text), null, 2);
        } catch {
          formatted = text;
        }
        output = `${headerLine(`formatted JSON, ${fmtChars(formatted.length)}`)}\n\n${formatted}`;
        previewContent = formatted;
      } else if (kind === "text") {
        const text = body.toString("utf-8");
        const sub = ctShort.includes("csv") ? "CSV" : ctShort.includes("tsv") ? "TSV" : "plain text";
        output = `${headerLine(`${sub}, ${fmtChars(text.length)}`)}\n\n${text}`;
        previewContent = text;
      } else {
        // HTML — extract main content, run through pandoc
        const hint = await checkToolAvailability("pandoc", TOOL_HINTS.pandoc);
        if (hint) {
          clearStatus();
          return {
            content: [{ type: "text", text: hint }],
            isError: true,
            details: { url: params.url, kind: "error", error: hint },
          };
        }
        const html = body.toString("utf-8");
        const extracted = extractMainContent(html);
        let md: string;
        try {
          md = await runPandoc(extracted, format);
        } catch {
          try {
            md = await runPandoc(extracted, format, false);
          } catch (err2) {
            const errMsg = `Pandoc error: ${(err2 as Error).message}`;
            return {
              content: [{ type: "text", text: errMsg }],
              isError: true,
              details: { url: params.url, kind: "error", error: errMsg },
            };
          }
        }
        const fmtLabel = format === "text" ? "plain text"
          : format === "json" ? "Pandoc AST JSON"
          : format === "html" ? "extracted HTML"
          : "markdown";
        output = `${headerLine(`${fmtLabel} via pandoc, ${fmtChars(md.length)}`)}\n\n${md}`;
        previewContent = md;
      }

      // Safety fallback - should never reach here but just in case
      if (output === undefined) {
        output = `[${contentType} | ${bodyLen}B | → unknown content type]`;
        previewContent = output;
      }

      if (output.length > maxChars) {
        output = output.slice(0, maxChars) + "\n… (truncated)";
      }

      const urlPrefixedOutput = `${params.url}\n\n${output}`;
      clearStatus();

      // Wrap all fetched text content in spotlight markers
      const wrappedOutput = wrapUntrusted(urlPrefixedOutput, spotlightMarkers);

      const details: Record<string, unknown> = {
        url: params.url,
        kind,
        format,
        chars: output.length,
        contentType,
        bodySize: bodyLen,
      };
      if (tmpPath) details.tmpPath = tmpPath;
      if (officeFormat) details.officeFormat = officeFormat;
      if (previewContent) details.preview = previewContent;

      return {
        content: [{ type: "text", text: wrappedOutput }],
        details,
      };
    },
  });

  // ── 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("🔍 web_search "));
      text += theme.fg("accent", `"${args.query}"`);
      return new Text(text, 0, 0);
    },

    renderResult(result, { expanded, isPartial }, theme) {
      if (isPartial) {
        return new Text(theme.fg("warning", "Searching..."), 0, 0);
      }

      if (result.isError || result.details?.error) {
        const errorMsg = (result.details as { error?: string } | undefined)?.error
          || (result.content[0]?.type === "text" ? result.content[0].text : "Search failed");
        return new Text(theme.fg("error", `✗ ${errorMsg}`), 0, 0);
      }

      const details = result.details as { query?: string; results?: UnifiedSearchResult[]; source?: string } | undefined;

      if (expanded) {
        const content = result.content[0];
        if (content?.type === "text") {
          const lines = content.text.split("\n");
          let text = "";
          for (const line of lines) {
            text += `\n${theme.fg("dim", line)}`;
          }
          return new Text(text, 0, 0);
        }
      }

      // Compact view — show top results as bullet list
      const results = details?.results;
      let text = theme.fg("success", "✓");
      if (results && results.length > 0) {
        const top = results.slice(0, 5);
        for (const r of top) {
          text += `\n${theme.fg("dim", "• " + 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}"…` }],
      });

      // Try MiniMax first, fall back to DDG
      let results: UnifiedSearchResult[];
      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) {
          // MiniMax failed — fall back to DDG
          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") {
        const jsonText = JSON.stringify(
          { query: params.query, count: sliced.length, results: sliced, source },
          null,
          2,
        );
        return {
          content: [
            { type: "text", text: wrapUntrusted(jsonText, spotlightMarkers) },
          ],
          details: { query: params.query, results: sliced, source },
        };
      }

      const showing = sliced.length;
      const lines: string[] = [
        `Search: ${params.query}`,
        `Results: ${showing}${results.length > showing ? ` of ${results.length}` : ""} (${source})`,
        "",
      ];

      for (let i = 0; i < showing; 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("");
      }

      const searchText = lines.join("\n");
      return {
        content: [{ type: "text", text: wrapUntrusted(searchText, spotlightMarkers) }],
        details: { query: params.query, results: sliced, source },
      };
    },
  });

  // ── DDG search helper ──────────────────────────────────────────────────

  async function searchDdg(
    query: string,
    signal?: AbortSignal,
    timeout?: number,
    ctx?: ExtensionCommandContext,
  ): Promise<UnifiedSearchResult[]> {
    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 encodedQuery = encodeURIComponent(query);
    const html = await fetchSearchHtml(
      `${DDG_HTML_URL}?q=${encodedQuery}`,
      signal,
      timeout,
    );
    markSearchTime();

    const parsed = parseDdgResults(html);

    if (parsed.diagnostics.captcha) {
      ctx?.ui?.notify("DDG captcha detected — try again later", "warning");
    }

    // Surface parse stats as subtle info
    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 — HTTP/HTTPS URL, local file path (strip @ prefix), or data URL",
      }),
    }),

    renderCall(args, theme) {
      let text = theme.fg("toolTitle", theme.bold("🖼 understand_image "));
      const promptPreview = args.prompt.length > 50
        ? args.prompt.substring(0, 50) + "..."
        : args.prompt;
      text += theme.fg("muted", `"${promptPreview}"`);
      text += " " + theme.fg("dim", args.image_source);
      return new Text(text, 0, 0);
    },

    renderResult(result, { expanded, isPartial }, theme) {
      if (isPartial) {
        return new Text(theme.fg("warning", "Analyzing image..."), 0, 0);
      }

      if (result.isError || result.details?.error) {
        const errorMsg = (result.details as { error?: string } | undefined)?.error
          || (result.content[0]?.type === "text" ? result.content[0].text : "Image analysis failed");
        return new Text(theme.fg("error", `✗ ${errorMsg}`), 0, 0);
      }

      // Build result display
      let text = theme.fg("success", "✓ Image analyzed");

      if (expanded) {
        const content = result.content[0];
        if (content?.type === "text") {
          const lines = content.text.split("\n");
          for (const line of lines) {
            text += `\n${theme.fg("dim", line)}`;
          }
        }
      } else {
        // Collapsed — show brief snippet
        const content = result.content[0];
        if (content?.type === "text" && content.text) {
          const snippet = content.text.substring(0, 100).replace(/\n/g, " ");
          text += `\n${theme.fg("dim", snippet + "...")}`;
        }
        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…` }],
      });

      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 },
        };
      }
    },
  });
}