repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/neko/index.ts

Raw
File outline
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
	// @ts-expect-error — AutocompleteItem removed from upstream but used at runtime
	type AutocompleteItem,
	CustomEditor,
	type ExtensionAPI,
	type ExtensionContext,
	getAgentDir,
	SettingsManager,
} from "@earendil-works/pi-coding-agent";
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";

const DEBOUNCE_MS = 420;
const TICK_MS = 90;
const MOVE_STEP = 1;
const IDLE_ADVANCE_TICKS = 3;
const SLEEP_AFTER_MS = 30_000;
const ERROR_FLASH_MS = 2_500;
const COMPACTION_FAILSAFE_MS = 180_000;

type Facing = "left" | "right";
type Motion = "idle" | "walking";
type Activity =
	| "normal"
	| "thinking"
	| "working"
	| "compacting"
	| "error"
	| "sleeping";
type RawSpriteSet = Record<Motion, Record<Facing, string[]>>;
type SpriteSet = Record<Motion, Record<Facing, SpriteFrame[]>>;

type SpriteFrame = {
	text: string;
	width: number;
	noseAnchor: number;
};

const A = {
	reset: "\x1b[0m",
	gray: "\x1b[90m",
	red: "\x1b[31m",
	yellow: "\x1b[33m",
	blue: "\x1b[34m",
	magenta: "\x1b[35m",
	cyan: "\x1b[36m",
} as const;

const ACTIVITY_COLOR: Record<Activity, string> = {
	normal: A.cyan,
	thinking: A.blue,
	working: A.yellow,
	compacting: A.magenta,
	error: A.red,
	sleeping: A.gray,
};

