index.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /**
  2. * Plan Mode Extension
  3. *
  4. * Read-only exploration mode for safe code analysis.
  5. * When enabled, only read-only tools are available.
  6. *
  7. * Features:
  8. * - /plan command or Ctrl+Alt+P to toggle
  9. * - Bash restricted to allowlisted read-only commands
  10. * - Extracts numbered plan steps from "Plan:" sections
  11. * - [DONE:n] markers to complete steps during execution
  12. * - Progress tracking widget during execution
  13. */
  14. import type { AgentMessage } from "@earendil-works/pi-agent-core";
  15. import type { AssistantMessage, TextContent } from "@earendil-works/pi-ai";
  16. import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
  17. import { Key } from "@earendil-works/pi-tui";
  18. import { extractTodoItems, isSafeCommand, markCompletedSteps, type TodoItem } from "./utils.ts";
  19. // Tools
  20. const PLAN_MODE_TOOLS = ["read", "bash", "grep", "find", "ls", "questionnaire"];
  21. const NORMAL_MODE_TOOLS = ["read", "bash", "edit", "write"];
  22. // Type guard for assistant messages
  23. function isAssistantMessage(m: AgentMessage): m is AssistantMessage {
  24. return m.role === "assistant" && Array.isArray(m.content);
  25. }
  26. // Extract text content from an assistant message
  27. function getTextContent(message: AssistantMessage): string {
  28. return message.content
  29. .filter((block): block is TextContent => block.type === "text")
  30. .map((block) => block.text)
  31. .join("\n");
  32. }
  33. export default function planModeExtension(pi: ExtensionAPI): void {
  34. let planModeEnabled = false;
  35. let executionMode = false;
  36. let todoItems: TodoItem[] = [];
  37. pi.registerFlag("plan", {
  38. description: "Start in plan mode (read-only exploration)",
  39. type: "boolean",
  40. default: false,
  41. });
  42. function updateStatus(ctx: ExtensionContext): void {
  43. // Footer status
  44. if (executionMode && todoItems.length > 0) {
  45. const completed = todoItems.filter((t) => t.completed).length;
  46. ctx.ui.setStatus("plan-mode", ctx.ui.theme.fg("accent", `📋 ${completed}/${todoItems.length}`));
  47. } else if (planModeEnabled) {
  48. ctx.ui.setStatus("plan-mode", ctx.ui.theme.fg("warning", "⏸ plan"));
  49. } else {
  50. ctx.ui.setStatus("plan-mode", undefined);
  51. }
  52. // Widget showing todo list
  53. if (executionMode && todoItems.length > 0) {
  54. const lines = todoItems.map((item) => {
  55. if (item.completed) {
  56. return (
  57. ctx.ui.theme.fg("success", "☑ ") + ctx.ui.theme.fg("muted", ctx.ui.theme.strikethrough(item.text))
  58. );
  59. }
  60. return `${ctx.ui.theme.fg("muted", "☐ ")}${item.text}`;
  61. });
  62. ctx.ui.setWidget("plan-todos", lines);
  63. } else {
  64. ctx.ui.setWidget("plan-todos", undefined);
  65. }
  66. }
  67. function togglePlanMode(ctx: ExtensionContext): void {
  68. planModeEnabled = !planModeEnabled;
  69. executionMode = false;
  70. todoItems = [];
  71. if (planModeEnabled) {
  72. pi.setActiveTools(PLAN_MODE_TOOLS);
  73. ctx.ui.notify(`Plan mode enabled. Tools: ${PLAN_MODE_TOOLS.join(", ")}`);
  74. } else {
  75. pi.setActiveTools(NORMAL_MODE_TOOLS);
  76. ctx.ui.notify("Plan mode disabled. Full access restored.");
  77. }
  78. updateStatus(ctx);
  79. }
  80. function persistState(): void {
  81. pi.appendEntry("plan-mode", {
  82. enabled: planModeEnabled,
  83. todos: todoItems,
  84. executing: executionMode,
  85. });
  86. }
  87. pi.registerCommand("plan", {
  88. description: "Toggle plan mode (read-only exploration)",
  89. handler: async (_args, ctx) => togglePlanMode(ctx),
  90. });
  91. pi.registerCommand("todos", {
  92. description: "Show current plan todo list",
  93. handler: async (_args, ctx) => {
  94. if (todoItems.length === 0) {
  95. ctx.ui.notify("No todos. Create a plan first with /plan", "info");
  96. return;
  97. }
  98. const list = todoItems.map((item, i) => `${i + 1}. ${item.completed ? "✓" : "○"} ${item.text}`).join("\n");
  99. ctx.ui.notify(`Plan Progress:\n${list}`, "info");
  100. },
  101. });
  102. pi.registerShortcut(Key.ctrlAlt("p"), {
  103. description: "Toggle plan mode",
  104. handler: async (ctx) => togglePlanMode(ctx),
  105. });
  106. // Block destructive bash commands in plan mode
  107. pi.on("tool_call", async (event) => {
  108. if (!planModeEnabled || event.toolName !== "bash") return;
  109. const command = event.input.command as string;
  110. if (!isSafeCommand(command)) {
  111. return {
  112. block: true,
  113. reason: `Plan mode: command blocked (not allowlisted). Use /plan to disable plan mode first.\nCommand: ${command}`,
  114. };
  115. }
  116. });
  117. // Filter out stale plan mode context when not in plan mode
  118. pi.on("context", async (event) => {
  119. if (planModeEnabled) return;
  120. return {
  121. messages: event.messages.filter((m) => {
  122. const msg = m as AgentMessage & { customType?: string };
  123. if (msg.customType === "plan-mode-context") return false;
  124. if (msg.role !== "user") return true;
  125. const content = msg.content;
  126. if (typeof content === "string") {
  127. return !content.includes("[PLAN MODE ACTIVE]");
  128. }
  129. if (Array.isArray(content)) {
  130. return !content.some(
  131. (c) => c.type === "text" && (c as TextContent).text?.includes("[PLAN MODE ACTIVE]"),
  132. );
  133. }
  134. return true;
  135. }),
  136. };
  137. });
  138. // Inject plan/execution context before agent starts
  139. pi.on("before_agent_start", async () => {
  140. if (planModeEnabled) {
  141. return {
  142. message: {
  143. customType: "plan-mode-context",
  144. content: `[PLAN MODE ACTIVE]
  145. You are in plan mode - a read-only exploration mode for safe code analysis.
  146. Restrictions:
  147. - You can only use: read, bash, grep, find, ls, questionnaire
  148. - You CANNOT use: edit, write (file modifications are disabled)
  149. - Bash is restricted to an allowlist of read-only commands
  150. Ask clarifying questions using the questionnaire tool.
  151. Use brave-search skill via bash for web research.
  152. Create a detailed numbered plan under a "Plan:" header:
  153. Plan:
  154. 1. First step description
  155. 2. Second step description
  156. ...
  157. Do NOT attempt to make changes - just describe what you would do.`,
  158. display: false,
  159. },
  160. };
  161. }
  162. if (executionMode && todoItems.length > 0) {
  163. const remaining = todoItems.filter((t) => !t.completed);
  164. const todoList = remaining.map((t) => `${t.step}. ${t.text}`).join("\n");
  165. return {
  166. message: {
  167. customType: "plan-execution-context",
  168. content: `[EXECUTING PLAN - Full tool access enabled]
  169. Remaining steps:
  170. ${todoList}
  171. Execute each step in order.
  172. After completing a step, include a [DONE:n] tag in your response.`,
  173. display: false,
  174. },
  175. };
  176. }
  177. });
  178. // Track progress after each turn
  179. pi.on("turn_end", async (event, ctx) => {
  180. if (!executionMode || todoItems.length === 0) return;
  181. if (!isAssistantMessage(event.message)) return;
  182. const text = getTextContent(event.message);
  183. if (markCompletedSteps(text, todoItems) > 0) {
  184. updateStatus(ctx);
  185. }
  186. persistState();
  187. });
  188. // Handle plan completion and plan mode UI
  189. pi.on("agent_end", async (event, ctx) => {
  190. // Check if execution is complete
  191. if (executionMode && todoItems.length > 0) {
  192. if (todoItems.every((t) => t.completed)) {
  193. const completedList = todoItems.map((t) => `~~${t.text}~~`).join("\n");
  194. pi.sendMessage(
  195. { customType: "plan-complete", content: `**Plan Complete!** ✓\n\n${completedList}`, display: true },
  196. { triggerTurn: false },
  197. );
  198. executionMode = false;
  199. todoItems = [];
  200. pi.setActiveTools(NORMAL_MODE_TOOLS);
  201. updateStatus(ctx);
  202. persistState(); // Save cleared state so resume doesn't restore old execution mode
  203. }
  204. return;
  205. }
  206. if (!planModeEnabled || !ctx.hasUI) return;
  207. // Extract todos from last assistant message
  208. const lastAssistant = [...event.messages].reverse().find(isAssistantMessage);
  209. if (lastAssistant) {
  210. const extracted = extractTodoItems(getTextContent(lastAssistant));
  211. if (extracted.length > 0) {
  212. todoItems = extracted;
  213. }
  214. }
  215. // Show plan steps and prompt for next action
  216. if (todoItems.length > 0) {
  217. const todoListText = todoItems.map((t, i) => `${i + 1}. ☐ ${t.text}`).join("\n");
  218. pi.sendMessage(
  219. {
  220. customType: "plan-todo-list",
  221. content: `**Plan Steps (${todoItems.length}):**\n\n${todoListText}`,
  222. display: true,
  223. },
  224. { triggerTurn: false },
  225. );
  226. }
  227. const choice = await ctx.ui.select("Plan mode - what next?", [
  228. todoItems.length > 0 ? "Execute the plan (track progress)" : "Execute the plan",
  229. "Stay in plan mode",
  230. "Refine the plan",
  231. ]);
  232. if (choice?.startsWith("Execute")) {
  233. planModeEnabled = false;
  234. executionMode = todoItems.length > 0;
  235. pi.setActiveTools(NORMAL_MODE_TOOLS);
  236. updateStatus(ctx);
  237. const execMessage =
  238. todoItems.length > 0
  239. ? `Execute the plan. Start with: ${todoItems[0].text}`
  240. : "Execute the plan you just created.";
  241. pi.sendMessage(
  242. { customType: "plan-mode-execute", content: execMessage, display: true },
  243. { triggerTurn: true },
  244. );
  245. } else if (choice === "Refine the plan") {
  246. const refinement = await ctx.ui.editor("Refine the plan:", "");
  247. if (refinement?.trim()) {
  248. pi.sendUserMessage(refinement.trim());
  249. }
  250. }
  251. });
  252. // Restore state on session start/resume
  253. pi.on("session_start", async (_event, ctx) => {
  254. if (pi.getFlag("plan") === true) {
  255. planModeEnabled = true;
  256. }
  257. const entries = ctx.sessionManager.getEntries();
  258. // Restore persisted state
  259. const planModeEntry = entries
  260. .filter((e: { type: string; customType?: string }) => e.type === "custom" && e.customType === "plan-mode")
  261. .pop() as { data?: { enabled: boolean; todos?: TodoItem[]; executing?: boolean } } | undefined;
  262. if (planModeEntry?.data) {
  263. planModeEnabled = planModeEntry.data.enabled ?? planModeEnabled;
  264. todoItems = planModeEntry.data.todos ?? todoItems;
  265. executionMode = planModeEntry.data.executing ?? executionMode;
  266. }
  267. // On resume: re-scan messages to rebuild completion state
  268. // Only scan messages AFTER the last "plan-mode-execute" to avoid picking up [DONE:n] from previous plans
  269. const isResume = planModeEntry !== undefined;
  270. if (isResume && executionMode && todoItems.length > 0) {
  271. // Find the index of the last plan-mode-execute entry (marks when current execution started)
  272. let executeIndex = -1;
  273. for (let i = entries.length - 1; i >= 0; i--) {
  274. const entry = entries[i] as { type: string; customType?: string };
  275. if (entry.customType === "plan-mode-execute") {
  276. executeIndex = i;
  277. break;
  278. }
  279. }
  280. // Only scan messages after the execute marker
  281. const messages: AssistantMessage[] = [];
  282. for (let i = executeIndex + 1; i < entries.length; i++) {
  283. const entry = entries[i];
  284. if (entry.type === "message" && "message" in entry && isAssistantMessage(entry.message as AgentMessage)) {
  285. messages.push(entry.message as AssistantMessage);
  286. }
  287. }
  288. const allText = messages.map(getTextContent).join("\n");
  289. markCompletedSteps(allText, todoItems);
  290. }
  291. if (planModeEnabled) {
  292. pi.setActiveTools(PLAN_MODE_TOOLS);
  293. }
  294. updateStatus(ctx);
  295. });
  296. }