Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/minimax/src/render.ts

Raw
import { basename } from "node:path";
import { pathToFileURL } from "node:url";
import { stripVTControlCharacters } from "node:util";
import type {
	AgentToolResult,
	Theme,
	ToolRenderResultOptions,
} from "@earendil-works/pi-coding-agent";
import { keyHint } from "@earendil-works/pi-coding-agent";
import {
	Container,
	getCapabilities,
	hyperlink,
	Image,
	Text,
} from "@earendil-works/pi-tui";
import { object } from "./api.ts";
import { isPreview, PREVIEW_KEY, type Preview } from "./preview.ts";
import { quotaLine } from "./quota.ts";

export type Kind = "vision" | "speech" | "video" | "capabilities";
type Hint = typeof keyHint;
interface RenderContext {
	args?: unknown;
	isError?: boolean;
	keyHint?: Hint;
	showImages?: boolean;
}
const TITLES: Record<Kind, string> = {
	vision: "◉ MiniMax vision",
	speech: "♪ MiniMax speech",
	video: "▶ MiniMax H3",
	capabilities: "MiniMax capabilities",
};
const PROGRESS: Record<Kind, string> = {
	vision: "◉ Understanding image…",
	speech: "♪ Synthesizing speech…",
	video: "▶ Contacting MiniMax H3…",
	capabilities: "Inspecting local MiniMax setup…",
};
const MAX_LINES = 400;

