Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/loop/__bench__/companion.ts

Raw
// Standalone preview of the loop companion in this terminal: no Pi, no loop run.
// Keys 1-5 switch the loop state she reacts to; q or Ctrl-C quits.
import { Theme } from "@earendil-works/pi-coding-agent";
import { type CompanionState, createCompanion } from "../src/companion.ts";

const theme = new Theme(
	{
		accent: "#e890b0",
		dim: "#777777",
		muted: "#888888",
		warning: "#c08040",
		thinkingXhigh: "#888888",
		text: "#eeeeee",
	} as ConstructorParameters<typeof Theme>[0],
	{ selectedBg: "" } as ConstructorParameters<typeof Theme>[1],
	"truecolor",
	{ appearance: "dark" },
);

const budgets = { minutes: 60, turns: 30, attempts: 10 };
let state: CompanionState = {
	status: "active",
	pending: false,
	attempts: 3,
	turns: 6,
	budgets,
	failed: { gate: "tests", at: 0 },
	updatedAt: Date.now(),
};
const scenes: Record<string, [string, () => CompanionState]> = {
	"1": [
		"running (posing)",
		() => ({
			...state,
			status: "active",
			pending: false,
			failed: { gate: "tests", at: 0 },
		}),
	],
	"2": [
		"gates checking",
		() => ({ ...state, status: "active", pending: true }),
	],
	"3": [
		"attempt failed",
		() => ({
			...state,
			status: "active",
			pending: false,
			attempts: state.attempts + 1,
			failed: { gate: "tests", at: Date.now() },
		}),
	],
	"4": ["paused", () => ({ ...state, status: "paused", pending: false })],
	"5": [
		"succeeded",
		() => ({
			...state,
			status: "succeeded",
			pending: false,
			updatedAt: Date.now(),
		}),
	],
};
let scene = "running (posing)";

const out = process.stdout;
const draw = () => {
	const width = out.columns || 80;
	const lines = widget.render(width);
	const help = theme.fg(
		"dim",
		`[${scene}]  1 run · 2 gates · 3 fail · 4 pause · 5 success · q quit`,
	);
	out.write(
		`\x1b[H${[...lines, "", help].map((line) => `${line}\x1b[K`).join("\n")}\x1b[J`,
	);
};
const widget = createCompanion(
	{ requestRender: draw } as never,
	theme,
	() => state,
);

const restore = () => {
	widget.dispose();
	out.write("\x1b[?25h\x1b[?1049l");
	if (process.stdin.isTTY) process.stdin.setRawMode(false);
	process.exit(0);
};
out.write("\x1b[?1049h\x1b[?25l\x1b[2J");
if (process.stdin.isTTY) process.stdin.setRawMode(true);
process.stdin.on("data", (data) => {
	const key = data.toString();
	if (key === "q" || key === "\x03") restore();
	const next = scenes[key];
	if (!next) return;
	scene = next[0];
	state = next[1]();
	draw();
});
out.on("resize", () => {
	out.write("\x1b[2J");
	draw();
});
process.on("SIGTERM", restore);
draw();