const RAW_SPRITES: Record<Activity, RawSpriteSet> = {
	normal: {
		idle: {
			left: [
				"(=^・ω・^=)   ",
				"(=^・ω・^=)   ",
				"(=^˘ω˘^=)   ",
				"(=^・ω・^=)   ",
				"(=^・ω・^=)   ",
				"(=^・ω・^=)~  ",
				"(=^・ω・^=)~~ ",
				"(=^・ω・^=)~  ",
				"(=^・ω・^=)   ",
				"(=^・ω・^=)   ",
			],
			right: [
				"   (=^・ω・^=)",
				"   (=^・ω・^=)",
				"   (=^˘ω˘^=)",
				"   (=^・ω・^=)",
				"   (=^・ω・^=)",
				"  ~(=^・ω・^=)",
				" ~~(=^・ω・^=)",
				"  ~(=^・ω・^=)",
				"   (=^・ω・^=)",
				"   (=^・ω・^=)",
			],
		},
		walking: {
			left: ["(~^・ω・^∿)~~ ", "(~^・ω・^∿)~  ", "(~^・ω・^∿)<  ", "(~^・ω・^∿)~  "],
			right: [" ~~(∿^・ω・^~)", "  ~(∿^・ω・^~)", "  >(∿^・ω・^~)", "  ~(∿^・ω・^~)"],
		},
	},

	thinking: {
		idle: {
			left: [
				"(?^・ω・^?)   ",
				"(?^・ω・^?) . ",
				"(?^・ω・^?) ..",
				"(?^˘ω˘^?) ..",
				"(?^・ω・^?) ..",
				"(?^・ω・^?) . ",
			],
			right: [
				"   (?^・ω・^?)",
				" . (?^・ω・^?)",
				".. (?^・ω・^?)",
				".. (?^˘ω˘^?)",
				".. (?^・ω・^?)",
				" . (?^・ω・^?)",
			],
		},
		walking: {
			left: ["(?^・ω・^∿)?? ", "(?^・ω・^∿)?  ", "(?^・ω・^∿)<  ", "(?^˘ω˘^∿)?  "],
			right: [" ??(∿^・ω・^?)", "  ?(∿^・ω・^?)", "  >(∿^・ω・^?)", "  ?(∿^˘ω˘^?)"],
		},
	},

	working: {
		idle: {
			left: ["(=^・ω・^=)  ", "(=^>ω<^=)  ", "(=^・ω・^=)  ", "(=^>ω<^=)  "],
			right: ["  (=^・ω・^=)", "  (=^>ω<^=)", "  (=^・ω・^=)", "  (=^>ω<^=)"],
		},
		walking: {
			left: ["(^・ω・^∿)~~ ", "(^・ω・^∿)~  ", "(^>ω<^∿)<  ", "(^・ω・^∿)~  "],
			right: [" ~~(∿^・ω・^)", "  ~(∿^・ω・^)", "  >(∿^>ω<^)", "  ~(∿^・ω・^)"],
		},
	},

	compacting: {
		idle: {
			left: ["[=^・ω・^=]  ", "[=^˘ω˘^=]  ", "[=^・ω・^=]▣ ", "[=^・ω・^=]▥ "],
			right: ["  [=^・ω・^=]", "  [=^˘ω˘^=]", " ▣[=^・ω・^=]", " ▥[=^・ω・^=]"],
		},
		walking: {
			left: ["[~^・ω・^∿]▣ ", "[~^・ω・^∿]▥ ", "[~^・ω・^∿]< ", "[~^˘ω˘^∿]▥ "],
			right: [" ▣[∿^・ω・^~]", " ▥[∿^・ω・^~]", " >[∿^・ω・^~]", " ▥[∿^˘ω˘^~]"],
		},
	},

	error: {
		idle: {
			left: ["(!^ಠωಠ^)!! ", "(!!ಠωಠ^)! ", "(!^ಠωಠ!!) ", "(!!ಠωಠ!!) "],
			right: [" !!(^ಠωಠ^!)", " !(^ಠωಠ!!)", " (!!ಠωಠ^!)", " (!!ಠωಠ!!)"],
		},
		walking: {
			left: ["(!^ಠωಠ^∿)!!", "(!^ಠωಠ^∿)! ", "(!^ಠωಠ^∿)< ", "(!^ಠωಠ^∿)! "],
			right: ["!!(∿^ಠωಠ^!)", " !(∿^ಠωಠ^!)", " >(∿^ಠωಠ^!)", " !(∿^ಠωಠ^!)"],
		},
	},

	sleeping: {
		idle: {
			left: ["(-˘ω˘-) z ", "(-˘ω˘-) z ", "(-˘ω˘-) Z ", "(-˘ω˘-)   "],
			right: [" z (-˘ω˘-)", " z (-˘ω˘-)", " Z (-˘ω˘-)", "   (-˘ω˘-)"],
		},
		walking: {
			left: ["(-˘ω˘-∿)z ", "(-˘ω˘-∿)z ", "(-˘ω˘-∿)< ", "(-˘ω˘-∿)  "],
			right: [" z(∿-˘ω˘-)", " z(∿-˘ω˘-)", " >(∿-˘ω˘-)", "  (∿-˘ω˘-)"],
		},
	},
};

function color(activity: Activity, text: string): string {
	return `${ACTIVITY_COLOR[activity]}${text}${A.reset}`;
}

function makeFrame(activity: Activity, raw: string): SpriteFrame {
	const noseIndex = raw.indexOf("ω");
	const noseAnchor =
		noseIndex >= 0
			? visibleWidth(raw.slice(0, noseIndex))
			: Math.floor(visibleWidth(raw) / 2);

	return {
		text: color(activity, raw),
		width: visibleWidth(raw),
		noseAnchor,
	};
}

function makeSpriteSet(activity: Activity, raw: RawSpriteSet): SpriteSet {
	return {
		idle: {
			left: raw.idle.left.map((frame) => makeFrame(activity, frame)),
			right: raw.idle.right.map((frame) => makeFrame(activity, frame)),
		},
		walking: {
			left: raw.walking.left.map((frame) => makeFrame(activity, frame)),
			right: raw.walking.right.map((frame) => makeFrame(activity, frame)),
		},
	};
}

const SPRITES = Object.fromEntries(
	(Object.entries(RAW_SPRITES) as [Activity, RawSpriteSet][]).map(
		([activity, sprites]) => [activity, makeSpriteSet(activity, sprites)],
	),
) as Record<Activity, SpriteSet>;

function clamp(value: number, min: number, max: number): number {
	return Math.max(min, Math.min(value, max));
}

