xtrm-tools 0.5.26 → 0.5.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,417 +0,0 @@
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
-
15
- import type { AgentMessage } from "@mariozechner/pi-agent-core";
16
- import type { AssistantMessage, TextContent } from "@mariozechner/pi-ai";
17
- import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
18
- import { Key } from "@mariozechner/pi-tui";
19
- import {
20
- extractTodoItems,
21
- isSafeCommand,
22
- markCompletedSteps,
23
- type TodoItem,
24
- getShortId,
25
- isBeadsProject,
26
- deriveEpicTitle,
27
- createPlanIssues,
28
- bdClaim,
29
- } from "./utils.js";
30
-
31
- // Tools
32
- const PLAN_MODE_TOOLS = ["read", "bash", "grep", "find", "ls", "questionnaire"];
33
- const NORMAL_MODE_TOOLS = ["read", "bash", "edit", "write"];
34
-
35
- // Type guard for assistant messages
36
- function isAssistantMessage(m: AgentMessage): m is AssistantMessage {
37
- return m.role === "assistant" && Array.isArray(m.content);
38
- }
39
-
40
- // Extract text content from an assistant message
41
- function getTextContent(message: AssistantMessage): string {
42
- return message.content
43
- .filter((block): block is TextContent => block.type === "text")
44
- .map((block) => block.text)
45
- .join("\n");
46
- }
47
-
48
- export default function planModeExtension(pi: ExtensionAPI): void {
49
- let planModeEnabled = false;
50
- let executionMode = false;
51
- let todoItems: TodoItem[] = [];
52
- let epicId: string | null = null;
53
- let issueIds: Map<number, string> = new Map(); // step -> issue ID
54
-
55
- pi.registerFlag("plan", {
56
- description: "Start in plan mode (read-only exploration)",
57
- type: "boolean",
58
- default: false,
59
- });
60
-
61
- function updateStatus(ctx: ExtensionContext): void {
62
- // Footer status
63
- if (executionMode && todoItems.length > 0) {
64
- const completed = todoItems.filter((t) => t.completed).length;
65
- ctx.ui.setStatus("plan-mode", ctx.ui.theme.fg("accent", `📋 ${completed}/${todoItems.length}`));
66
- } else if (planModeEnabled) {
67
- ctx.ui.setStatus("plan-mode", ctx.ui.theme.fg("warning", "⏸ plan"));
68
- } else {
69
- ctx.ui.setStatus("plan-mode", undefined);
70
- }
71
-
72
- // Widget showing todo list with bd issue IDs
73
- if (executionMode && todoItems.length > 0) {
74
- const lines = todoItems.map((item) => {
75
- const issueId = issueIds.get(item.step);
76
- const idLabel = issueId ? `[${getShortId(issueId)}] ` : "";
77
- if (item.completed) {
78
- return (
79
- ctx.ui.theme.fg("success", "☑ ") + ctx.ui.theme.fg("muted", ctx.ui.theme.strikethrough(`${idLabel}${item.text}`))
80
- );
81
- }
82
- return `${ctx.ui.theme.fg("muted", "☐ ")}${idLabel}${item.text}`;
83
- });
84
- ctx.ui.setWidget("plan-todos", lines);
85
- } else {
86
- ctx.ui.setWidget("plan-todos", undefined);
87
- }
88
- }
89
-
90
- function togglePlanMode(ctx: ExtensionContext): void {
91
- planModeEnabled = !planModeEnabled;
92
- executionMode = false;
93
- todoItems = [];
94
- epicId = null;
95
- issueIds.clear();
96
-
97
- if (planModeEnabled) {
98
- pi.setActiveTools(PLAN_MODE_TOOLS);
99
- ctx.ui.notify(`Plan mode enabled. Tools: ${PLAN_MODE_TOOLS.join(", ")}`);
100
- } else {
101
- pi.setActiveTools(NORMAL_MODE_TOOLS);
102
- ctx.ui.notify("Plan mode disabled. Full access restored.");
103
- }
104
- updateStatus(ctx);
105
- }
106
-
107
- function persistState(): void {
108
- pi.appendEntry("plan-mode", {
109
- enabled: planModeEnabled,
110
- todos: todoItems,
111
- executing: executionMode,
112
- epicId,
113
- issueIds: Object.fromEntries(issueIds),
114
- });
115
- }
116
-
117
- pi.registerCommand("plan", {
118
- description: "Toggle plan mode (read-only exploration)",
119
- handler: async (_args, ctx) => togglePlanMode(ctx),
120
- });
121
-
122
- pi.registerCommand("todos", {
123
- description: "Show current plan todo list",
124
- handler: async (_args, ctx) => {
125
- if (todoItems.length === 0) {
126
- ctx.ui.notify("No todos. Create a plan first with /plan", "info");
127
- return;
128
- }
129
- const list = todoItems.map((item, i) => {
130
- const issueId = issueIds.get(item.step);
131
- const idLabel = issueId ? `[${getShortId(issueId)}] ` : "";
132
- return `${i + 1}. ${item.completed ? "✓" : "○"} ${idLabel}${item.text}`;
133
- }).join("\n");
134
- ctx.ui.notify(`Plan Progress:\n${list}`, "info");
135
- },
136
- });
137
-
138
- pi.registerShortcut(Key.ctrlAlt("p"), {
139
- description: "Toggle plan mode",
140
- handler: async (ctx) => togglePlanMode(ctx),
141
- });
142
-
143
- // Block destructive bash commands in plan mode
144
- pi.on("tool_call", async (event) => {
145
- if (!planModeEnabled || event.toolName !== "bash") return;
146
-
147
- const command = event.input.command as string;
148
- if (!isSafeCommand(command)) {
149
- return {
150
- block: true,
151
- reason: `Plan mode: command blocked (not allowlisted). Use /plan to disable plan mode first.\nCommand: ${command}`,
152
- };
153
- }
154
- });
155
-
156
- // Filter out stale plan mode context when not in plan mode
157
- pi.on("context", async (event) => {
158
- if (planModeEnabled) return;
159
-
160
- return {
161
- messages: event.messages.filter((m) => {
162
- const msg = m as AgentMessage & { customType?: string };
163
- if (msg.customType === "plan-mode-context") return false;
164
- if (msg.role !== "user") return true;
165
-
166
- const content = msg.content;
167
- if (typeof content === "string") {
168
- return !content.includes("[PLAN MODE ACTIVE]");
169
- }
170
- if (Array.isArray(content)) {
171
- return !content.some(
172
- (c) => c.type === "text" && (c as TextContent).text?.includes("[PLAN MODE ACTIVE]"),
173
- );
174
- }
175
- return true;
176
- }),
177
- };
178
- });
179
-
180
- // Inject plan/execution context before agent starts
181
- pi.on("before_agent_start", async () => {
182
- if (planModeEnabled) {
183
- return {
184
- message: {
185
- customType: "plan-mode-context",
186
- content: `[PLAN MODE ACTIVE]
187
- You are in plan mode - a read-only exploration mode for safe code analysis.
188
-
189
- Restrictions:
190
- - You can only use: read, bash, grep, find, ls, questionnaire
191
- - You CANNOT use: edit, write (file modifications are disabled)
192
- - Bash is restricted to an allowlist of read-only commands
193
-
194
- Ask clarifying questions using the questionnaire tool.
195
- Use brave-search skill via bash for web research.
196
-
197
- Create a detailed numbered plan under a "Plan:" header:
198
-
199
- Plan:
200
- 1. First step description
201
- 2. Second step description
202
- ...
203
-
204
- Do NOT attempt to make changes - just describe what you would do.`,
205
- display: false,
206
- },
207
- };
208
- }
209
-
210
- if (executionMode && todoItems.length > 0) {
211
- const remaining = todoItems.filter((t) => !t.completed);
212
- const todoList = remaining.map((t) => {
213
- const issueId = issueIds.get(t.step);
214
- const idLabel = issueId ? `[${getShortId(issueId)}] ` : "";
215
- return `${t.step}. ${idLabel}${t.text}`;
216
- }).join("\n");
217
- return {
218
- message: {
219
- customType: "plan-execution-context",
220
- content: `[EXECUTING PLAN - Full tool access enabled]
221
-
222
- Remaining steps:
223
- ${todoList}
224
-
225
- Execute each step in order.
226
- After completing a step, include a [DONE:n] tag in your response.`,
227
- display: false,
228
- },
229
- };
230
- }
231
- });
232
-
233
- // Track progress after each turn
234
- pi.on("turn_end", async (event, ctx) => {
235
- if (!executionMode || todoItems.length === 0) return;
236
- if (!isAssistantMessage(event.message)) return;
237
-
238
- const text = getTextContent(event.message);
239
- if (markCompletedSteps(text, todoItems) > 0) {
240
- updateStatus(ctx);
241
- }
242
- persistState();
243
- });
244
-
245
- // Handle plan completion and plan mode UI
246
- pi.on("agent_end", async (event, ctx) => {
247
- // Check if execution is complete
248
- if (executionMode && todoItems.length > 0) {
249
- if (todoItems.every((t) => t.completed)) {
250
- const completedList = todoItems.map((t) => {
251
- const issueId = issueIds.get(t.step);
252
- const idLabel = issueId ? `[${getShortId(issueId)}] ` : "";
253
- return `~~${idLabel}${t.text}~~`;
254
- }).join("\n");
255
- pi.sendMessage(
256
- { customType: "plan-complete", content: `**Plan Complete!** ✓\n\n${completedList}`, display: true },
257
- { triggerTurn: false },
258
- );
259
- executionMode = false;
260
- todoItems = [];
261
- epicId = null;
262
- issueIds.clear();
263
- pi.setActiveTools(NORMAL_MODE_TOOLS);
264
- updateStatus(ctx);
265
- persistState(); // Save cleared state so resume doesn't restore old execution mode
266
- }
267
- return;
268
- }
269
-
270
- if (!planModeEnabled || !ctx.hasUI) return;
271
-
272
- // Extract todos from last assistant message
273
- const lastAssistant = [...event.messages].reverse().find(isAssistantMessage);
274
- if (lastAssistant) {
275
- const extracted = extractTodoItems(getTextContent(lastAssistant));
276
- if (extracted.length > 0) {
277
- todoItems = extracted;
278
- }
279
- }
280
-
281
- // Auto-create epic + issues if in a beads project
282
- const cwd = ctx.cwd || process.cwd();
283
- if (todoItems.length > 0 && isBeadsProject(cwd) && !epicId) {
284
- // Derive epic title from user prompt or first step
285
- const epicTitle = deriveEpicTitle(event.messages);
286
-
287
- ctx.ui.notify("Creating epic and issues in bd...", "info");
288
- const result = await createPlanIssues(epicTitle, todoItems, cwd);
289
-
290
- if (result) {
291
- epicId = result.epic.id;
292
- for (const issue of result.issues) {
293
- // Match issue to todo by title similarity
294
- const matchingTodo = todoItems.find(t =>
295
- issue.title.toLowerCase().includes(t.text.toLowerCase().slice(0, 30)) ||
296
- t.text.toLowerCase().includes(issue.title.toLowerCase().slice(0, 30))
297
- );
298
- if (matchingTodo) {
299
- issueIds.set(matchingTodo.step, issue.id);
300
- }
301
- }
302
- ctx.ui.notify(`Created epic ${getShortId(epicId)} with ${result.issues.length} issues`, "info");
303
- }
304
- }
305
-
306
- // Show plan steps with bd issue IDs
307
- if (todoItems.length > 0) {
308
- const todoListText = todoItems.map((t, i) => {
309
- const issueId = issueIds.get(t.step);
310
- const idLabel = issueId ? `[${getShortId(issueId)}] ` : "";
311
- return `${i + 1}. ☐ ${idLabel}${t.text}`;
312
- }).join("\n");
313
-
314
- const epicLabel = epicId ? `\n\nEpic: ${getShortId(epicId)}` : "";
315
- pi.sendMessage(
316
- {
317
- customType: "plan-todo-list",
318
- content: `**Plan Steps (${todoItems.length}):**${epicLabel}\n\n${todoListText}`,
319
- display: true,
320
- },
321
- { triggerTurn: false },
322
- );
323
- }
324
-
325
- // Show "Start implementation?" prompt (no approval dialog for issue creation)
326
- const choice = await ctx.ui.select("Start implementation?", [
327
- todoItems.length > 0 ? "Yes, start with first step" : "Yes",
328
- "Stay in plan mode",
329
- "Refine the plan",
330
- ]);
331
-
332
- if (choice?.startsWith("Yes")) {
333
- // Auto-exit plan mode and start execution
334
- planModeEnabled = false;
335
- executionMode = todoItems.length > 0;
336
- pi.setActiveTools(NORMAL_MODE_TOOLS);
337
- updateStatus(ctx);
338
-
339
- // Auto-claim first issue if available
340
- if (todoItems.length > 0 && issueIds.size > 0) {
341
- const firstIssueId = issueIds.get(todoItems[0].step);
342
- if (firstIssueId) {
343
- await bdClaim(firstIssueId, cwd);
344
- }
345
- }
346
-
347
- const execMessage =
348
- todoItems.length > 0
349
- ? `Execute the plan. Start with: ${todoItems[0].text}`
350
- : "Execute the plan you just created.";
351
- pi.sendMessage(
352
- { customType: "plan-mode-execute", content: execMessage, display: true },
353
- { triggerTurn: true },
354
- );
355
- } else if (choice === "Refine the plan") {
356
- const refinement = await ctx.ui.editor("Refine the plan:", "");
357
- if (refinement?.trim()) {
358
- pi.sendUserMessage(refinement.trim());
359
- }
360
- }
361
- });
362
-
363
- // Restore state on session start/resume
364
- pi.on("session_start", async (_event, ctx) => {
365
- if (pi.getFlag("plan") === true) {
366
- planModeEnabled = true;
367
- }
368
-
369
- const entries = ctx.sessionManager.getEntries();
370
-
371
- // Restore persisted state
372
- const planModeEntry = entries
373
- .filter((e: { type: string; customType?: string }) => e.type === "custom" && e.customType === "plan-mode")
374
- .pop() as { data?: { enabled: boolean; todos?: TodoItem[]; executing?: boolean; epicId?: string; issueIds?: Record<number, string> } } | undefined;
375
-
376
- if (planModeEntry?.data) {
377
- planModeEnabled = planModeEntry.data.enabled ?? planModeEnabled;
378
- todoItems = planModeEntry.data.todos ?? todoItems;
379
- executionMode = planModeEntry.data.executing ?? executionMode;
380
- epicId = planModeEntry.data.epicId ?? null;
381
- if (planModeEntry.data.issueIds) {
382
- issueIds = new Map(Object.entries(planModeEntry.data.issueIds).map(([k, v]) => [Number(k), v]));
383
- }
384
- }
385
-
386
- // On resume: re-scan messages to rebuild completion state
387
- // Only scan messages AFTER the last "plan-mode-execute" to avoid picking up [DONE:n] from previous plans
388
- const isResume = planModeEntry !== undefined;
389
- if (isResume && executionMode && todoItems.length > 0) {
390
- // Find the index of the last plan-mode-execute entry (marks when current execution started)
391
- let executeIndex = -1;
392
- for (let i = entries.length - 1; i >= 0; i--) {
393
- const entry = entries[i] as { type: string; customType?: string };
394
- if (entry.customType === "plan-mode-execute") {
395
- executeIndex = i;
396
- break;
397
- }
398
- }
399
-
400
- // Only scan messages after the execute marker
401
- const messages: AssistantMessage[] = [];
402
- for (let i = executeIndex + 1; i < entries.length; i++) {
403
- const entry = entries[i];
404
- if (entry.type === "message" && "message" in entry && isAssistantMessage(entry.message as AgentMessage)) {
405
- messages.push(entry.message as AssistantMessage);
406
- }
407
- }
408
- const allText = messages.map(getTextContent).join("\n");
409
- markCompletedSteps(allText, todoItems);
410
- }
411
-
412
- if (planModeEnabled) {
413
- pi.setActiveTools(PLAN_MODE_TOOLS);
414
- }
415
- updateStatus(ctx);
416
- });
417
- }
@@ -1,12 +0,0 @@
1
- {
2
- "name": "@xtrm/pi-plan-mode",
3
- "version": "1.0.0",
4
- "description": "Plan mode extension for Pi - read-only exploration with plan extraction and bd integration",
5
- "type": "module",
6
- "exports": {
7
- ".": "./index.ts"
8
- },
9
- "keywords": ["pi", "extension", "plan-mode", "xtrm"],
10
- "author": "xtrm",
11
- "license": "MIT"
12
- }