repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/timing/index.ts

Raw
File outline
/**
 * Wall-clock timing footer segment producer.
 *
 * Tracks agent time, turn time, and session time with 250ms polling.
 * Emits footer:segment with zone "llm".
 */

import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";

function fmtMin(ms: number | null): string {
	if (ms === null) return "--";
	const s = Math.round(ms / 1000);
	if (s < 60) return `${s}s`;
	const m = Math.floor(s / 60);
	const rs = s % 60;
	return rs > 0 ? `${m}m${rs}s` : `${m}m`;
}

const POLL_MS = 250;

export default function timingExtension(pi: ExtensionAPI) {
	let sessionStart: number | null = null;
	let agentStart: number | null = null;
	let lastAgentMs: number | null = null;
	let turnStart: number | null = null;
	let turnAccumMs = 0;
	let timer: ReturnType<typeof setInterval> | null = null;
	let lastSig = "";
	let hasUI = false;

	const getAgentMs = (now: number): number | null => {
		if (agentStart !== null) return now - agentStart;
		return lastAgentMs;
	};

	const getTurnMs = (now: number): number => {
		let total = turnAccumMs;
		if (turnStart !== null) total += now - turnStart;
		return total;
	};

	const emit = () => {
		if (!sessionStart) return;
		const now = Date.now();
		const agent = getAgentMs(now);
		const turn = getTurnMs(now);
		const session = now - sessionStart;

		const sig = `${agent}|${turn}|${session}`;
		if (sig === lastSig) return;
		lastSig = sig;

		pi.events.emit("footer:segment", {
			id: "timing",
			text: `⏱ ${fmtMin(agent)} turn · ${fmtMin(session)} session`,
			color: "dim",
			zone: "llm",
			order: 10,
		});
	};

	const startPoll = () => {
		stopPoll();
		timer = setInterval(emit, POLL_MS);
	};

	const stopPoll = () => {
		if (timer) { clearInterval(timer); timer = null; }
	};

	const finalizeTurn = () => {
		if (turnStart !== null) {
			turnAccumMs += Date.now() - turnStart;
			turnStart = null;
		}
	};

	pi.on("session_start", async (_e, ctx) => {
		hasUI = ctx.hasUI;
		if (!hasUI) return;
		sessionStart = Date.now();
		agentStart = null;
		lastAgentMs = null;
		turnStart = null;
		turnAccumMs = 0;
		lastSig = "";
	});

	pi.on("agent_start", async () => {
		if (!hasUI) return;
		finalizeTurn();
		agentStart = Date.now();
		lastAgentMs = 0;
		turnAccumMs = 0;
		startPoll();
	});

	pi.on("turn_start", async () => {
		finalizeTurn();
		turnStart = Date.now();
	});

	pi.on("turn_end", async () => finalizeTurn());

	pi.on("agent_end", async () => {
		if (!hasUI) return;
		finalizeTurn();
		if (agentStart !== null) {
			lastAgentMs = Date.now() - agentStart;
			agentStart = null;
		}
		emit();
		stopPoll();
	});

	pi.on("session_shutdown", async () => {
		stopPoll();
		pi.events.emit("footer:segment", { id: "timing", text: undefined });
	});
}