function overlayLine(width: number, frame: SpriteFrame, x: number): string {
	if (width <= 0) return "";
	if (frame.width >= width) return truncateToWidth(frame.text, width, "", true);

	const left = clamp(x, 0, width - frame.width);
	const right = Math.max(0, width - left - frame.width);
	return " ".repeat(left) + frame.text + " ".repeat(right);
}

// @ts-expect-error — private paddingX conflicts with base class CustomEditor
class NekoEditor extends CustomEditor {
	private noseX = 2;
	private targetNoseX = 2;
	private facing: Facing = "left";
	private paddingX: number;
	private activity: Activity;

	private frame = 0;
	private idleTick = 0;
	private lastRenderWidth = 80;
	private lastInputAt = Date.now();

	private debounceTimer: ReturnType<typeof setTimeout> | null = null;
	private animTimer: ReturnType<typeof setInterval> | null = null;

	constructor(
		paddingX: number,
		activity: Activity,
		...args: ConstructorParameters<typeof CustomEditor>
	) {
		super(...args);
		this.paddingX = paddingX;
		this.activity = activity;

		this.animTimer = setInterval(() => {
			let changed = false;
			const delta = this.targetNoseX - this.noseX;
			const motion: Motion = Math.abs(delta) > MOVE_STEP ? "walking" : "idle";
			const frames = this.framesFor(motion);

			if (motion === "walking") {
				this.facing = delta > 0 ? "right" : "left";
				const step = Math.min(MOVE_STEP, Math.abs(delta));
				this.noseX += this.facing === "right" ? step : -step;
				this.frame = (this.frame + 1) % frames.length;
				this.idleTick = 0;
				changed = true;
			} else if (delta !== 0) {
				this.noseX = this.targetNoseX;
				this.idleTick = 0;
				changed = true;
			} else {
				this.idleTick++;
				if (this.idleTick % IDLE_ADVANCE_TICKS === 0) {
					this.frame = (this.frame + 1) % frames.length;
					changed = true;
				}
			}

			if (changed) this.tui.requestRender();
		}, TICK_MS);
	}

	public setActivity(activity: Activity): void {
		if (this.activity === activity) return;
		this.activity = activity;
		this.frame = 0;
		this.idleTick = 0;
		this.tui.requestRender();
	}

	private displayActivity(): Activity {
		const moving = Math.abs(this.targetNoseX - this.noseX) > MOVE_STEP;
		if (
			this.activity === "normal" &&
			!moving &&
			Date.now() - this.lastInputAt >= SLEEP_AFTER_MS
		) {
			return "sleeping";
		}
		return this.activity;
	}

	private framesFor(motion: Motion): SpriteFrame[] {
		return SPRITES[this.displayActivity()][motion][this.facing];
	}

	private currentFrame(): SpriteFrame {
		const motion: Motion =
			Math.abs(this.targetNoseX - this.noseX) > MOVE_STEP ? "walking" : "idle";
		const frames = this.framesFor(motion);
		const frame = frames[this.frame % frames.length];
		if (!frame) throw new Error(`missing neko sprite frame: ${motion}`);
		return frame;
	}

	override setPaddingX(padding: number): void {
		super.setPaddingX(padding);
		this.paddingX = Math.max(0, Math.floor(padding));
	}

	private inputWidth(): number {
		const maxPadding = Math.max(0, Math.floor((this.lastRenderWidth - 1) / 2));
		const paddingX = Math.min(this.paddingX, maxPadding);

		// In Pi's editor, editorPaddingX shifts input content right; visually it is
		// left padding. Track against the visible input span, not symmetric padding.
		return Math.max(1, this.lastRenderWidth - paddingX);
	}

	private noseBounds(frame = this.currentFrame()): {
		min: number;
		max: number;
	} {
		if (this.lastRenderWidth <= frame.width) {
			return { min: 0, max: Math.max(0, this.lastRenderWidth - 1) };
		}

		return {
			min: frame.noseAnchor,
			max: this.lastRenderWidth - frame.width + frame.noseAnchor,
		};
	}

	private clampNoseX(value: number, frame = this.currentFrame()): number {
		const { min, max } = this.noseBounds(frame);
		return clamp(value, min, max);
	}

