repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/notes/index.ts

Raw
File outline
import type {
	ExtensionAPI,
	ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import type { AutocompleteItem } from "@earendil-works/pi-tui";
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";

const ENTRY_TYPE = "notes-state";
const WIDGET_KEY = "notes";
const NOTES_ICON = "󰎚";
const WIDGET_DEFAULT_WIDTH = 80;
const NEW_SESSION_NOTES = Symbol.for("@bugabinga/pi-ext-notes/new-session");

type Note = { id: number; text: string };
type NotesEvent =
	| { op: "add"; id: number; text: string; createdAt: number }
	| { op: "edit"; id: number; text: string; updatedAt: number }
	| { op: "remove"; id: number; removedAt: number }
	| { op: "clear"; clearedAt: number };

type SessionEntryLike = {
	type?: unknown;
	customType?: unknown;
	data?: unknown;
};

type NotesState = {
	notes: Map<number, Note>;
	nextId: number;
};

function createState(): NotesState {
	return { notes: new Map(), nextId: 1 };
}

function isPositiveInteger(value: unknown): value is number {
	return Number.isInteger(value) && typeof value === "number" && value > 0;
}

function isNonEmptyText(value: unknown): value is string {
	return typeof value === "string" && value.trim().length > 0;
}

function parseEvent(data: unknown): NotesEvent | undefined {
	if (!data || typeof data !== "object") return undefined;
	const event = data as Record<string, unknown>;
	if (
		event.op === "add" &&
		isPositiveInteger(event.id) &&
		isNonEmptyText(event.text) &&
		typeof event.createdAt === "number"
	) {
		return {
			op: "add",
			id: event.id,
			text: event.text.trim(),
			createdAt: event.createdAt,
		};
	}
	if (
		event.op === "edit" &&
		isPositiveInteger(event.id) &&
		isNonEmptyText(event.text) &&
		typeof event.updatedAt === "number"
	) {
		return {
			op: "edit",
			id: event.id,
			text: event.text.trim(),
			updatedAt: event.updatedAt,
		};
	}
	if (
		event.op === "remove" &&
		isPositiveInteger(event.id) &&
		typeof event.removedAt === "number"
	) {
		return { op: "remove", id: event.id, removedAt: event.removedAt };
	}
	if (event.op === "clear" && typeof event.clearedAt === "number") {
		return { op: "clear", clearedAt: event.clearedAt };
	}
	return undefined;
}

function applyEvent(state: NotesState, event: NotesEvent): void {
	if (event.op === "add") {
		state.notes.set(event.id, { id: event.id, text: event.text });
		state.nextId = Math.max(state.nextId, event.id + 1);
		return;
	}
	if (event.op === "edit") {
		const note = state.notes.get(event.id);
		if (!note) return;
		state.notes.set(event.id, { id: event.id, text: event.text });
		state.nextId = Math.max(state.nextId, event.id + 1);
		return;
	}
	if (event.op === "remove") {
		if (!state.notes.has(event.id)) return;
		state.notes.delete(event.id);
		state.nextId = Math.max(state.nextId, event.id + 1);
		return;
	}
	state.notes.clear();
}

function replayNotes(entries: SessionEntryLike[]): NotesState {
	const state = createState();
	for (const entry of entries) {
		if (entry.type !== "custom" || entry.customType !== ENTRY_TYPE) continue;
		const event = parseEvent(entry.data);
		if (event) applyEvent(state, event);
	}
	return state;
}

function pendingNotes(state: NotesState): Note[] {
	return [...state.notes.values()].sort((a, b) => a.id - b.id);
}

function replaceState(target: NotesState, source: NotesState): void {
	target.notes = source.notes;
	target.nextId = source.nextId;
}

function newSessionHandoffs(): Map<string | undefined, Note[]> {
	const existing = Reflect.get(globalThis, NEW_SESSION_NOTES);
	if (existing instanceof Map) return existing;
	const handoffs = new Map<string | undefined, Note[]>();
	Reflect.set(globalThis, NEW_SESSION_NOTES, handoffs);
	return handoffs;
}

function stashNewSessionNotes(
	targetSessionFile: string | undefined,
	notes: Note[],
): void {
	newSessionHandoffs().set(targetSessionFile, structuredClone(notes));
}

function takeNewSessionNotes(targetSessionFile?: string): Note[] {
	const handoffs = newSessionHandoffs();
	const notes = handoffs.get(targetSessionFile) ?? [];
	handoffs.delete(targetSessionFile);
	if (handoffs.size === 0)
		Reflect.deleteProperty(globalThis, NEW_SESSION_NOTES);
	return notes;
}

function appendEvent(
	pi: ExtensionAPI,
	state: NotesState,
	event: NotesEvent,
): void {
	pi.appendEntry(ENTRY_TYPE, event);
	applyEvent(state, event);
}

function notify(
	ctx: ExtensionContext,
	message: string,
	type: "info" | "warning" | "error" = "info",
): void {
	if (ctx.hasUI) ctx.ui.notify(message, type);
}

function preview(text: string, max = 72): string {
	const oneLine = text
		.replace(/[\x00-\x1F\x7F]+/g, " ")
		.replace(/ +/g, " ")
		.trim();
	return oneLine.length > max
		? `${oneLine.slice(0, Math.max(0, max - 1))}…`
		: oneLine;
}

function fitVisible(text: string, width: number): string {
	return truncateToWidth(text, Math.max(0, width), "…");
}

function wrapVisibleWords(text: string, width: number): string[] {
	if (width <= 0) return [""];
	const words = text.replace(/\s+/g, " ").trim().split(" ").filter(Boolean);
	if (words.length === 0) return [""];
	const lines: string[] = [];
	let line = "";
	for (const word of words) {
		if (visibleWidth(word) > width) {
			if (line) {
				lines.push(line);
				line = "";
			}
			let rest = word;
			while (visibleWidth(rest) > width) {
				const part = truncateToWidth(rest, width, "");
				if (!part) break;
				lines.push(part);
				rest = rest.slice(part.length);
			}
			line = rest;
			continue;
		}
		const candidate = line ? `${line} ${word}` : word;
		if (visibleWidth(candidate) <= width) line = candidate;
		else {
			lines.push(line);
			line = word;
		}
	}
	if (line) lines.push(line);
	return lines;
}

function iconWrap(rows: string[], width: number): string[] {
	const safeWidth = Math.max(1, width);
	const firstPrefix = `${NOTES_ICON}  `;
	const nextPrefix = "   ";
	const lines: string[] = [];
	for (const row of rows) {
		const prefix = lines.length === 0 ? firstPrefix : nextPrefix;
		const textWidth = Math.max(1, safeWidth - visibleWidth(prefix));
		for (const part of wrapVisibleWords(row, textWidth)) {
			lines.push(`${lines.length === 0 ? firstPrefix : nextPrefix}${part}`);
		}
	}
	return lines;
}

function compactWidgetLine(
	state: NotesState,
	width = WIDGET_DEFAULT_WIDTH,
): string {
	const notes = pendingNotes(state);
	const last = notes.at(-1);
	return fitVisible(
		`${NOTES_ICON}  ${notes.length} notes · alt+n expand · last: ${preview(
			last?.text ?? "",
		)}`,
		width,
	);
}

function expandedWidgetLines(
	state: NotesState,
	width = WIDGET_DEFAULT_WIDTH,
): string[] {
	const notes = pendingNotes(state);
	const lines = iconWrap([`notes · ${notes.length}`], width);
	for (const note of notes) {
		const prefix = `   ${note.id}  `;
		const textWidth = Math.max(1, width - visibleWidth(prefix));
		for (const [index, part] of wrapVisibleWords(
			note.text,
			textWidth,
		).entries()) {
			lines.push(`${index === 0 ? prefix : "   "}${part}`);
		}
	}
	return lines;
}

function widgetLines(
	state: NotesState,
	expanded: boolean,
	width = WIDGET_DEFAULT_WIDTH,
): string[] | undefined {
	if (state.notes.size === 0) return undefined;
	return expanded
		? expandedWidgetLines(state, width)
		: [compactWidgetLine(state, width)];
}

function splitCommand(args: string): { command: string; rest: string } {
	const trimmed = args.trim();
	const space = trimmed.indexOf(" ");
	if (space === -1) return { command: trimmed, rest: "" };
	return {
		command: trimmed.slice(0, space),
		rest: trimmed.slice(space + 1).trim(),
	};
}

function parseId(text: string): number | undefined {
	const value = Number(text.trim());
	return isPositiveInteger(value) ? value : undefined;
}

function requireNote(
	ctx: ExtensionContext,
	state: NotesState,
	idText: string,
): Note | undefined {
	const id = parseId(idText);
	if (!id || !state.notes.has(id)) {
		notify(ctx, `Unknown note id: ${idText.trim() || "?"}`, "error");
		return undefined;
	}
	return state.notes.get(id);
}

const SUBCOMMANDS = ["add", "send", "edit", "rm", "clear"] as const;

function argumentCompletions(
	state: NotesState,
	argumentPrefix: string,
): AutocompleteItem[] {
	const { command, rest } = splitCommand(argumentPrefix);
	if (!argumentPrefix.includes(" ")) {
		return SUBCOMMANDS.filter((item) => item.startsWith(command)).map(
			(item) => ({
				value: item,
				label: item,
			}),
		);
	}
	if (command !== "send" && command !== "edit" && command !== "rm") return [];
	return pendingNotes(state)
		.filter((note) => String(note.id).startsWith(rest))
		.map((note) => ({
			value: `${command} ${note.id}`,
			label: `${note.id}  ${preview(note.text)}`,
		}));
}

export default function notesExtension(pi: ExtensionAPI): void {
	const state = createState();
	let expanded = false;

	function refreshWidget(ctx: ExtensionContext): void {
		if (!ctx.hasUI) return;
		if (state.notes.size === 0) {
			ctx.ui.setWidget(WIDGET_KEY, undefined);
			return;
		}
		ctx.ui.setWidget(WIDGET_KEY, () => ({
			invalidate() {},
			render(width: number): string[] {
				return widgetLines(state, expanded, width) ?? [];
			},
		}));
	}

	function toggleWidget(ctx: ExtensionContext): void {
		if (state.notes.size === 0) {
			notify(ctx, "No pending notes", "info");
			refreshWidget(ctx);
			return;
		}
		expanded = !expanded;
		refreshWidget(ctx);
	}

	pi.registerCommand("note", {
		description: "Park, inspect, edit, send, or clear pending prompt notes.",
		getArgumentCompletions: (argumentPrefix) =>
			argumentCompletions(state, argumentPrefix),
		async handler(args, ctx) {
			const trimmed = args.trim();
			const { command, rest } = splitCommand(trimmed);

			if (!trimmed) {
				toggleWidget(ctx);
				return;
			}

			if (command === "add") {
				const text = rest.trim();
				if (!text) {
					notify(ctx, "Note text required", "warning");
					return;
				}
				const wasEmpty = state.notes.size === 0;
				appendEvent(pi, state, {
					op: "add",
					id: state.nextId,
					text,
					createdAt: Date.now(),
				});
				if (wasEmpty) expanded = false;
				refreshWidget(ctx);
				return;
			}

			if (command === "rm") {
				const note = requireNote(ctx, state, rest);
				if (!note) return;
				appendEvent(pi, state, {
					op: "remove",
					id: note.id,
					removedAt: Date.now(),
				});
				refreshWidget(ctx);
				return;
			}

			if (command === "clear") {
				if (state.notes.size === 0) {
					notify(ctx, "No pending notes", "info");
					refreshWidget(ctx);
					return;
				}
				const confirmed = await ctx.ui.confirm(
					"Clear notes?",
					`Remove ${state.notes.size} pending notes?`,
				);
				if (!confirmed) return;
				appendEvent(pi, state, { op: "clear", clearedAt: Date.now() });
				refreshWidget(ctx);
				return;
			}

			if (command === "edit") {
				const note = requireNote(ctx, state, rest);
				if (!note) return;
				const edited = await ctx.ui.editor(`Edit note ${note.id}`, note.text);
				if (edited === undefined) return;
				const text = edited.trim();
				if (!text) {
					notify(ctx, "Note text required", "warning");
					return;
				}
				appendEvent(pi, state, {
					op: "edit",
					id: note.id,
					text,
					updatedAt: Date.now(),
				});
				refreshWidget(ctx);
				return;
			}

			if (command === "send") {
				const note = requireNote(ctx, state, rest);
				if (!note) return;
				if (ctx.isIdle()) pi.sendUserMessage(note.text);
				else pi.sendUserMessage(note.text, { deliverAs: "followUp" });
				appendEvent(pi, state, {
					op: "remove",
					id: note.id,
					removedAt: Date.now(),
				});
				refreshWidget(ctx);
				return;
			}

			notify(ctx, "Usage: /note [add|send|edit|rm|clear]", "warning");
			refreshWidget(ctx);
		},
	});

	pi.registerShortcut("alt+n", {
		description: "Toggle notes widget",
		handler: async (ctx) => toggleWidget(ctx),
	});

	function restoreBranch(ctx: ExtensionContext): void {
		replaceState(
			state,
			replayNotes(ctx.sessionManager.getBranch() as SessionEntryLike[]),
		);
		expanded = false;
		refreshWidget(ctx);
	}

	pi.on("session_shutdown", (event) => {
		if (event.reason === "new") {
			stashNewSessionNotes(event.targetSessionFile, pendingNotes(state));
		}
	});

	pi.on("session_start", async (event, ctx) => {
		restoreBranch(ctx);
		if (event.reason !== "new") return;

		const notes = takeNewSessionNotes(ctx.sessionManager.getSessionFile());
		if (
			notes.length === 0 ||
			!ctx.hasUI ||
			!(await ctx.ui.confirm(
				"Carry notes?",
				`Copy ${notes.length} pending notes into the new session?`,
			))
		) {
			return;
		}
		for (const note of notes) {
			appendEvent(pi, state, {
				op: "add",
				id: note.id,
				text: note.text,
				createdAt: Date.now(),
			});
		}
		refreshWidget(ctx);
	});

	pi.on("session_tree", (_event, ctx) => restoreBranch(ctx));
}

export const __test = {
	ENTRY_TYPE,
	argumentCompletions,
	compactWidgetLine,
	expandedWidgetLines,
	parseEvent,
	pendingNotes,
	preview,
	replayNotes,
	takeNewSessionNotes,
	widgetLines,
};