repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/llmiterate/log.ts

Raw
File outline
import { spawnSync } from "node:child_process";
import * as fs from "node:fs";
import * as path from "node:path";
import { previewText } from "./util";

export interface RenderedLogTarget {
	sessionFile: string;
	markdownFile: string;
}

export function latestSessionFile(sessionDir: string): string | undefined {
	const files: string[] = [];
	walk(sessionDir, (file) => {
		if (file.endsWith(".jsonl")) files.push(file);
	});
	return files.sort((a, b) => mtimeMs(b) - mtimeMs(a))[0];
}

export function renderLatestSessionLog(
	sessionDir: string,
	outDir: string,
): RenderedLogTarget | undefined {
	const sessionFile = latestSessionFile(sessionDir);
	if (!sessionFile) return undefined;

	fs.mkdirSync(outDir, { recursive: true });
	const markdownFile = path.join(outDir, "latest.md");
	fs.writeFileSync(
		markdownFile,
		renderSessionLogMarkdown(sessionFile),
		"utf-8",
	);
	return { sessionFile, markdownFile };
}

export function renderSessionLogMarkdown(sessionFile: string): string {
	const lines = fs
		.readFileSync(sessionFile, "utf-8")
		.split(/\r?\n/)
		.filter(Boolean);
	const out = ["# llmiterate log", "", `Session: ${sessionFile}`, ""];

	for (const line of lines) {
		let entry: unknown;
		try {
			entry = JSON.parse(line);
		} catch {
			continue;
		}
		const rendered = renderEntry(entry);
		if (rendered) out.push(rendered, "");
	}

	return out.join("\n").trimEnd() + "\n";
}

export interface EditorCommand {
	command: string;
	args: string[];
}

export function openInEditor(
	file: string,
	env: NodeJS.ProcessEnv = process.env,
): string | undefined {
	const editor = parseEditorCommand(env.VISUAL || env.EDITOR || "");
	if (!editor) return "VISUAL/EDITOR not set";

	const result = spawnSync(editor.command, [...editor.args, file], {
		stdio: "inherit",
	});
	if (result.error) return result.error.message;
	if (typeof result.status === "number" && result.status !== 0)
		return `${editor.command} exited with ${result.status}`;
	return undefined;
}

export function parseEditorCommand(input: string): EditorCommand | undefined {
	const args = shellWords(input);
	const command = args.shift();
	return command ? { command, args } : undefined;
}

function renderEntry(entry: unknown): string | undefined {
	if (!isObject(entry)) return undefined;
	const message = isObject(entry.message) ? entry.message : entry;
	const role = typeof message.role === "string" ? message.role : undefined;
	const text = contentText(message.content);

	if (role && text) return `## ${title(role)}\n\n${fence(text)}`;
	if (typeof entry.type === "string" && entry.type.includes("tool")) {
		return `## ${entry.type}\n\n${fence(previewText(JSON.stringify(entry, null, 2), 4000))}`;
	}
	return undefined;
}

function contentText(content: unknown): string {
	if (typeof content === "string") return content.trim();
	if (!Array.isArray(content)) return "";
	return content
		.map((part) => {
			if (!isObject(part)) return "";
			if (typeof part.text === "string") return part.text;
			if (typeof part.content === "string") return part.content;
			return "";
		})
		.filter(Boolean)
		.join("\n")
		.trim();
}

function title(role: string): string {
	return role.slice(0, 1).toUpperCase() + role.slice(1);
}

function fence(text: string): string {
	return `\`\`\`text\n${text}\n\`\`\``;
}

function walk(dir: string, onFile: (file: string) => void): void {
	let entries: fs.Dirent[];
	try {
		entries = fs.readdirSync(dir, { withFileTypes: true });
	} catch {
		return;
	}
	for (const entry of entries) {
		const file = path.join(dir, entry.name);
		if (entry.isDirectory()) walk(file, onFile);
		else if (entry.isFile()) onFile(file);
	}
}

function mtimeMs(file: string): number {
	try {
		return fs.statSync(file).mtimeMs;
	} catch {
		return 0;
	}
}

function shellWords(input: string): string[] {
	const words: string[] = [];
	let current = "";
	let quote: "'" | '"' | undefined;
	let escaped = false;

	for (const char of input.trim()) {
		if (escaped) {
			current += char;
			escaped = false;
			continue;
		}
		if (char === "\\") {
			escaped = true;
			continue;
		}
		if (quote) {
			if (char === quote) quote = undefined;
			else current += char;
			continue;
		}
		if (char === "'" || char === '"') {
			quote = char;
			continue;
		}
		if (/\s/.test(char)) {
			if (current) words.push(current);
			current = "";
			continue;
		}
		current += char;
	}

	if (current) words.push(current);
	return words;
}

function isObject(value: unknown): value is Record<string, unknown> {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}