	private updateTargetFromCursor(): void {
		const cursor = this.getCursor();
		const line = this.getLines()[cursor.line] ?? "";
		const visualCol =
			visibleWidth(line.slice(0, cursor.col)) % this.inputWidth();

		const rawTargetNoseX = this.paddingX + visualCol;

		const delta = rawTargetNoseX - this.noseX;
		if (delta !== 0) this.facing = delta > 0 ? "right" : "left";

		this.targetNoseX = this.clampNoseX(rawTargetNoseX);

		this.tui.requestRender();
	}

	private scheduleMoveToCursor(): void {
		if (this.debounceTimer) clearTimeout(this.debounceTimer);
		this.debounceTimer = setTimeout(
			() => this.updateTargetFromCursor(),
			DEBOUNCE_MS,
		);
	}

	override handleInput(data: string): void {
		this.lastInputAt = Date.now();
		super.handleInput(data);
		this.scheduleMoveToCursor();
	}

	override render(width: number): string[] {
		const editorLines = super.render(width);
		if (width <= 0) return editorLines;

		this.lastRenderWidth = width;

		const frame = this.currentFrame();
		this.noseX = this.clampNoseX(this.noseX, frame);
		this.targetNoseX = this.clampNoseX(this.targetNoseX, frame);

		const left = this.noseX - frame.noseAnchor;
		const catLine = overlayLine(width, frame, left);

		return [catLine, ...editorLines];
	}

	public dispose(): void {
		if (this.debounceTimer) clearTimeout(this.debounceTimer);
		if (this.animTimer) clearInterval(this.animTimer);
	}
}

interface NekoSettings {
	enabled?: boolean;
}

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

function mergedSettings(cwd: string): Record<string, unknown> {
	const manager = SettingsManager.create(cwd);
	const global = manager.getGlobalSettings() as Record<string, unknown>;
	const project = manager.getProjectSettings() as Record<string, unknown>;
	return {
		...global,
		...project,
		neko: {
			...settingsRecord(global.neko),
			...settingsRecord(project.neko),
		},
	};
}

function resolveEditorPaddingX(cwd: string): number {
	const value = mergedSettings(cwd).editorPaddingX;
	return typeof value === "number" && value > 0 ? value : 0;
}

function isNekoEnabled(cwd: string, override?: boolean): boolean {
	if (override !== undefined) return override;
	const raw = mergedSettings(cwd).neko;
	return !(
		raw &&
		typeof raw === "object" &&
		!Array.isArray(raw) &&
		(raw as Record<string, unknown>).enabled === false
	);
}

function updateNekoSettings(values: Partial<NekoSettings>): void {
	const filePath = join(getAgentDir(), "settings.json");
	let settings: Record<string, unknown> = {};
	try {
		if (existsSync(filePath))
			settings = JSON.parse(readFileSync(filePath, "utf-8"));
	} catch {
		settings = {};
	}
	const existing =
		settings.neko &&
		typeof settings.neko === "object" &&
		!Array.isArray(settings.neko)
			? (settings.neko as Record<string, unknown>)
			: {};
	settings.neko = { ...existing, ...values };
	try {
		writeFileSync(filePath, JSON.stringify(settings, null, 2) + "\n", "utf-8");
	} catch {
		/* best-effort */
	}
}