/** Untrusted provider/user text: no escape sequences, no control or format characters. */
export function terminal(value: unknown): string {
	return stripVTControlCharacters(String(value ?? ""))
		.replace(/\r\n?/g, "\n")
		.replace(/\t/g, "  ")
		.replace(/(?!\n)[\p{Cc}\p{Cf}]/gu, " ");
}
function display(value: unknown): string {
	return terminal(value).replace(/\s+/g, " ").trim();
}
function clip(value: unknown, max: number): string {
	const text = display(value);
	return text.length > max ? `${text.slice(0, max - 1)}…` : text;
}
/** Never surface signed query strings from remote sources. */
function sourceName(source: unknown): string {
	const raw = String(source ?? "");
	if (/^https?:\/\//i.test(raw))
		try {
			const url = new URL(raw);
			return basename(url.pathname) || url.hostname;
		} catch {
			return "remote image";
		}
	return basename(raw);
}
function usd(value: unknown): string | undefined {
	return typeof value === "number" && Number.isFinite(value)
		? `est $${Number(value.toPrecision(3))}`
		: undefined;
}
function size(bytes: unknown): string | undefined {
	if (typeof bytes !== "number" || !Number.isFinite(bytes)) return undefined;
	if (bytes < 1024) return `${bytes} B`;
	if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
	return `${(bytes / 1048576).toFixed(1)} MB`;
}
/** Link the already-clipped visible label; sanitising after wrapping would strip OSC 8. */
export function fileLink(path: string, label: string): string {
	if (!getCapabilities().hyperlinks) return label;
	try {
		return hyperlink(label, pathToFileURL(path).href);
	} catch {
		return label;
	}
}
function scalar(value: unknown): string {
	return typeof value === "string" ? display(value) : String(value);
}
/** Readable indented key/value view instead of a JSON dump; bounded in depth and lines. */
function readable(
	value: Record<string, unknown>,
	pad = "",
	out: string[] = [],
	depth = 0,
): string[] {
	for (const [key, item] of Object.entries(value)) {
		if (out.length >= MAX_LINES) break;
		if (key === "summary" || key === "answer" || key === PREVIEW_KEY) continue;
		if (Array.isArray(item)) {
			out.push(`${pad}${key}:${item.length ? "" : " none"}`);
			for (const entry of item.slice(0, 64)) {
				if (out.length >= MAX_LINES) break;
				if (entry && typeof entry === "object" && depth < 5) {
					out.push(`${pad}  -`);
					readable(object(entry), `${pad}    `, out, depth + 1);
				} else out.push(`${pad}  - ${scalar(entry)}`);
			}
		} else if (item && typeof item === "object" && depth < 5) {
			out.push(`${pad}${key}:`);
			readable(object(item), `${pad}  `, out, depth + 1);
		} else out.push(`${pad}${key}: ${scalar(item)}`);
	}
	return out;
}
function text(result: AgentToolResult<unknown>): string {
	return result.content
		.map((block) => (block.type === "text" ? block.text : ""))
		.join("\n");
}

export function hintBox(
	theme: Theme,
	style: "warning" | "error",
	message: string,
): Text {
	return new Text(theme.fg(style, display(message)), 0, 0);
}
export function expandableError(
	theme: Theme,
	message: string,
	expanded: boolean,
	hint: Hint = keyHint,
): Text {
	const full = terminal(message).trim();
	if (expanded) return new Text(theme.fg("error", full), 0, 0);
	const summary = display(full);
	const clipped = summary.length > 160 ? `${summary.slice(0, 159)}…` : summary;
	let out = theme.fg("error", clipped);
	if (clipped !== summary)
		out += `\n${theme.fg("muted", "↳")} ${hint("app.tools.expand", "to expand")}`;
	return new Text(out, 0, 0);
}

export function renderCall(kind: Kind) {
	return (args: unknown, theme: Theme): Text => {
		const a = object(args);
		let out = theme.fg("toolTitle", theme.bold(TITLES[kind]));
		const accent = (value: string) =>
			value ? ` ${theme.fg("accent", value)}` : "";
		if (kind === "vision") {
			out += accent(clip(sourceName(a["source"]), 60));
			if (typeof a["prompt"] === "string")
				out += ` ${theme.fg("dim", `"${clip(a["prompt"], 60)}"`)}`;
		} else if (kind === "speech") {
			if (typeof a["text"] === "string")
				out += accent(`"${clip(a["text"], 50)}"`);
			if (typeof a["outputPath"] === "string")
				out += ` ${theme.fg("muted", "→")}${accent(clip(basename(a["outputPath"]), 60))}`;
		} else if (kind === "video") {
			out += accent(clip(a["action"] ?? "", 12));
			if (typeof a["job"] === "string") out += accent(clip(a["job"], 80));
			if (a["action"] === "submit")
				out += ` ${theme.fg("dim", `${a["duration"] ?? 4}s ${clip(a["resolution"] ?? "768P", 5)}`)}`;
		}
		return new Text(out, 0, 0);
	};
}

interface Summary {
	headline: string;
	link?: { path: string; label: string };
	meta: (string | undefined)[];
	body: string[];
}
function videoLine(job: Record<string, unknown>, withArtifact = true): string {
	const parts = [clip(job["job"], 80)];
	if (typeof job["taskId"] === "string") parts.push(clip(job["taskId"], 128));
	parts.push(clip(job["state"], 40));
	const artifact = object(job["artifact"])["path"];
	return (
		parts.join(" · ") +
		(withArtifact && typeof artifact === "string"
			? ` → ${clip(artifact, 200)}`
			: "")
	);
}
function summarize(
	kind: Kind,
	details: Record<string, unknown>,
	content: string,
): Summary | undefined {
	const accounting = object(details["accounting"]);
	const quota = quotaLine(details["quota"]);
	if (kind === "vision" && typeof details["answer"] === "string")
		return {
			headline: `Answered · ${details["answer"].length} chars`,
			meta: [usd(accounting["usd"]), quota],
			body: [
				...terminal(details["answer"]).split("\n"),
				"",
				...readable(details),
			],
		};
	const artifact = object(details["artifact"]);
	if (kind === "speech" && typeof artifact["path"] === "string")
		return {
			headline: "Saved MP3",
			link: { path: artifact["path"], label: clip(artifact["path"], 200) },
			meta: [
				typeof accounting["units"] === "number"
					? `${accounting["units"]} chars`
					: undefined,
				size(artifact["bytes"]),
				usd(accounting["usd"]),
				quota,
			],
			body: readable(details),
		};
	if (kind === "video" && Array.isArray(details["jobs"]))
		return {
			headline: `${details["jobs"].length} owned H3 job${details["jobs"].length === 1 ? "" : "s"}`,
			meta: [],
			body: details["jobs"].slice(0, 64).map((job) => videoLine(object(job))),
		};
	if (kind === "video" && typeof details["job"] === "string")
		return {
			headline: videoLine(details, typeof artifact["path"] !== "string"),
			...(typeof artifact["path"] === "string"
				? {
						link: {
							path: artifact["path"],
							label: clip(artifact["path"], 200),
						},
					}
				: {}),
			meta: [
				typeof details["requestedDuration"] === "number"
					? `${details["requestedDuration"]}s ${clip(details["resolution"], 5)}`
					: undefined,
				size(artifact["bytes"]),
				// Show the estimate only on the observation that carried it, not on repeats.
				details["accountingDelivery"] === "already emitted; not recounted"
					? "counted earlier"
					: usd(accounting["usd"]),
				quota,
			],
			body: readable(details),
		};
	if (kind === "capabilities" && typeof details["region"] === "string")
		return {
			headline: `region ${clip(details["region"], 20)} · credential ${clip(object(details["credential"])["state"], 40)} · H3 ${clip(object(details["videoApproval"])["value"] ?? "invalid", 10)}`,
			meta: [],
			body: readable(details),
		};
	if (!content.trim()) return undefined;
	// Malformed or legacy details: fall back to the model-facing text.
	const lines = terminal(content).trim().split("\n");
	return {
		headline: clip(lines[0], 160),
		meta: [],
		body: lines.length > 1 || display(lines[0]).length > 160 ? lines : [],
	};
}

export function renderResult(kind: Kind) {
	return (
		result: AgentToolResult<unknown>,
		{ expanded, isPartial }: ToolRenderResultOptions,
		theme: Theme,
		context?: RenderContext,
	): Text | Container => {
		if (isPartial) return hintBox(theme, "warning", PROGRESS[kind]);
		const hint = context?.keyHint ?? keyHint;
		const details = object(result.details);
		const content = text(result);
		if (
			context?.isError ||
			(result as { isError?: boolean }).isError ||
			typeof details["errorKind"] === "string"
		)
			return expandableError(
				theme,
				`✗ ${typeof details["error"] === "string" ? details["error"] : content || "MiniMax operation failed."}`,
				expanded,
				hint,
			);
		const summary = summarize(kind, details, content);
		if (!summary) return new Text(theme.fg("success", "✓ Done"), 0, 0);
		const meta = summary.meta.filter((part): part is string => !!part);
		let out = theme.fg("success", `✓ ${summary.headline}`);
		if (summary.link)
			out += `${theme.fg("success", " → ")}${fileLink(summary.link.path, theme.fg("accent", summary.link.label))}`;
		if (meta.length) out += ` ${theme.fg("muted", meta.join(" · "))}`;
		if (summary.body.length) {
			if (expanded)
				for (const line of summary.body.slice(0, MAX_LINES))
					out += `\n${theme.fg("dim", line)}`;
			else
				out += `\n${theme.fg("muted", "↳")} ${hint("app.tools.expand", "to expand")}`;
		}
		const preview = details[PREVIEW_KEY];
		if (!context?.showImages || !isPreview(preview)) return new Text(out, 0, 0);
		const container = new Container();
		container.addChild(new Text(out, 0, 0));
		container.addChild(previewImage(preview, theme));
		return container;
	};
}

/** One Image per preview object: avoids re-encoding/re-sending Kitty payloads on re-render. */
const images = new WeakMap<Preview, Image>();
function previewImage(preview: Preview, theme: Theme): Image {
	let image = images.get(preview);
	if (!image) {
		image = new Image(
			preview.data,
			preview.mimeType,
			{ fallbackColor: (value) => theme.fg("dim", value) },
			{ maxHeightCells: 6, filename: "H3 preview" },
		);
		images.set(preview, image);
	}
	return image;
}