preset.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /**
  2. * Preset Extension
  3. *
  4. * Allows defining named presets that configure model, thinking level, tools,
  5. * and system prompt instructions. Presets are defined in JSON config files
  6. * and can be activated via CLI flag, /preset command, or Ctrl+Shift+U to cycle.
  7. *
  8. * Config files (merged, project takes precedence):
  9. * - ~/.pi/agent/presets.json (global)
  10. * - <cwd>/.pi/presets.json (project-local)
  11. *
  12. * Example presets.json:
  13. * ```json
  14. * {
  15. * "plan": {
  16. * "provider": "openai-codex",
  17. * "model": "gpt-5.2-codex",
  18. * "thinkingLevel": "high",
  19. * "tools": ["read", "grep", "find", "ls"],
  20. * "instructions": "You are in PLANNING MODE. Your job is to deeply understand the problem and create a detailed implementation plan.\n\nRules:\n- DO NOT make any changes. You cannot edit or write files.\n- Read files IN FULL (no offset/limit) to get complete context. Partial reads miss critical details.\n- Explore thoroughly: grep for related code, find similar patterns, understand the architecture.\n- Ask clarifying questions if requirements are ambiguous. Do not assume.\n- Identify risks, edge cases, and dependencies before proposing solutions.\n\nOutput:\n- Create a structured plan with numbered steps.\n- For each step: what to change, why, and potential risks.\n- List files that will be modified.\n- Note any tests that should be added or updated.\n\nWhen done, ask the user if they want you to:\n1. Write the plan to a markdown file (e.g., PLAN.md)\n2. Create a GitHub issue with the plan\n3. Proceed to implementation (they should switch to 'implement' preset)"
  21. * },
  22. * "implement": {
  23. * "provider": "anthropic",
  24. * "model": "claude-sonnet-4-5",
  25. * "thinkingLevel": "high",
  26. * "tools": ["read", "bash", "edit", "write"],
  27. * "instructions": "You are in IMPLEMENTATION MODE. Your job is to make focused, correct changes.\n\nRules:\n- Keep scope tight. Do exactly what was asked, no more.\n- Read files before editing to understand current state.\n- Make surgical edits. Prefer edit over write for existing files.\n- Explain your reasoning briefly before each change.\n- Run tests or type checks after changes if the project has them (npm test, npm run check, etc.).\n- If you encounter unexpected complexity, STOP and explain the issue rather than hacking around it.\n\nIf no plan exists:\n- Ask clarifying questions before starting.\n- Propose what you'll do and get confirmation for non-trivial changes.\n\nAfter completing changes:\n- Summarize what was done.\n- Note any follow-up work or tests that should be added."
  28. * }
  29. * }
  30. * ```
  31. *
  32. * Usage:
  33. * - `pi --preset plan` - start with plan preset
  34. * - `/preset` - show selector to switch presets mid-session
  35. * - `/preset implement` - switch to implement preset directly
  36. * - `Ctrl+Shift+U` - cycle through presets
  37. *
  38. * CLI flags always override preset values.
  39. */
  40. import { existsSync, readFileSync } from "node:fs";
  41. import { join } from "node:path";
  42. import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
  43. import type { Api, Model } from "@earendil-works/pi-ai";
  44. import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
  45. import { DynamicBorder, getAgentDir } from "@earendil-works/pi-coding-agent";
  46. import { Container, Key, type SelectItem, SelectList, Text } from "@earendil-works/pi-tui";
  47. // Preset configuration
  48. interface Preset {
  49. /** Provider name (e.g., "anthropic", "openai") */
  50. provider?: string;
  51. /** Model ID (e.g., "claude-sonnet-4-5") */
  52. model?: string;
  53. /** Thinking level */
  54. thinkingLevel?: ThinkingLevel;
  55. /** Tools to enable (replaces default set) */
  56. tools?: string[];
  57. /** Instructions to append to system prompt */
  58. instructions?: string;
  59. }
  60. interface PresetsConfig {
  61. [name: string]: Preset;
  62. }
  63. /**
  64. * Load presets from config files.
  65. * Project-local presets override global presets with the same name.
  66. */
  67. function loadPresets(cwd: string): PresetsConfig {
  68. const globalPath = join(getAgentDir(), "presets.json");
  69. const projectPath = join(cwd, ".pi", "presets.json");
  70. let globalPresets: PresetsConfig = {};
  71. let projectPresets: PresetsConfig = {};
  72. // Load global presets
  73. if (existsSync(globalPath)) {
  74. try {
  75. const content = readFileSync(globalPath, "utf-8");
  76. globalPresets = JSON.parse(content);
  77. } catch (err) {
  78. console.error(`Failed to load global presets from ${globalPath}: ${err}`);
  79. }
  80. }
  81. // Load project presets
  82. if (existsSync(projectPath)) {
  83. try {
  84. const content = readFileSync(projectPath, "utf-8");
  85. projectPresets = JSON.parse(content);
  86. } catch (err) {
  87. console.error(`Failed to load project presets from ${projectPath}: ${err}`);
  88. }
  89. }
  90. // Merge (project overrides global)
  91. return { ...globalPresets, ...projectPresets };
  92. }
  93. interface OriginalState {
  94. model: Model<Api> | undefined;
  95. thinkingLevel: ThinkingLevel;
  96. tools: string[];
  97. }
  98. export default function presetExtension(pi: ExtensionAPI) {
  99. let presets: PresetsConfig = {};
  100. let activePresetName: string | undefined;
  101. let activePreset: Preset | undefined;
  102. let originalState: OriginalState | undefined;
  103. // Register --preset CLI flag
  104. pi.registerFlag("preset", {
  105. description: "Preset configuration to use",
  106. type: "string",
  107. });
  108. /**
  109. * Apply a preset configuration.
  110. */
  111. async function applyPreset(name: string, preset: Preset, ctx: ExtensionContext): Promise<boolean> {
  112. // Snapshot state before the first preset is applied (i.e. only when transitioning from no-preset)
  113. if (activePresetName === undefined) {
  114. originalState = {
  115. model: ctx.model,
  116. thinkingLevel: pi.getThinkingLevel(),
  117. tools: pi.getActiveTools(),
  118. };
  119. }
  120. // Apply model if specified
  121. if (preset.provider && preset.model) {
  122. const model = ctx.modelRegistry.find(preset.provider, preset.model);
  123. if (model) {
  124. const success = await pi.setModel(model);
  125. if (!success) {
  126. ctx.ui.notify(`Preset "${name}": No API key for ${preset.provider}/${preset.model}`, "warning");
  127. }
  128. } else {
  129. ctx.ui.notify(`Preset "${name}": Model ${preset.provider}/${preset.model} not found`, "warning");
  130. }
  131. }
  132. // Apply thinking level if specified
  133. if (preset.thinkingLevel) {
  134. pi.setThinkingLevel(preset.thinkingLevel);
  135. }
  136. // Apply tools if specified
  137. if (preset.tools && preset.tools.length > 0) {
  138. const allToolNames = pi.getAllTools().map((t) => t.name);
  139. const validTools = preset.tools.filter((t) => allToolNames.includes(t));
  140. const invalidTools = preset.tools.filter((t) => !allToolNames.includes(t));
  141. if (invalidTools.length > 0) {
  142. ctx.ui.notify(`Preset "${name}": Unknown tools: ${invalidTools.join(", ")}`, "warning");
  143. }
  144. if (validTools.length > 0) {
  145. pi.setActiveTools(validTools);
  146. }
  147. }
  148. // Store active preset for system prompt injection
  149. activePresetName = name;
  150. activePreset = preset;
  151. return true;
  152. }
  153. /**
  154. * Build description string for a preset.
  155. */
  156. function buildPresetDescription(preset: Preset): string {
  157. const parts: string[] = [];
  158. if (preset.provider && preset.model) {
  159. parts.push(`${preset.provider}/${preset.model}`);
  160. }
  161. if (preset.thinkingLevel) {
  162. parts.push(`thinking:${preset.thinkingLevel}`);
  163. }
  164. if (preset.tools) {
  165. parts.push(`tools:${preset.tools.join(",")}`);
  166. }
  167. if (preset.instructions) {
  168. const truncated =
  169. preset.instructions.length > 30 ? `${preset.instructions.slice(0, 27)}...` : preset.instructions;
  170. parts.push(`"${truncated}"`);
  171. }
  172. return parts.join(" | ");
  173. }
  174. /**
  175. * Show preset selector UI using custom SelectList component.
  176. */
  177. async function showPresetSelector(ctx: ExtensionContext): Promise<void> {
  178. const presetNames = Object.keys(presets);
  179. if (presetNames.length === 0) {
  180. ctx.ui.notify("No presets defined. Add presets to ~/.pi/agent/presets.json or .pi/presets.json", "warning");
  181. return;
  182. }
  183. // Build select items with descriptions
  184. const items: SelectItem[] = presetNames.map((name) => {
  185. const preset = presets[name];
  186. const isActive = name === activePresetName;
  187. return {
  188. value: name,
  189. label: isActive ? `${name} (active)` : name,
  190. description: buildPresetDescription(preset),
  191. };
  192. });
  193. // Add "None" option to clear preset
  194. items.push({
  195. value: "(none)",
  196. label: "(none)",
  197. description: "Clear active preset, restore defaults",
  198. });
  199. const result = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => {
  200. const container = new Container();
  201. container.addChild(new DynamicBorder((str) => theme.fg("accent", str)));
  202. // Header
  203. container.addChild(new Text(theme.fg("accent", theme.bold("Select Preset"))));
  204. // SelectList with themed styling
  205. const selectList = new SelectList(items, Math.min(items.length, 10), {
  206. selectedPrefix: (text) => theme.fg("accent", text),
  207. selectedText: (text) => theme.fg("accent", text),
  208. description: (text) => theme.fg("muted", text),
  209. scrollInfo: (text) => theme.fg("dim", text),
  210. noMatch: (text) => theme.fg("warning", text),
  211. });
  212. selectList.onSelect = (item) => done(item.value);
  213. selectList.onCancel = () => done(null);
  214. container.addChild(selectList);
  215. // Footer hint
  216. container.addChild(new Text(theme.fg("dim", "↑↓ navigate • enter select • esc cancel")));
  217. container.addChild(new DynamicBorder((str) => theme.fg("accent", str)));
  218. return {
  219. render(width: number) {
  220. return container.render(width);
  221. },
  222. invalidate() {
  223. container.invalidate();
  224. },
  225. handleInput(data: string) {
  226. selectList.handleInput(data);
  227. tui.requestRender();
  228. },
  229. };
  230. });
  231. if (!result) return;
  232. if (result === "(none)") {
  233. // Clear preset and restore original state
  234. activePresetName = undefined;
  235. activePreset = undefined;
  236. if (originalState) {
  237. if (originalState.model) {
  238. await pi.setModel(originalState.model);
  239. }
  240. pi.setThinkingLevel(originalState.thinkingLevel);
  241. pi.setActiveTools(originalState.tools);
  242. } else {
  243. pi.setActiveTools(["read", "bash", "edit", "write"]);
  244. }
  245. ctx.ui.notify("Preset cleared, defaults restored", "info");
  246. updateStatus(ctx);
  247. return;
  248. }
  249. const preset = presets[result];
  250. if (preset) {
  251. await applyPreset(result, preset, ctx);
  252. ctx.ui.notify(`Preset "${result}" activated`, "info");
  253. updateStatus(ctx);
  254. }
  255. }
  256. /**
  257. * Update status indicator.
  258. */
  259. function updateStatus(ctx: ExtensionContext) {
  260. if (activePresetName) {
  261. ctx.ui.setStatus("preset", ctx.ui.theme.fg("accent", `preset:${activePresetName}`));
  262. } else {
  263. ctx.ui.setStatus("preset", undefined);
  264. }
  265. }
  266. function getPresetOrder(): string[] {
  267. return Object.keys(presets).sort();
  268. }
  269. async function cyclePreset(ctx: ExtensionContext): Promise<void> {
  270. const presetNames = getPresetOrder();
  271. if (presetNames.length === 0) {
  272. ctx.ui.notify("No presets defined. Add presets to ~/.pi/agent/presets.json or .pi/presets.json", "warning");
  273. return;
  274. }
  275. const cycleList = ["(none)", ...presetNames];
  276. const currentName = activePresetName ?? "(none)";
  277. const currentIndex = cycleList.indexOf(currentName);
  278. const nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % cycleList.length;
  279. const nextName = cycleList[nextIndex];
  280. if (nextName === "(none)") {
  281. activePresetName = undefined;
  282. activePreset = undefined;
  283. if (originalState) {
  284. if (originalState.model) {
  285. await pi.setModel(originalState.model);
  286. }
  287. pi.setThinkingLevel(originalState.thinkingLevel);
  288. pi.setActiveTools(originalState.tools);
  289. } else {
  290. pi.setActiveTools(["read", "bash", "edit", "write"]);
  291. }
  292. ctx.ui.notify("Preset cleared, defaults restored", "info");
  293. updateStatus(ctx);
  294. return;
  295. }
  296. const preset = presets[nextName];
  297. if (!preset) return;
  298. await applyPreset(nextName, preset, ctx);
  299. ctx.ui.notify(`Preset "${nextName}" activated`, "info");
  300. updateStatus(ctx);
  301. }
  302. pi.registerShortcut(Key.ctrlShift("u"), {
  303. description: "Cycle presets",
  304. handler: async (ctx) => {
  305. await cyclePreset(ctx);
  306. },
  307. });
  308. // Register /preset command
  309. pi.registerCommand("preset", {
  310. description: "Switch preset configuration",
  311. handler: async (args, ctx) => {
  312. // If preset name provided, apply directly
  313. if (args?.trim()) {
  314. const name = args.trim();
  315. const preset = presets[name];
  316. if (!preset) {
  317. const available = Object.keys(presets).join(", ") || "(none defined)";
  318. ctx.ui.notify(`Unknown preset "${name}". Available: ${available}`, "error");
  319. return;
  320. }
  321. await applyPreset(name, preset, ctx);
  322. ctx.ui.notify(`Preset "${name}" activated`, "info");
  323. updateStatus(ctx);
  324. return;
  325. }
  326. // Otherwise show selector
  327. await showPresetSelector(ctx);
  328. },
  329. });
  330. // Inject preset instructions into system prompt
  331. pi.on("before_agent_start", async (event) => {
  332. if (activePreset?.instructions) {
  333. return {
  334. systemPrompt: `${event.systemPrompt}\n\n${activePreset.instructions}`,
  335. };
  336. }
  337. });
  338. // Initialize on session start
  339. pi.on("session_start", async (_event, ctx) => {
  340. // Load presets from config files
  341. presets = loadPresets(ctx.cwd);
  342. // Check for --preset flag
  343. const presetFlag = pi.getFlag("preset");
  344. if (typeof presetFlag === "string" && presetFlag) {
  345. const preset = presets[presetFlag];
  346. if (preset) {
  347. await applyPreset(presetFlag, preset, ctx);
  348. ctx.ui.notify(`Preset "${presetFlag}" activated`, "info");
  349. } else {
  350. const available = Object.keys(presets).join(", ") || "(none defined)";
  351. ctx.ui.notify(`Unknown preset "${presetFlag}". Available: ${available}`, "warning");
  352. }
  353. }
  354. // Restore preset from session state
  355. const entries = ctx.sessionManager.getEntries();
  356. const presetEntry = entries
  357. .filter((e: { type: string; customType?: string }) => e.type === "custom" && e.customType === "preset-state")
  358. .pop() as { data?: { name: string } } | undefined;
  359. if (presetEntry?.data?.name && !presetFlag) {
  360. const preset = presets[presetEntry.data.name];
  361. if (preset) {
  362. activePresetName = presetEntry.data.name;
  363. activePreset = preset;
  364. // Don't re-apply model/tools on restore, just keep the name for instructions
  365. }
  366. }
  367. updateStatus(ctx);
  368. });
  369. // Persist preset state
  370. pi.on("turn_start", async () => {
  371. if (activePresetName) {
  372. pi.appendEntry("preset-state", { name: activePresetName });
  373. }
  374. });
  375. }