pi-code 0.1.0

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.
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Output Styles Extension
3
+ *
4
+ * Bridges Claude Code's output styles into pi. It discovers `.claude/output-styles/*.md`
5
+ * (user then project), honors the active style recorded as `outputStyle` in
6
+ * `.claude/settings.json` (user, project, then settings.local.json, last wins),
7
+ * and appends that style's body to the system prompt so the agent adopts its
8
+ * tone and role. `/output-style` lists the styles and persists a choice to the
9
+ * project's settings.local.json.
10
+ *
11
+ * pi keeps its own base system prompt (tools, safety); the style is layered on
12
+ * top rather than replacing it wholesale.
13
+ *
14
+ * Docs: https://code.claude.com/docs/en/output-styles.md
15
+ */
16
+
17
+ import * as fs from 'node:fs'
18
+ import * as os from 'node:os'
19
+ import * as path from 'node:path'
20
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
21
+
22
+ export interface OutputStyle {
23
+ name: string
24
+ description: string
25
+ body: string
26
+ }
27
+
28
+ function field(frontmatter: string, key: string): string {
29
+ const match = new RegExp(`^\\s*${key}\\s*:\\s*(.+)$`, 'm').exec(frontmatter)
30
+ return match ? match[1].trim().replace(/^["']|["']$/g, '') : ''
31
+ }
32
+
33
+ /** Parse an output-style markdown file into its name, description, and body. */
34
+ export function parseStyle(content: string, fallbackName: string): OutputStyle {
35
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(content)
36
+ const frontmatter = match ? match[1] : ''
37
+ const body = match ? content.slice(match[0].length) : content
38
+ return { name: field(frontmatter, 'name') || fallbackName, description: field(frontmatter, 'description'), body: body.trim() }
39
+ }
40
+
41
+ function isDirectory(target: string): boolean {
42
+ try {
43
+ return fs.statSync(target).isDirectory()
44
+ } catch {
45
+ return false
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Existing `.claude/output-styles` directories, user first then project. The project
51
+ * directory is included only for trusted projects, since its style body is injected
52
+ * verbatim into the system prompt.
53
+ */
54
+ export function styleDirs(cwd: string, home: string, trusted: boolean): string[] {
55
+ const dirs = [path.join(home, '.claude', 'output-styles')]
56
+ if (trusted) dirs.push(path.join(cwd, '.claude', 'output-styles'))
57
+ return dirs.filter((dir) => isDirectory(dir))
58
+ }
59
+
60
+ /** All output styles, project entries overriding user entries of the same name. */
61
+ export function loadStyles(dirs: string[]): OutputStyle[] {
62
+ const byName = new Map<string, OutputStyle>()
63
+ for (const dir of dirs) {
64
+ let entries: string[]
65
+ try {
66
+ entries = fs.readdirSync(dir)
67
+ } catch {
68
+ continue
69
+ }
70
+ for (const entry of entries) {
71
+ if (!entry.endsWith('.md')) continue
72
+ const style = parseStyle(fs.readFileSync(path.join(dir, entry), 'utf-8'), entry.replace(/\.md$/, ''))
73
+ byName.set(style.name, style)
74
+ }
75
+ }
76
+ return [...byName.values()]
77
+ }
78
+
79
+ /** Settings files that carry `outputStyle`. Project settings apply only when trusted. */
80
+ export function settingsFiles(cwd: string, home: string, trusted: boolean): string[] {
81
+ const files = [path.join(home, '.claude', 'settings.json')]
82
+ if (trusted) files.push(path.join(cwd, '.claude', 'settings.json'), path.join(cwd, '.claude', 'settings.local.json'))
83
+ return files
84
+ }
85
+
86
+ /** The `outputStyle` recorded in settings, last file winning. */
87
+ export function readActiveStyleName(files: string[]): string | undefined {
88
+ let name: string | undefined
89
+ for (const file of files) {
90
+ try {
91
+ const settings = JSON.parse(fs.readFileSync(file, 'utf-8'))
92
+ if (typeof settings.outputStyle === 'string') name = settings.outputStyle
93
+ } catch {
94
+ // missing or invalid file: skip
95
+ }
96
+ }
97
+ return name
98
+ }
99
+
100
+ export function styleForName(styles: OutputStyle[], name: string | undefined): OutputStyle | undefined {
101
+ return name ? styles.find((style) => style.name === name) : undefined
102
+ }
103
+
104
+ function persistActiveStyle(file: string, name: string): void {
105
+ let config: Record<string, unknown> = {}
106
+ try {
107
+ config = JSON.parse(fs.readFileSync(file, 'utf-8'))
108
+ } catch {
109
+ // start from an empty config when the file is missing or invalid
110
+ }
111
+ config.outputStyle = name
112
+ fs.mkdirSync(path.dirname(file), { recursive: true })
113
+ fs.writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`)
114
+ }
115
+
116
+ export default function outputStylesExtension(pi: ExtensionAPI) {
117
+ let styles: OutputStyle[] = []
118
+ let activeName: string | undefined
119
+ let localSettingsPath = ''
120
+
121
+ pi.on('session_start', async (_event, ctx) => {
122
+ const home = os.homedir()
123
+ // A project style body is injected verbatim into the system prompt, so only honor
124
+ // project styles / selection once the project is trusted.
125
+ const trusted = ctx.isProjectTrusted?.() ?? false
126
+ styles = loadStyles(styleDirs(ctx.cwd, home, trusted))
127
+ localSettingsPath = path.join(ctx.cwd, '.claude', 'settings.local.json')
128
+ activeName = readActiveStyleName(settingsFiles(ctx.cwd, home, trusted))
129
+ const active = styleForName(styles, activeName)
130
+ if (active) ctx.ui.notify(`Output style: ${active.name}`, 'info')
131
+ })
132
+
133
+ pi.on('before_agent_start', async (event) => {
134
+ const active = styleForName(styles, activeName)
135
+ if (!active || active.body.length === 0) return
136
+ return { systemPrompt: `${event.systemPrompt}\n\n## Output Style: ${active.name}\n\n${active.body}` }
137
+ })
138
+
139
+ pi.registerCommand('output-style', {
140
+ description: 'Choose the active Claude output style',
141
+ handler: async (_args, ctx) => {
142
+ if (!ctx.hasUI) {
143
+ ctx.ui.notify('/output-style requires interactive mode', 'error')
144
+ return
145
+ }
146
+ if (styles.length === 0) {
147
+ ctx.ui.notify('No output styles found in .claude/output-styles', 'info')
148
+ return
149
+ }
150
+ const labels = styles.map((style) => (style.description ? `${style.name} — ${style.description}` : style.name))
151
+ const choice = await ctx.ui.select('Output style:', labels)
152
+ if (!choice) return
153
+ const picked = styles[labels.indexOf(choice)]
154
+ activeName = picked.name
155
+ persistActiveStyle(localSettingsPath, picked.name)
156
+ ctx.ui.notify(`Output style set to ${picked.name} (applies next turn)`, 'info')
157
+ },
158
+ })
159
+ }
@@ -0,0 +1,65 @@
1
+ # Plan Mode Extension
2
+
3
+ Read-only exploration mode for safe code analysis.
4
+
5
+ ## Features
6
+
7
+ - **Read-only tools**: Restricts available tools to read, bash, grep, find, ls, question
8
+ - **Bash allowlist**: Only read-only bash commands are allowed
9
+ - **Plan extraction**: Extracts numbered steps from `Plan:` sections
10
+ - **Progress tracking**: Widget shows completion status during execution
11
+ - **[DONE:n] markers**: Explicit step completion tracking
12
+ - **Session persistence**: State survives session resume
13
+
14
+ ## Commands
15
+
16
+ - `/plan` - Toggle plan mode
17
+ - `/todos` - Show current plan progress
18
+ - `Ctrl+Alt+P` - Toggle plan mode (shortcut)
19
+
20
+ ## Usage
21
+
22
+ 1. Enable plan mode with `/plan` or `--plan` flag
23
+ 2. Ask the agent to analyze code and create a plan
24
+ 3. The agent should output a numbered plan under a `Plan:` header:
25
+
26
+ ```
27
+ Plan:
28
+ 1. First step description
29
+ 2. Second step description
30
+ 3. Third step description
31
+ ```
32
+
33
+ 4. Choose "Execute the plan" when prompted
34
+ 5. During execution, the agent marks steps complete with `[DONE:n]` tags
35
+ 6. Progress widget shows completion status
36
+
37
+ ## How It Works
38
+
39
+ ### Plan Mode (Read-Only)
40
+ - Only read-only tools available
41
+ - Bash commands filtered through allowlist
42
+ - Agent creates a plan without making changes
43
+
44
+ ### Execution Mode
45
+ - Full tool access restored
46
+ - Agent executes steps in order
47
+ - `[DONE:n]` markers track completion
48
+ - Widget shows progress
49
+
50
+ ### Command Allowlist
51
+
52
+ Safe commands (allowed):
53
+ - File inspection: `cat`, `head`, `tail`, `less`, `more`
54
+ - Search: `grep`, `find`, `rg`, `fd`
55
+ - Directory: `ls`, `pwd`, `tree`
56
+ - Git read: `git status`, `git log`, `git diff`, `git branch`
57
+ - Package info: `npm list`, `npm outdated`, `yarn info`
58
+ - System info: `uname`, `whoami`, `date`, `uptime`
59
+
60
+ Blocked commands:
61
+ - File modification: `rm`, `mv`, `cp`, `mkdir`, `touch`
62
+ - Git write: `git add`, `git commit`, `git push`
63
+ - Package install: `npm install`, `yarn add`, `pip install`
64
+ - System: `sudo`, `kill`, `reboot`
65
+ - Editors: `vim`, `nano`, `code`
@@ -0,0 +1,352 @@
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 '@earendil-works/pi-agent-core'
16
+ import type { AssistantMessage, TextContent } from '@earendil-works/pi-ai'
17
+ import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent'
18
+ import { Key } from '@earendil-works/pi-tui'
19
+ import { Type } from 'typebox'
20
+ import { extractTodoItems, isSafeCommand, markCompletedSteps, planToTodos, type TodoItem } from './utils.js'
21
+
22
+ // Tools
23
+ const PLAN_MODE_TOOLS = ['read', 'bash', 'grep', 'find', 'ls', 'question', 'plan_mode_complete']
24
+
25
+ // Type guard for assistant messages
26
+ function isAssistantMessage(m: AgentMessage): m is AssistantMessage {
27
+ return m.role === 'assistant' && Array.isArray(m.content)
28
+ }
29
+
30
+ // Extract text content from an assistant message
31
+ function getTextContent(message: AssistantMessage): string {
32
+ return message.content
33
+ .filter((block): block is TextContent => block.type === 'text')
34
+ .map((block) => block.text)
35
+ .join('\n')
36
+ }
37
+
38
+ export default function planModeExtension(pi: ExtensionAPI): void {
39
+ let planModeEnabled = false
40
+ let executionMode = false
41
+ let todoItems: TodoItem[] = []
42
+ let planFromTool = false
43
+ let savedTools: string[] = []
44
+
45
+ function enterPlanTools(): void {
46
+ savedTools = pi.getActiveTools()
47
+ pi.setActiveTools(PLAN_MODE_TOOLS.filter((t) => savedTools.includes(t)))
48
+ }
49
+
50
+ function restoreTools(): void {
51
+ if (savedTools.length > 0) {
52
+ pi.setActiveTools(savedTools)
53
+ }
54
+ }
55
+
56
+ pi.registerFlag('plan', {
57
+ description: 'Start in plan mode (read-only exploration)',
58
+ type: 'boolean',
59
+ default: false,
60
+ })
61
+
62
+ function updateStatus(ctx: ExtensionContext): void {
63
+ // Footer status
64
+ if (executionMode && todoItems.length > 0) {
65
+ const completed = todoItems.filter((t) => t.completed).length
66
+ ctx.ui.setStatus('plan-mode', ctx.ui.theme.fg('accent', `📋 ${completed}/${todoItems.length}`))
67
+ } else if (planModeEnabled) {
68
+ ctx.ui.setStatus('plan-mode', ctx.ui.theme.fg('warning', '⏸ plan'))
69
+ } else {
70
+ ctx.ui.setStatus('plan-mode', undefined)
71
+ }
72
+
73
+ // Widget showing todo list
74
+ if (executionMode && todoItems.length > 0) {
75
+ const lines = todoItems.map((item) => {
76
+ if (item.completed) {
77
+ return ctx.ui.theme.fg('success', '☑ ') + ctx.ui.theme.fg('muted', ctx.ui.theme.strikethrough(item.text))
78
+ }
79
+ return `${ctx.ui.theme.fg('muted', '☐ ')}${item.text}`
80
+ })
81
+ ctx.ui.setWidget('plan-todos', lines)
82
+ } else {
83
+ ctx.ui.setWidget('plan-todos', undefined)
84
+ }
85
+ }
86
+
87
+ function togglePlanMode(ctx: ExtensionContext): void {
88
+ planModeEnabled = !planModeEnabled
89
+ executionMode = false
90
+ todoItems = []
91
+ planFromTool = false
92
+
93
+ if (planModeEnabled) {
94
+ enterPlanTools()
95
+ ctx.ui.notify(`Plan mode enabled. Tools: ${pi.getActiveTools().join(', ')}`)
96
+ } else {
97
+ restoreTools()
98
+ ctx.ui.notify('Plan mode disabled. Full access restored.')
99
+ }
100
+ updateStatus(ctx)
101
+ }
102
+
103
+ function persistState(): void {
104
+ pi.appendEntry('plan-mode', {
105
+ enabled: planModeEnabled,
106
+ todos: todoItems,
107
+ executing: executionMode,
108
+ })
109
+ }
110
+
111
+ pi.registerCommand('plan', {
112
+ description: 'Toggle plan mode (read-only exploration)',
113
+ handler: async (_args, ctx) => togglePlanMode(ctx),
114
+ })
115
+
116
+ pi.registerTool({
117
+ name: 'plan_mode_complete',
118
+ label: 'Plan complete',
119
+ description: 'Submit the finished plan for user review while in plan mode. Pass the full plan as numbered steps (1. ... 2. ...). Call this exactly once, when the plan is ready.',
120
+ parameters: Type.Object({ plan: Type.String({ description: 'The complete numbered plan' }) }),
121
+ async execute(_id, params) {
122
+ if (!planModeEnabled) {
123
+ return { content: [{ type: 'text', text: 'Not in plan mode; tool ignored.' }], details: {} }
124
+ }
125
+ todoItems = planToTodos(params.plan)
126
+ planFromTool = true
127
+ persistState()
128
+ return { content: [{ type: 'text', text: 'Plan submitted. The user will now review it.' }], details: {}, terminate: true }
129
+ },
130
+ })
131
+
132
+ pi.registerCommand('plan-todos', {
133
+ description: 'Show current plan todo list',
134
+ handler: async (_args, ctx) => {
135
+ if (todoItems.length === 0) {
136
+ ctx.ui.notify('No todos. Create a plan first with /plan', 'info')
137
+ return
138
+ }
139
+ const list = todoItems.map((item, i) => `${i + 1}. ${item.completed ? '✓' : '○'} ${item.text}`).join('\n')
140
+ ctx.ui.notify(`Plan Progress:\n${list}`, 'info')
141
+ },
142
+ })
143
+
144
+ pi.registerShortcut(Key.ctrlAlt('p'), {
145
+ description: 'Toggle plan mode',
146
+ handler: async (ctx) => togglePlanMode(ctx),
147
+ })
148
+
149
+ // Block destructive bash commands in plan mode
150
+ pi.on('tool_call', async (event) => {
151
+ if (!planModeEnabled || event.toolName !== 'bash') return
152
+
153
+ const command = event.input.command as string
154
+ if (!isSafeCommand(command)) {
155
+ return {
156
+ block: true,
157
+ reason: `Plan mode: command blocked (not allowlisted). Use /plan to disable plan mode first.\nCommand: ${command}`,
158
+ }
159
+ }
160
+ })
161
+
162
+ // Filter out stale plan mode context when not in plan mode
163
+ pi.on('context', async (event) => {
164
+ if (planModeEnabled) return
165
+
166
+ return {
167
+ messages: event.messages.filter((m) => {
168
+ const msg = m as AgentMessage & { customType?: string }
169
+ if (msg.customType === 'plan-mode-context') return false
170
+ if (msg.role !== 'user') return true
171
+
172
+ const content = msg.content
173
+ if (typeof content === 'string') {
174
+ return !content.includes('[PLAN MODE ACTIVE]')
175
+ }
176
+ if (Array.isArray(content)) {
177
+ return !content.some((c) => c.type === 'text' && (c as TextContent).text?.includes('[PLAN MODE ACTIVE]'))
178
+ }
179
+ return true
180
+ }),
181
+ }
182
+ })
183
+
184
+ // Inject plan/execution context before agent starts
185
+ pi.on('before_agent_start', async () => {
186
+ if (planModeEnabled) {
187
+ return {
188
+ message: {
189
+ customType: 'plan-mode-context',
190
+ content: `[PLAN MODE ACTIVE]
191
+ You are in plan mode - a read-only exploration mode for safe code analysis.
192
+
193
+ Restrictions:
194
+ - You can only use: read, bash, grep, find, ls, question
195
+ - You CANNOT use: edit, write (file modifications are disabled)
196
+ - Bash is restricted to an allowlist of read-only commands
197
+
198
+ Ask clarifying questions using the question tool.
199
+
200
+ When your plan is ready, call the plan_mode_complete tool with the full plan as numbered steps:
201
+
202
+ 1. First step description
203
+ 2. Second step description
204
+ ...
205
+
206
+ Do NOT attempt to make changes - just describe what you would do.`,
207
+ display: false,
208
+ },
209
+ }
210
+ }
211
+
212
+ if (executionMode && todoItems.length > 0) {
213
+ const remaining = todoItems.filter((t) => !t.completed)
214
+ const todoList = remaining.map((t) => `${t.step}. ${t.text}`).join('\n')
215
+ return {
216
+ message: {
217
+ customType: 'plan-execution-context',
218
+ content: `[EXECUTING PLAN - Full tool access enabled]
219
+
220
+ Remaining steps:
221
+ ${todoList}
222
+
223
+ Execute each step in order.
224
+ After completing a step, include a [DONE:n] tag in your response.`,
225
+ display: false,
226
+ },
227
+ }
228
+ }
229
+ })
230
+
231
+ // Track progress after each turn
232
+ pi.on('turn_end', async (event, ctx) => {
233
+ if (!executionMode || todoItems.length === 0) return
234
+ if (!isAssistantMessage(event.message)) return
235
+
236
+ const text = getTextContent(event.message)
237
+ if (markCompletedSteps(text, todoItems) > 0) {
238
+ updateStatus(ctx)
239
+ }
240
+ persistState()
241
+ })
242
+
243
+ // Handle plan completion and plan mode UI
244
+ pi.on('agent_end', async (event, ctx) => {
245
+ // Check if execution is complete
246
+ if (executionMode && todoItems.length > 0) {
247
+ if (todoItems.every((t) => t.completed)) {
248
+ const completedList = todoItems.map((t) => `~~${t.text}~~`).join('\n')
249
+ pi.sendMessage({ customType: 'plan-complete', content: `**Plan Complete!** ✓\n\n${completedList}`, display: true }, { triggerTurn: false })
250
+ executionMode = false
251
+ todoItems = []
252
+ restoreTools()
253
+ updateStatus(ctx)
254
+ persistState() // Save cleared state so resume doesn't restore old execution mode
255
+ }
256
+ return
257
+ }
258
+
259
+ if (!planModeEnabled || !ctx.hasUI) return
260
+
261
+ // Prefer an explicitly submitted plan; fall back to extracting from prose
262
+ if (!planFromTool) {
263
+ const lastAssistant = [...event.messages].reverse().find(isAssistantMessage)
264
+ if (lastAssistant) {
265
+ const extracted = extractTodoItems(getTextContent(lastAssistant))
266
+ if (extracted.length > 0) {
267
+ todoItems = extracted
268
+ }
269
+ }
270
+ }
271
+
272
+ // Show plan steps and prompt for next action
273
+ if (todoItems.length > 0) {
274
+ const todoListText = todoItems.map((t, i) => `${i + 1}. ☐ ${t.text}`).join('\n')
275
+ pi.sendMessage(
276
+ {
277
+ customType: 'plan-todo-list',
278
+ content: `**Plan Steps (${todoItems.length}):**\n\n${todoListText}`,
279
+ display: true,
280
+ },
281
+ { triggerTurn: false },
282
+ )
283
+ }
284
+
285
+ const choice = await ctx.ui.select('Plan mode - what next?', [todoItems.length > 0 ? 'Execute the plan (track progress)' : 'Execute the plan', 'Stay in plan mode', 'Refine the plan'])
286
+
287
+ if (choice?.startsWith('Execute')) {
288
+ planModeEnabled = false
289
+ executionMode = todoItems.length > 0
290
+ planFromTool = false
291
+ restoreTools()
292
+ updateStatus(ctx)
293
+
294
+ const execMessage = todoItems.length > 0 ? `Execute the plan. Start with: ${todoItems[0].text}` : 'Execute the plan you just created.'
295
+ pi.sendMessage({ customType: 'plan-mode-execute', content: execMessage, display: true }, { triggerTurn: true })
296
+ } else if (choice === 'Refine the plan') {
297
+ const refinement = await ctx.ui.editor('Refine the plan:', '')
298
+ if (refinement?.trim()) {
299
+ pi.sendUserMessage(refinement.trim())
300
+ }
301
+ }
302
+ })
303
+
304
+ // Restore state on session start/resume
305
+ pi.on('session_start', async (_event, ctx) => {
306
+ if (pi.getFlag('plan') === true) {
307
+ planModeEnabled = true
308
+ }
309
+
310
+ const entries = ctx.sessionManager.getEntries()
311
+
312
+ // Restore persisted state
313
+ const planModeEntry = entries.filter((e: { type: string; customType?: string }) => e.type === 'custom' && e.customType === 'plan-mode').pop() as { data?: { enabled: boolean; todos?: TodoItem[]; executing?: boolean } } | undefined
314
+
315
+ if (planModeEntry?.data) {
316
+ planModeEnabled = planModeEntry.data.enabled ?? planModeEnabled
317
+ todoItems = planModeEntry.data.todos ?? todoItems
318
+ executionMode = planModeEntry.data.executing ?? executionMode
319
+ }
320
+
321
+ // On resume: re-scan messages to rebuild completion state
322
+ // Only scan messages AFTER the last "plan-mode-execute" to avoid picking up [DONE:n] from previous plans
323
+ const isResume = planModeEntry !== undefined
324
+ if (isResume && executionMode && todoItems.length > 0) {
325
+ // Find the index of the last plan-mode-execute entry (marks when current execution started)
326
+ let executeIndex = -1
327
+ for (let i = entries.length - 1; i >= 0; i--) {
328
+ const entry = entries[i] as { type: string; customType?: string }
329
+ if (entry.customType === 'plan-mode-execute') {
330
+ executeIndex = i
331
+ break
332
+ }
333
+ }
334
+
335
+ // Only scan messages after the execute marker
336
+ const messages: AssistantMessage[] = []
337
+ for (let i = executeIndex + 1; i < entries.length; i++) {
338
+ const entry = entries[i]
339
+ if (entry.type === 'message' && 'message' in entry && isAssistantMessage(entry.message as AgentMessage)) {
340
+ messages.push(entry.message as AssistantMessage)
341
+ }
342
+ }
343
+ const allText = messages.map(getTextContent).join('\n')
344
+ markCompletedSteps(allText, todoItems)
345
+ }
346
+
347
+ if (planModeEnabled) {
348
+ enterPlanTools()
349
+ }
350
+ updateStatus(ctx)
351
+ })
352
+ }