import { CONFIG_DIR_NAME, type ExtensionAPI, type ExtensionCommandContext, } from "@earendil-works/pi-coding-agent"; import { homedir } from "node:os"; import { ConfigStore } from "./config"; import { createChiBaseModule } from "./identity"; import { ChiRegistry } from "./registry"; import { createChiSettingsUI } from "./settings-ui"; export interface ExtensionFactoryOptions { homeDir?: string; } export function createChiBaseExtension( pi: ExtensionAPI, options: ExtensionFactoryOptions = {}, ): void { let currentRegistry: ChiRegistry | undefined; pi.on("session_start", async (_event, ctx) => { const config = new ConfigStore({ homeDir: options.homeDir ?? homedir(), cwd: ctx.cwd, configDirName: CONFIG_DIR_NAME, projectTrusted: ctx.isProjectTrusted(), }); const registry = new ChiRegistry({ config }); currentRegistry = registry; registry.register(createChiBaseModule()); pi.events.emit("chi:discover", registry); await registry.initializeAll(); for (const id of registry.getDuplicateModuleIds()) { ctx.ui.notify( "Two identical Chi modules are active: " + id + ". Install the Chi bundle OR individual modules, never both — and a global" + " install may be clashing with a local one. Remove one of the installations" + " (pi list, then pi remove ).", "error", ); } }); pi.on("before_agent_start", async (event) => { const sections = currentRegistry?.renderPromptSections(); if (!sections) return; return { systemPrompt: event.systemPrompt + "\n\n" + sections }; }); pi.registerCommand("chi", { description: "View and edit Chi settings", handler: async (_args: string, ctx: ExtensionCommandContext) => { if (ctx.mode !== "tui") { ctx.ui.notify("/chi requires TUI mode", "error"); return; } const registry = currentRegistry; if (!registry) { ctx.ui.notify("Chi Base is not ready", "error"); return; } await ctx.ui.custom((tui, theme, _keybindings, done) => createChiSettingsUI({ registry, projectTrusted: ctx.isProjectTrusted(), theme: { bold: (value) => theme.bold(value) }, notify: (message, type) => ctx.ui.notify(message, type), requestRender: () => tui.requestRender(), done: () => done(undefined), }), ); }, }); } export default createChiBaseExtension;