repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/fast/index.ts

Raw
File outline
import {
	type Api,
	type Context,
	clampThinkingLevel,
	type Model,
	type SimpleStreamOptions,
} from "@earendil-works/pi-ai";
import {
	streamOpenAICodexResponses,
	streamSimpleOpenAICodexResponses,
} from "@earendil-works/pi-ai/compat";
import type {
	ExtensionAPI,
	ExtensionContext,
	ThemeColor,
} from "@earendil-works/pi-coding-agent";
import { SettingsManager } from "@earendil-works/pi-coding-agent";

const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
const PROVIDER = "openai-codex";
const API = "openai-codex-responses";
const SETTINGS_KEY = "fast";
const STATUS_ID = "fast";
const SEGMENT_ID = "fast";

type FastSettings = { enable?: boolean };
type FooterGlobal = typeof globalThis & {
	[FOOTER_KEY]?: { loaded?: boolean; version?: number };
};

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

function parseFastSettings(value: unknown): FastSettings {
	if (!isRecord(value)) return {};
	return typeof value.enable === "boolean" ? { enable: value.enable } : {};
}

function readEnabled(cwd: string): boolean {
	const settings = SettingsManager.create(cwd);
	const globalFast = parseFastSettings(
		(settings.getGlobalSettings() as Record<string, unknown>)[SETTINGS_KEY],
	);
	const projectFast = parseFastSettings(
		(settings.getProjectSettings() as Record<string, unknown>)[SETTINGS_KEY],
	);
	return projectFast.enable ?? globalFast.enable ?? false;
}

function isStaleContextError(error: unknown): boolean {
	return (
		error instanceof Error &&
		error.message.includes("ctx is stale after session replacement or reload")
	);
}

function hasFooter(): boolean {
	const footer = (globalThis as FooterGlobal)[FOOTER_KEY];
	return footer?.loaded === true && (footer.version ?? 0) >= 1;
}

function fastActive(
	ctx: Pick<ExtensionContext, "model">,
	enabled: boolean,
): boolean {
	return enabled && ctx.model?.provider === PROVIDER;
}

export default function fast(pi: ExtensionAPI): void {
	let currentCwd = process.cwd();
	let enabled: boolean | undefined;
	let generation = 0;

	function ensureEnabled(): boolean {
		if (enabled === undefined) enabled = readEnabled(currentCwd);
		return enabled;
	}

	function clear(ctx?: ExtensionContext): void {
		pi.events.emit("footer:segment", { id: SEGMENT_ID, text: undefined });
		if (ctx?.hasUI) ctx.ui.setStatus(STATUS_ID, undefined);
	}

	function publish(ctx: ExtensionContext): void {
		if (!ctx.hasUI) return;
		if (!fastActive(ctx, enabled ?? false)) {
			clear(ctx);
			return;
		}

		if (hasFooter()) {
			ctx.ui.setStatus(STATUS_ID, undefined);
			pi.events.emit("footer:segment", {
				id: SEGMENT_ID,
				text: "fast",
				color: "warning" as ThemeColor,
				zone: "llm",
				order: 0.5,
			});
			return;
		}

		pi.events.emit("footer:segment", { id: SEGMENT_ID, text: undefined });
		ctx.ui.setStatus(STATUS_ID, "fast");
	}

	pi.registerProvider(PROVIDER, {
		api: API,
		streamSimple(
			model: Model<Api>,
			context: Context,
			options?: SimpleStreamOptions,
		) {
			if (!ensureEnabled())
				return streamSimpleOpenAICodexResponses(
					model as Model<typeof API>,
					context,
					options,
				);

			const clampedReasoning = options?.reasoning
				? clampThinkingLevel(model, options.reasoning)
				: undefined;
			const reasoningEffort =
				clampedReasoning === "off" ? undefined : clampedReasoning;

			return streamOpenAICodexResponses(model as Model<typeof API>, context, {
				...options,
				reasoningEffort,
				serviceTier: "priority",
			});
		},
	});

	function scheduleRefresh(ctx: ExtensionContext): void {
		const ticket = ++generation;
		currentCwd = ctx.cwd;
		enabled = undefined;
		const timer = setTimeout(() => {
			if (ticket !== generation) return;
			ensureEnabled();
			try {
				publish(ctx);
			} catch (error) {
				if (!isStaleContextError(error)) throw error;
			}
		}, 0);
		timer.unref?.();
	}

	pi.on("session_start", (_event, ctx) => scheduleRefresh(ctx));
	pi.on("model_select", (_event, ctx) => scheduleRefresh(ctx));
	pi.on("session_shutdown", (_event, ctx) => {
		generation++;
		enabled = undefined;
		clear(ctx);
	});
}

export const _test = { fastActive, parseFastSettings };