repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/the-system/index.ts

Raw
File outline
import path from "node:path";
import {
	type ExtensionAPI,
	type ExtensionContext,
	isToolCallEventType,
} from "@earendil-works/pi-coding-agent";
import { createArtifactSlotTool } from "./artifact-slot-tool.js";
import { createBoardRuntime } from "./board-runtime.js";
import { createMockupRuntime } from "./mockup-tool.js";
import { systemArgumentCompletions } from "./system-command-meta.js";

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

export default function registerTheSystem(pi: ExtensionAPI): void {
	let generation = 0;
	let warningNotified = false;
	let artifactSlotRunActive = false;
	let artifactSlotUsed = false;
	let boardProposalRunActive = false;
	let bundleMigrationRunActive = false;
	const mockup = createMockupRuntime();
	const artifactSlot = createArtifactSlotTool(() => {
		artifactSlotUsed = true;
	});
	const board = createBoardRuntime();
	const activateArtifactSlot = () => {
		const active = pi.getActiveTools();
		if (!active.includes(artifactSlot.name))
			pi.setActiveTools([...active, artifactSlot.name]);
		artifactSlotRunActive = true;
		artifactSlotUsed = false;
	};
	const deactivateArtifactSlot = () => {
		const active = pi.getActiveTools();
		if (active.includes(artifactSlot.name))
			pi.setActiveTools(active.filter((name) => name !== artifactSlot.name));
		artifactSlotRunActive = false;
		artifactSlotUsed = false;
	};
	const activateBoardProposal = (cwd: string) => {
		board.beginProposal(cwd);
		const active = pi.getActiveTools();
		if (!active.includes(board.tool.name))
			pi.setActiveTools([...active, board.tool.name]);
		boardProposalRunActive = true;
	};
	const deactivateBoardProposal = () => {
		const active = pi.getActiveTools();
		if (active.includes(board.tool.name))
			pi.setActiveTools(active.filter((name) => name !== board.tool.name));
		board.endProposal();
		boardProposalRunActive = false;
	};
	const activateBundleMigration = () => {
		bundleMigrationRunActive = true;
	};
	const beginLifecycle = () => {
		if (artifactSlotRunActive) deactivateArtifactSlot();
		if (boardProposalRunActive) deactivateBoardProposal();
	};

	const syncRuntimeIndicator = async (
		ctx: ExtensionContext,
		ticket: number,
	) => {
		if (ticket !== generation) return;
		try {
			const { startupRuntimeState } = await import("./startup-notice.js");
			if (ticket !== generation) return;
			const runtime = await startupRuntimeState(ctx.cwd);
			if (ticket !== generation) return;
			if (ctx.hasUI) {
				ctx.ui.setStatus(
					"the-system",
					runtime.active
						? ctx.ui.theme.fg(
								"accent",
								` ${runtime.prefix ?? "?"}${runtime.phaseLabel ? ` · ${runtime.phaseLabel}` : ""}`,
							)
						: undefined,
				);
				if (runtime.notice && !warningNotified) {
					warningNotified = true;
					ctx.ui.notify(runtime.notice, "warning");
				}
			}
		} catch (error) {
			if (!isStaleContextError(error)) throw error;
		}
	};

	pi.on("resources_discover", async (event) => {
		const root = path.join(import.meta.dirname, "skills");
		const skillPaths = [path.join(root, "vertical-slices")];
		const { startupRuntimeState } = await import("./startup-notice.js");
		const runtime = await startupRuntimeState(event.cwd);
		if (runtime.active && !runtime.notice)
			skillPaths.push(
				...["the-system-gfm", "the-system-tex", "the-system-mermaid"].map(
					(name) => path.join(root, name),
				),
			);
		return { skillPaths };
	});
	pi.on("session_start", (_event, ctx) => {
		deactivateArtifactSlot();
		deactivateBoardProposal();
		bundleMigrationRunActive = false;
		const ticket = ++generation;
		warningNotified = false;
		mockup.remember(ctx);
		const timer = setTimeout(() => {
			if (ticket === generation)
				void syncRuntimeIndicator(ctx, ticket).catch((error) =>
					console.error("The System startup check failed:", error),
				);
		}, 0);
		timer.unref?.();
	});
	pi.on("session_shutdown", (_event, ctx) => {
		generation++;
		warningNotified = false;
		artifactSlotRunActive = false;
		artifactSlotUsed = false;
		boardProposalRunActive = false;
		bundleMigrationRunActive = false;
		board.shutdown();
		mockup.shutdown(ctx);
	});
	pi.on("before_agent_start", async (event, ctx) => {
		void syncRuntimeIndicator(ctx, generation).catch((error) =>
			console.error("The System startup check failed:", error),
		);
		mockup.agentWorking(ctx);
		const { composeSystemPrompt } = await import("./system.js");
		const systemPrompt = composeSystemPrompt(ctx.cwd, event.systemPrompt);
		const capsule = mockup.contextCapsule(ctx);
		return {
			systemPrompt: capsule
				? `${systemPrompt}\n\n<mockup-context>\n${capsule}\n</mockup-context>`
				: systemPrompt,
		};
	});
	pi.on("agent_settled", (_event, ctx) => {
		void syncRuntimeIndicator(ctx, generation).catch((error) =>
			console.error("The System status refresh failed:", error),
		);
		mockup.agentSettled(ctx);
		if (artifactSlotRunActive && artifactSlotUsed) deactivateArtifactSlot();
		if (boardProposalRunActive && board.proposalComplete())
			deactivateBoardProposal();
		bundleMigrationRunActive = false;
	});
	pi.on("tool_call", async (event, ctx) => {
		if (
			!isToolCallEventType("write", event) &&
			!isToolCallEventType("edit", event)
		)
			return;
		const { preflightFileMutation } = await import("./system.js");
		const ui = {
			hasUI: ctx.hasUI,
			select: (title: string, items: string[]) => ctx.ui.select(title, items),
		};
		const options = { bundleMigration: bundleMigrationRunActive };
		const result = isToolCallEventType("write", event)
			? await preflightFileMutation(ctx.cwd, "write", event.input, ui, options)
			: await preflightFileMutation(ctx.cwd, "edit", event.input, ui, options);
		return result ? { block: true, reason: result.reason } : undefined;
	});

	pi.registerTool(mockup.tool);
	pi.registerTool(artifactSlot);
	pi.registerTool(board.tool);
	pi.registerCommand("system", {
		description: "The System project governance",
		getArgumentCompletions: systemArgumentCompletions,
		handler: async (args, ctx) => {
			const { createSystemCommand } = await import("./system-command.js");
			await createSystemCommand(pi, {
				beginLifecycle,
				activateArtifactTool: activateArtifactSlot,
				activateBoardTool: activateBoardProposal,
				activateBundleMigration,
				openBoard: board.open,
			}).handler(args, ctx);
		},
	});
}