export default function nekoExtension(pi: ExtensionAPI) {
	const activeEditors = new Set<NekoEditor>();
	let agentRunning = false;
	let toolsRunning = 0;
	let compacting = false;
	let enabledOverride: boolean | undefined;
	let compactingTimer: ReturnType<typeof setTimeout> | null = null;
	let errorUntil = 0;
	let errorTimer: ReturnType<typeof setTimeout> | null = null;

	const resolveActivity = (): Activity => {
		if (Date.now() < errorUntil) return "error";
		if (compacting) return "compacting";
		if (toolsRunning > 0) return "working";
		if (agentRunning) return "thinking";
		return "normal";
	};

	const updateActivity = () => {
		const activity = resolveActivity();
		for (const editor of activeEditors) editor.setActivity(activity);
	};

	const disposeEditors = () => {
		for (const editor of activeEditors) editor.dispose();
		activeEditors.clear();
	};

	const applyEditor = (ctx: ExtensionContext) => {
		if (!ctx.hasUI) return;

		disposeEditors();

		if (!isNekoEnabled(ctx.cwd, enabledOverride)) {
			ctx.ui.setWorkingVisible?.(true);
			ctx.ui.setEditorComponent?.(undefined);
			return;
		}

		ctx.ui.setWorkingVisible?.(false);

		const paddingX = resolveEditorPaddingX(ctx.cwd);
		ctx.ui.setEditorComponent?.((tui, theme, keybindings) => {
			const editor = new NekoEditor(
				paddingX,
				resolveActivity(),
				tui,
				theme,
				keybindings,
			);
			activeEditors.add(editor);
			return editor;
		});
	};

	const setEnabled = (ctx: ExtensionContext, enabled: boolean) => {
		enabledOverride = enabled;
		updateNekoSettings({ enabled });
		applyEditor(ctx);
		if (ctx.hasUI) ctx.ui.notify(`Neko ${enabled ? "ON" : "OFF"}`, "info");
	};

	const clearCompactingTimer = () => {
		if (!compactingTimer) return;
		clearTimeout(compactingTimer);
		compactingTimer = null;
	};

	const stopCompacting = () => {
		clearCompactingTimer();
		compacting = false;
		updateActivity();
	};

	const startCompacting = () => {
		clearCompactingTimer();
		compacting = true;
		updateActivity();
		compactingTimer = setTimeout(() => {
			compactingTimer = null;
			compacting = false;
			updateActivity();
		}, COMPACTION_FAILSAFE_MS);
	};

	const flashError = () => {
		errorUntil = Date.now() + ERROR_FLASH_MS;
		updateActivity();
		if (errorTimer) clearTimeout(errorTimer);
		errorTimer = setTimeout(() => {
			errorTimer = null;
			updateActivity();
		}, ERROR_FLASH_MS);
	};

	pi.registerCommand("neko", {
		description: "Toggle neko editor cat: /neko [on|off|status]",
		getArgumentCompletions(text: string): AutocompleteItem[] {
			const opts = ["on", "off", "toggle", "status"];
			return opts
				.filter((opt) => opt.startsWith(text))
				.map((opt) => ({ value: opt, label: opt }));
		},
		handler: async (args, ctx) => {
			const arg = args.trim().toLowerCase();
			const enabled = isNekoEnabled(ctx.cwd, enabledOverride);

			switch (arg) {
				case "":
				case "toggle":
					setEnabled(ctx, !enabled);
					break;
				case "on":
					setEnabled(ctx, true);
					break;
				case "off":
					setEnabled(ctx, false);
					break;
				case "status":
					if (ctx.hasUI)
						ctx.ui.notify(`Neko ${enabled ? "ON" : "OFF"}`, "info");
					break;
				default:
					if (ctx.hasUI)
						ctx.ui.notify("Usage: /neko [on|off|toggle|status]", "warning");
			}
		},
	});

	pi.on("session_start", async (_event, ctx) => applyEditor(ctx));
	pi.on("agent_start", async () => {
		agentRunning = true;
		updateActivity();
	});
	pi.on("agent_end", async () => {
		agentRunning = false;
		toolsRunning = 0;
		stopCompacting();
	});
	pi.on("tool_execution_start", async () => {
		toolsRunning++;
		updateActivity();
	});
	pi.on("tool_execution_end", async () => {
		toolsRunning = Math.max(0, toolsRunning - 1);
		updateActivity();
	});
	pi.on("tool_result", async (event) => {
		if (event.isError) flashError();
	});
	pi.on("session_before_compact", async () => {
		startCompacting();
	});
	pi.on("session_compact", async () => {
		stopCompacting();
	});
	pi.on("session_shutdown", async (_event, ctx) => {
		disposeEditors();
		if (errorTimer) clearTimeout(errorTimer);
		clearCompactingTimer();
		if (ctx.hasUI) {
			ctx.ui.setWorkingVisible?.(true);
			ctx.ui.setEditorComponent?.(undefined);
		}
	});
}