repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/prune/src/normalize.ts

Raw
/**
 * prune — normalize messages to blocks
 */

import type { Block, ContentPart, Message } from "./types.ts";

/**
 * Map pi Message array to normalized Block array.
 * Each block gets a sourceIndex pointing to original message.
 */
export function normalize(messages: Message[]): Block[] {
	return messages.flatMap((msg, i) => normalizeOne(msg, i + 1));
}

function normalizeOne(msg: Message, msgIndex: number): Block[] {
	switch (msg.role) {
		case "user":
			return normalizeUser(msg, msgIndex);
		case "assistant":
			return normalizeAssistant(msg, msgIndex);
		case "tool":
		case "toolResult":
			return normalizeTool(msg, msgIndex);
		default:
			return [];
	}
}

function normalizeUser(msg: Message, msgIndex: number): Block[] {
	const text = extractText(msg.content);
	if (!text.trim()) return [];
	return [{ kind: "user", text, sourceIndex: msgIndex }];
}

function normalizeAssistant(msg: Message, msgIndex: number): Block[] {
	const blocks: Block[] = [];

	if (!msg.content) return [];

	if (typeof msg.content === "string") {
		if (msg.content.trim()) {
			blocks.push({
				kind: "assistant",
				text: msg.content,
				sourceIndex: msgIndex,
			});
		}
		return blocks;
	}

	for (const part of msg.content) {
		switch (part.type) {
			case "text":
				if (part.text?.trim()) {
					blocks.push({
						kind: "assistant",
						text: part.text,
						sourceIndex: msgIndex,
					});
				}
				break;
			case "thinking":
				// Skip thinking blocks
				break;
			case "toolCall":
				if (part.name?.trim()) {
					blocks.push({
						kind: "tool_call",
						text: "",
						sourceIndex: msgIndex,
						name: part.name,
						args: part.arguments,
					});
				}
				break;
			case "image":
				// Skip images
				break;
		}
	}

	return blocks;
}

function normalizeTool(msg: Message, msgIndex: number): Block[] {
	const text = extractText(msg.content);
	return [
		{
			kind: "tool_result",
			text,
			sourceIndex: msgIndex,
			name: msg.toolName,
			isError: msg.isError,
		},
	];
}

function extractText(content: string | ContentPart[] | undefined): string {
	if (!content) return "";
	if (typeof content === "string") return content.trim();

	const parts: string[] = [];
	for (const part of content) {
		if (part.type === "text" && part.text) {
			parts.push(part.text);
		}
	}
	return parts.join(" ").trim();
}