pi-cc-extensions 0.1.1

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.
Files changed (39) hide show
  1. package/README.md +141 -0
  2. package/assets/readme/context-preview.webp +0 -0
  3. package/assets/readme/context-usage.webp +0 -0
  4. package/assets/readme/hero.svg +101 -0
  5. package/assets/readme/session-reference.webp +0 -0
  6. package/assets/readme/showcase.webp +0 -0
  7. package/extensions/README.md +3 -0
  8. package/extensions/ccstyle-powerline/bash-mode/completion.ts +556 -0
  9. package/extensions/ccstyle-powerline/bash-mode/editor.ts +442 -0
  10. package/extensions/ccstyle-powerline/bash-mode/history.ts +151 -0
  11. package/extensions/ccstyle-powerline/bash-mode/shell-session.ts +286 -0
  12. package/extensions/ccstyle-powerline/bash-mode/transcript.ts +108 -0
  13. package/extensions/ccstyle-powerline/bash-mode/types.ts +59 -0
  14. package/extensions/ccstyle-powerline/colors.ts +69 -0
  15. package/extensions/ccstyle-powerline/context-usage.ts +46 -0
  16. package/extensions/ccstyle-powerline/fixed-editor/cluster.ts +107 -0
  17. package/extensions/ccstyle-powerline/fixed-editor/terminal-split.ts +1317 -0
  18. package/extensions/ccstyle-powerline/git-status.ts +218 -0
  19. package/extensions/ccstyle-powerline/icons.ts +181 -0
  20. package/extensions/ccstyle-powerline/powerline-config.ts +234 -0
  21. package/extensions/ccstyle-powerline/powerline.ts +3150 -0
  22. package/extensions/ccstyle-powerline/presets.ts +109 -0
  23. package/extensions/ccstyle-powerline/render-scheduler.ts +24 -0
  24. package/extensions/ccstyle-powerline/segments.ts +476 -0
  25. package/extensions/ccstyle-powerline/separators.ts +41 -0
  26. package/extensions/ccstyle-powerline/shortcuts.ts +57 -0
  27. package/extensions/ccstyle-powerline/theme.json +26 -0
  28. package/extensions/ccstyle-powerline/theme.ts +241 -0
  29. package/extensions/ccstyle-powerline/types.ts +197 -0
  30. package/extensions/ccstyle-powerline/welcome-dismiss.ts +34 -0
  31. package/extensions/ccstyle-powerline/welcome.ts +611 -0
  32. package/extensions/ccstyle-powerline/working-vibes.ts +695 -0
  33. package/extensions/claude-code-style.ts +987 -0
  34. package/extensions/context.ts +362 -0
  35. package/extensions/session-reference/README.md +28 -0
  36. package/extensions/session-reference/core.test.ts +74 -0
  37. package/extensions/session-reference/core.ts +258 -0
  38. package/extensions/session-reference/index.ts +379 -0
  39. package/package.json +33 -0
@@ -0,0 +1,987 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ createBashToolDefinition,
4
+ createEditToolDefinition,
5
+ createFindToolDefinition,
6
+ createGrepToolDefinition,
7
+ createLsToolDefinition,
8
+ createReadToolDefinition,
9
+ createWriteToolDefinition,
10
+ generateDiffString,
11
+ keyHint,
12
+ renderDiff,
13
+ ToolExecutionComponent,
14
+ } from "@earendil-works/pi-coding-agent";
15
+ import { Text, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
16
+ import powerlineFooter from "./ccstyle-powerline/powerline.ts";
17
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
18
+ import { readFile, stat } from "node:fs/promises";
19
+ import { homedir } from "node:os";
20
+ import { join, resolve } from "node:path";
21
+
22
+ /**
23
+ * Claude Code Style for pi
24
+ *
25
+ * Includes the bundled powerline footer (pipe separators, no Nerd Font arrows).
26
+ * When fixed-editor chat scrolling is active, a Claude Code-like jump-to-bottom
27
+ * button appears above the editor while the viewport is scrolled away from the
28
+ * latest output, including when new messages arrive. Click it, or use the
29
+ * displayed shortcut, to resume following the chat. Edit/write tool calls also
30
+ * show a bounded, colorized diff preview with +/- lines after execution. A
31
+ * collapsed tool result can be clicked on its Ctrl+O hint to expand only that tool.
32
+ *
33
+ * Dynamic commands:
34
+ * /ccstyle toggle on/off
35
+ * /ccstyle on enable
36
+ * /ccstyle off disable
37
+ * /ccstyle status show current state
38
+ * /ccstyle minimal hide most tool output in collapsed view
39
+ * /ccstyle compact show short summaries in collapsed view
40
+ * /ccstyle powerline compact|full|default|minimal|nerd|ascii|custom
41
+ *
42
+ * Shortcut:
43
+ * ctrl+shift+o toggle on/off
44
+ */
45
+
46
+ type StyleMode = "compact" | "minimal";
47
+
48
+ type Config = {
49
+ enabled: boolean;
50
+ mode: StyleMode;
51
+ };
52
+
53
+ const CONFIG_PATH = join(homedir(), ".pi", "agent", "claude-code-style.json");
54
+
55
+ let config: Config = loadConfig();
56
+
57
+ function loadConfig(): Config {
58
+ try {
59
+ if (existsSync(CONFIG_PATH)) {
60
+ const parsed = JSON.parse(readFileSync(CONFIG_PATH, "utf8")) as Partial<Config>;
61
+ return {
62
+ enabled: parsed.enabled ?? true,
63
+ mode: parsed.mode === "minimal" ? "minimal" : "compact",
64
+ };
65
+ }
66
+ } catch {
67
+ // Ignore bad config and fall back to defaults.
68
+ }
69
+ return { enabled: true, mode: "compact" };
70
+ }
71
+
72
+ function saveConfig() {
73
+ writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
74
+ }
75
+
76
+ function shortenPath(path: string): string {
77
+ const home = homedir();
78
+ if (path.startsWith(home)) return `~${path.slice(home.length)}`;
79
+ return path;
80
+ }
81
+
82
+ function oneLine(value: unknown, max = 72): string {
83
+ const text = String(value ?? "")
84
+ .replace(/\s+/g, " ")
85
+ .trim();
86
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
87
+ }
88
+
89
+ const UNSAFE_TERMINAL_ESCAPE = new RegExp(
90
+ "\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\x5C)"
91
+ + "|\\u001B[PX^_][\\s\\S]*?\\u001B\\x5C"
92
+ + "|(?:\\u001B\\[|\\u009B)[0-?]*[ -/]*[@-~]"
93
+ + "|\\u001B[@-_]",
94
+ "g",
95
+ );
96
+
97
+ /** Prevent captured terminal control responses from being replayed by tool renderers. */
98
+ function sanitizeToolResultText(value: string): string {
99
+ return value
100
+ .replace(UNSAFE_TERMINAL_ESCAPE, "")
101
+ .replace(/\x1B/g, "")
102
+ .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, "")
103
+ .replace(/\r\n/g, "\n")
104
+ .replace(/\r/g, "\n");
105
+ }
106
+
107
+ function textFromResult(result: any): string {
108
+ const item = result?.content?.find?.((c: any) => c.type === "text");
109
+ return item?.type === "text" ? sanitizeToolResultText(item.text ?? "") : "";
110
+ }
111
+
112
+ function countLines(text: string): number {
113
+ return text.trim().split("\n").filter((line) => line.trim().length > 0).length;
114
+ }
115
+
116
+ function hasExpandableResult(text: string): boolean {
117
+ return countLines(text) > 1;
118
+ }
119
+
120
+ function parsePathCount(text: string): number {
121
+ const files = new Set<string>();
122
+ for (const line of text.split("\n")) {
123
+ const match = line.match(/^([^:\n]+):(\d+:)?/);
124
+ if (match?.[1]) files.add(match[1]);
125
+ }
126
+ return files.size;
127
+ }
128
+
129
+ function summarizeBash(text: string): string {
130
+ const clean = text.trim();
131
+ if (!clean) return "Done";
132
+ const lower = clean.toLowerCase();
133
+ const lines = clean.split("\n").filter(Boolean);
134
+ const errorLine = lines.find((line) => /\b(error|failed|exception|fatal)\b/i.test(line));
135
+ if (errorLine) return `Failed: ${oneLine(errorLine, 88)}`;
136
+ if (/\b(warning|warn)\b/i.test(lower)) {
137
+ const warnings = lines.filter((line) => /\b(warning|warn)\b/i.test(line)).length;
138
+ return `Completed with ${warnings} warning${warnings === 1 ? "" : "s"}`;
139
+ }
140
+ if (/\b(success|passed|compiled|built|done)\b/i.test(lower)) return oneLine(lines.at(-1) ?? "Done", 88);
141
+ return lines.length > 1 ? `${lines.length} lines output: ${oneLine(lines.at(-1), 72)}` : oneLine(clean, 88);
142
+ }
143
+
144
+ function summarizeEdit(text: string): string {
145
+ const clean = text.trim();
146
+ if (!clean) return "Edited";
147
+ const added = (clean.match(/^\+/gm) ?? []).length;
148
+ const removed = (clean.match(/^-/gm) ?? []).length;
149
+ if (added || removed) return `Updated ${added} added, ${removed} removed`;
150
+ return oneLine(clean, 88);
151
+ }
152
+
153
+ function summarizeDiffStats(preview: FileDiffPreview | undefined): string | undefined {
154
+ if (!preview?.diff) return undefined;
155
+ const { added, removed } = preview.stats ?? diffStats(preview.lines ?? preview.diff.split("\n"));
156
+ if (!added && !removed) return undefined;
157
+ return `Added ${added} line${added === 1 ? "" : "s"}, removed ${removed} line${removed === 1 ? "" : "s"}`;
158
+ }
159
+
160
+ function toolIcon(_name: string): string {
161
+ return "●";
162
+ }
163
+
164
+ // Match the braille loader shown to the left of pi's "Working..." row.
165
+ // Every frame is one cell wide, so tool titles remain horizontally stable.
166
+ const WORKING_LOADER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
167
+ const TOOL_PENDING_FRAMES: Record<string, string[]> = {
168
+ read: WORKING_LOADER_FRAMES,
169
+ bash: WORKING_LOADER_FRAMES,
170
+ edit: WORKING_LOADER_FRAMES,
171
+ write: WORKING_LOADER_FRAMES,
172
+ find: WORKING_LOADER_FRAMES,
173
+ grep: WORKING_LOADER_FRAMES,
174
+ ls: WORKING_LOADER_FRAMES,
175
+ };
176
+
177
+ function animationFrame(frames: string[], intervalMs = 120): string {
178
+ return frames[Math.floor(Date.now() / intervalMs) % frames.length] ?? frames[0] ?? "";
179
+ }
180
+
181
+ const activeAnimationTimers = new Set<ReturnType<typeof setTimeout>>();
182
+
183
+ function clearAnimation(context: any) {
184
+ const timer = context?.state?.ccstyleAnimationTimer as ReturnType<typeof setTimeout> | undefined;
185
+ if (!timer) return;
186
+ clearTimeout(timer);
187
+ activeAnimationTimers.delete(timer);
188
+ context.state.ccstyleAnimationTimer = undefined;
189
+ }
190
+
191
+ function clearAllAnimations() {
192
+ for (const timer of activeAnimationTimers) clearTimeout(timer);
193
+ activeAnimationTimers.clear();
194
+ }
195
+
196
+ function scheduleAnimation(context: any, intervalMs = 80) {
197
+ const state = (context.state ??= {});
198
+ if (state.ccstyleAnimationTimer) return;
199
+ const timer = setTimeout(() => {
200
+ activeAnimationTimers.delete(timer);
201
+ state.ccstyleAnimationTimer = undefined;
202
+ context.invalidate?.();
203
+ }, intervalMs);
204
+ state.ccstyleAnimationTimer = timer;
205
+ activeAnimationTimers.add(timer);
206
+ }
207
+
208
+ function pendingIcon(name: string): string {
209
+ return animationFrame(TOOL_PENDING_FRAMES[name] ?? [toolIcon(name)], 80);
210
+ }
211
+
212
+ type ToolVisualState = "pending" | "success" | "error";
213
+
214
+ function settledIcon(name: string, state: ToolVisualState | undefined): string {
215
+ if (state === "success") return "✓";
216
+ if (state === "error") return "✗";
217
+ return toolIcon(name);
218
+ }
219
+
220
+ function setToolVisualState(context: any, visualState: ToolVisualState) {
221
+ const state = (context.state ??= {});
222
+ if (visualState !== "pending") clearAnimation(context);
223
+ if (state.ccstyleToolVisualState === visualState) return;
224
+ state.ccstyleToolVisualState = visualState;
225
+ // Do not invalidate synchronously from renderResult. Pi is already rendering
226
+ // this tool row; recursively scheduling another render here can retain both
227
+ // the finalized result component and its previous secondary/partial component,
228
+ // which displays the result summary twice. The current render pass also
229
+ // refreshes renderCall, so the settled icon still updates immediately.
230
+ }
231
+
232
+ function getToolVisualState(context: any): ToolVisualState | undefined {
233
+ return context?.state?.ccstyleToolVisualState as ToolVisualState | undefined;
234
+ }
235
+
236
+ function resolveToolVisualState(context: any): ToolVisualState | undefined {
237
+ const visualState = getToolVisualState(context);
238
+ if (visualState || context?.isPartial !== false) return visualState;
239
+ const settledState: ToolVisualState = context?.isError ? "error" : "success";
240
+ setToolVisualState(context, settledState);
241
+ return settledState;
242
+ }
243
+
244
+ function toolIconColor(context: any): "accent" | "error" | "success" | "muted" {
245
+ const visualState = getToolVisualState(context);
246
+ if (context?.isError || visualState === "error") return "error";
247
+ if (visualState === "success") return "success";
248
+ if (context?.isPartial || context?.executionStarted || visualState === "pending") return "accent";
249
+ return "muted";
250
+ }
251
+
252
+ function isToolExpanded(options: any, context: any): boolean {
253
+ const local = context?.state?.ccstyleToolExpanded;
254
+ return typeof local === "boolean" ? local : Boolean(options?.expanded ?? context?.expanded);
255
+ }
256
+
257
+ /** Keep the guide aligned when long result lines wrap at the viewport edge. */
258
+ class ExpandedToolResultText {
259
+ constructor(
260
+ private readonly text: string,
261
+ private readonly prefix: string,
262
+ ) {}
263
+
264
+ render(width: number): string[] {
265
+ const prefixWidth = visibleWidth(this.prefix);
266
+ const contentWidth = Math.max(1, width - prefixWidth);
267
+ return wrapTextWithAnsi(this.text.replace(/\t/g, " ").replace(/\n+$/, ""), contentWidth)
268
+ .map((line) => truncateToWidth(this.prefix + line, width, ""));
269
+ }
270
+
271
+ invalidate() {}
272
+ }
273
+
274
+ function renderCollapsedToolResult(body: string, collapsedHint = ""): string {
275
+ return ` ⎿ ${body}${collapsedHint}`;
276
+ }
277
+
278
+ function renderExpandedToolResult(body: string, theme: any, isError: boolean): ExpandedToolResultText | Text {
279
+ const color = isError ? "error" : "muted";
280
+ if (!body.trim()) {
281
+ return new Text(theme.fg(color, renderCollapsedToolResult("Done")), 0, 0);
282
+ }
283
+ return new ExpandedToolResultText(theme.fg(color, body), theme.fg(color, " │ "));
284
+ }
285
+
286
+ function expandHint(theme: any): string {
287
+ // Keep interaction guidance neutral; it should not inherit success/error
288
+ // coloring from the tool result surrounding it.
289
+ return `${theme.fg("muted", " (")}${keyHint("app.tools.expand", "expand")}${theme.fg("muted", " / click)")}`;
290
+ }
291
+
292
+ // Bright green for success icon (truecolor ANSI escape)
293
+ const BRIGHT_GREEN = "\x1b[38;2;80;220;100m";
294
+ const ANSI_RESET = "\x1b[0m";
295
+
296
+ function fileAction(args: any, verb: string): string {
297
+ const path = shortenPath(args?.path || "...");
298
+ return `${verb}(${path})`;
299
+ }
300
+
301
+ type DiffStats = { added: number; removed: number };
302
+ type FileDiffPreview = {
303
+ diff: string;
304
+ error?: string;
305
+ notice?: string;
306
+ stats?: DiffStats;
307
+ /** Pre-split outside the render hot path. */
308
+ lines?: string[];
309
+ };
310
+
311
+ // Diff generation is intentionally bounded: it runs before the mutation, but
312
+ // should never add unbounded latency or memory pressure to a tool call.
313
+ const MAX_DIFF_INPUT_BYTES = 2 * 1024 * 1024;
314
+ const COLLAPSED_DIFF_LINES = 12;
315
+ const EXPANDED_DIFF_LINES = 40;
316
+ const diffPreviewByCall = new Map<string, FileDiffPreview | undefined>();
317
+
318
+ function diffStats(lines: readonly string[]): DiffStats {
319
+ let added = 0;
320
+ let removed = 0;
321
+ for (const line of lines) {
322
+ if (/^\+\s*\d+\s/.test(line)) added++;
323
+ else if (/^-\s*\d+\s/.test(line)) removed++;
324
+ }
325
+ return { added, removed };
326
+ }
327
+
328
+ function diffPreview(diff: string): FileDiffPreview {
329
+ const lines = diff.split("\n");
330
+ return { diff, lines, stats: diffStats(lines) };
331
+ }
332
+
333
+ function normalizeDiffText(text: string): string {
334
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
335
+ }
336
+
337
+ function editEntries(args: any): Array<{ oldText: string; newText: string }> {
338
+ if (Array.isArray(args?.edits)) {
339
+ return args.edits.filter((edit: any) =>
340
+ typeof edit?.oldText === "string" && typeof edit?.newText === "string",
341
+ );
342
+ }
343
+ if (typeof args?.oldText === "string" && typeof args?.newText === "string") {
344
+ return [{ oldText: args.oldText, newText: args.newText }];
345
+ }
346
+ return [];
347
+ }
348
+
349
+ /** Build the preview before mutation, outside the renderer's hot path. */
350
+ async function buildFileDiffPreview(toolName: string, args: any, cwd: string): Promise<FileDiffPreview | undefined> {
351
+ const rawPath = typeof args?.path === "string" ? args.path : typeof args?.file_path === "string" ? args.file_path : "";
352
+ if (!rawPath) return undefined;
353
+
354
+ if (toolName === "write" && typeof args?.content === "string" && Buffer.byteLength(args.content, "utf8") > MAX_DIFF_INPUT_BYTES) {
355
+ return { diff: "", notice: "Diff omitted: new content exceeds 2 MiB" };
356
+ }
357
+
358
+ const absolutePath = resolve(cwd || process.cwd(), rawPath);
359
+ let before = "";
360
+ try {
361
+ const info = await stat(absolutePath);
362
+ if (info.size > MAX_DIFF_INPUT_BYTES) {
363
+ return { diff: "", notice: "Diff omitted: existing file exceeds 2 MiB" };
364
+ }
365
+ before = await readFile(absolutePath, "utf8");
366
+ } catch (error: any) {
367
+ if (error?.code !== "ENOENT") {
368
+ return { diff: "", error: `Cannot read ${shortenPath(rawPath)}: ${oneLine(error, 72)}` };
369
+ }
370
+ if (toolName === "edit") return { diff: "", error: `File not found: ${shortenPath(rawPath)}` };
371
+ }
372
+
373
+ before = normalizeDiffText(before);
374
+ let after = before;
375
+ if (toolName === "write") {
376
+ if (typeof args?.content !== "string") return undefined;
377
+ after = normalizeDiffText(args.content);
378
+ } else {
379
+ const edits = editEntries(args);
380
+ if (edits.length === 0) return undefined;
381
+ const replacements: Array<{ start: number; end: number; text: string }> = [];
382
+ for (const edit of edits) {
383
+ const oldText = normalizeDiffText(edit.oldText);
384
+ const start = after.indexOf(oldText);
385
+ if (start < 0) return { diff: "", error: "Preview unavailable: old text was not found" };
386
+ if (after.indexOf(oldText, start + 1) >= 0) {
387
+ return { diff: "", error: "Preview unavailable: old text is not unique" };
388
+ }
389
+ replacements.push({ start, end: start + oldText.length, text: normalizeDiffText(edit.newText) });
390
+ }
391
+ for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
392
+ after = after.slice(0, replacement.start) + replacement.text + after.slice(replacement.end);
393
+ }
394
+ }
395
+
396
+ if (Buffer.byteLength(after, "utf8") > MAX_DIFF_INPUT_BYTES) {
397
+ return { diff: "", notice: "Diff omitted: resulting content exceeds 2 MiB" };
398
+ }
399
+ const diff = generateDiffString(before, after).diff;
400
+ return diff ? diffPreview(diff) : undefined;
401
+ }
402
+
403
+ function diffLineCount(preview: FileDiffPreview | undefined): number {
404
+ if (!preview?.diff) return 0;
405
+ return preview.lines?.length ?? preview.diff.split("\n").length;
406
+ }
407
+
408
+ function hasExpandableDiff(preview: FileDiffPreview | undefined): boolean {
409
+ return diffLineCount(preview) > COLLAPSED_DIFF_LINES;
410
+ }
411
+
412
+ function renderDiffPreview(preview: FileDiffPreview | undefined, theme: any, expanded: boolean): string {
413
+ if (!preview) return "";
414
+ if (preview.error) return theme.fg("error", ` ${preview.error}`);
415
+ if (preview.notice) return theme.fg("muted", ` ${preview.notice}`);
416
+ if (!preview.diff.trim()) return "";
417
+
418
+ // Bound work before calling pi's renderer. Rendering only the visible raw
419
+ // lines avoids repeatedly running intra-line diffing over a multi-megabyte diff.
420
+ const rawLines = preview.lines ?? preview.diff.split("\n");
421
+ const maxLines = expanded ? EXPANDED_DIFF_LINES : COLLAPSED_DIFF_LINES;
422
+ const shown = renderDiff(rawLines.slice(0, maxLines).join("\n"))
423
+ .split("\n")
424
+ .map((line) => ` ${line}`);
425
+ if (rawLines.length > maxLines) {
426
+ shown.push(theme.fg("muted", ` … ${rawLines.length - maxLines} more diff lines`));
427
+ }
428
+ return shown.join("\n");
429
+ }
430
+
431
+ function renderFileDiffPreview(_toolName: string, _args: any, theme: any, context: any): string {
432
+ const state = (context.state ??= {});
433
+ if (diffPreviewByCall.has(context.toolCallId)) {
434
+ state.ccstyleDiffPreview = diffPreviewByCall.get(context.toolCallId);
435
+ diffPreviewByCall.delete(context.toolCallId);
436
+ }
437
+ return renderDiffPreview(state.ccstyleDiffPreview, theme, isToolExpanded(undefined, context));
438
+ }
439
+
440
+ function statusText() {
441
+ return config.enabled ? `CC ${config.mode}` : "CC off";
442
+ }
443
+
444
+ function updateStatus(ctx: any) {
445
+ ctx.ui.setStatus("ccstyle", statusText());
446
+ }
447
+
448
+ function renderDefault(tool: any, slot: "renderCall" | "renderResult", args: any[], fallback = "") {
449
+ try {
450
+ if (typeof tool?.[slot] === "function") return tool[slot](...args);
451
+ } catch {
452
+ // Fall through to raw fallback.
453
+ }
454
+ return new Text(fallback, 0, 0);
455
+ }
456
+
457
+ function createBuiltInTools(cwd: string) {
458
+ return {
459
+ // Keep complete definitions so wrapped tools retain prompt metadata,
460
+ // argument preparation, execution mode, and native fallback renderers.
461
+ read: createReadToolDefinition(cwd),
462
+ bash: createBashToolDefinition(cwd),
463
+ edit: createEditToolDefinition(cwd),
464
+ write: createWriteToolDefinition(cwd),
465
+ find: createFindToolDefinition(cwd),
466
+ grep: createGrepToolDefinition(cwd),
467
+ ls: createLsToolDefinition(cwd),
468
+ };
469
+ }
470
+
471
+ const toolCache = new Map<string, ReturnType<typeof createBuiltInTools>>();
472
+ function getBuiltInTools(cwd: string) {
473
+ let tools = toolCache.get(cwd);
474
+ if (!tools) {
475
+ tools = createBuiltInTools(cwd);
476
+ toolCache.set(cwd, tools);
477
+ }
478
+ return tools;
479
+ }
480
+
481
+ /** Tools explicitly wrapped with bespoke call/result renderers. Skip these in the generic interceptor. */
482
+ const WRAPPED_BUILTINS = new Set<string>();
483
+
484
+ /**
485
+ * Generate a descriptive label for an unknown tool from its args.
486
+ * Uses the tool label + first stringable arg value.
487
+ */
488
+ function toolCallLabel(toolName: string, toolLabel: string, args: any): string {
489
+ if (!args) return toolLabel;
490
+ const keys = Object.keys(args);
491
+ if (keys.length === 0) return toolLabel;
492
+ // Prefer "query" or "question" args, then fall back to the first stringable value
493
+ const preferred = ["query", "question", "command", "pattern", "name", "path", "url", "message"];
494
+ for (const key of preferred) {
495
+ const val = args[key];
496
+ if (val !== undefined && val !== null && typeof val !== "object") {
497
+ return `${toolLabel}(${oneLine(val, 60)})`;
498
+ }
499
+ }
500
+ const firstKey = keys[0];
501
+ const firstVal = args[firstKey];
502
+ if (firstVal !== undefined && firstVal !== null && typeof firstVal !== "object") {
503
+ return `${toolLabel}(${oneLine(firstVal, 60)})`;
504
+ }
505
+ return toolLabel;
506
+ }
507
+
508
+ /** Wrap an arbitrary tool definition with ccstyle call/result rendering. */
509
+ function createCcstyleTool(originalTool: any): any {
510
+ const toolName = originalTool.name;
511
+ const label = isMcpToolDefinition(originalTool, toolName)
512
+ ? toolName
513
+ : originalTool.label || toolName;
514
+
515
+ return {
516
+ ...originalTool,
517
+ renderShell: "self",
518
+ renderCall(args: any, theme: any, context: any) {
519
+ if (!config.enabled) {
520
+ return renderDefault(originalTool, "renderCall", [args, theme, context], String(toolName));
521
+ }
522
+
523
+ const visualState = resolveToolVisualState(context);
524
+ const isPending =
525
+ visualState === "pending" ||
526
+ (!visualState && (context?.isPartial || context?.executionStarted));
527
+ if (isPending) scheduleAnimation(context);
528
+ const rawIcon = isPending ? pendingIcon(toolName) : settledIcon(toolName, visualState);
529
+ const icon =
530
+ visualState === "success"
531
+ ? `${BRIGHT_GREEN}${rawIcon}${ANSI_RESET}`
532
+ : theme.fg(toolIconColor(context), rawIcon);
533
+
534
+ const title = `${icon} ${theme.fg("toolTitle", toolCallLabel(toolName, label, args))}`;
535
+ return new Text(title, 0, 0);
536
+ },
537
+ renderResult(result: any, options: any, theme: any, context: any) {
538
+ if (!config.enabled) {
539
+ return renderDefault(originalTool, "renderResult", [result, options, theme, context], textFromResult(result));
540
+ }
541
+
542
+ if (options?.isPartial) {
543
+ return new Text(theme.fg("muted", " ⎿ Pending…"), 0, 0);
544
+ }
545
+
546
+ const isError = options?.isError || context?.isError;
547
+ setToolVisualState(context, isError ? "error" : "success");
548
+ const expanded = isToolExpanded(options, context);
549
+
550
+ const text = textFromResult(result);
551
+ let rendered = "";
552
+ if (config.mode === "minimal" && !expanded) {
553
+ rendered = "";
554
+ } else if (!expanded) {
555
+ rendered = text ? oneLine(text, 96) : "Done";
556
+ } else {
557
+ rendered = text;
558
+ }
559
+
560
+ const hint = !expanded && hasExpandableResult(text) ? expandHint(theme) : "";
561
+ if (expanded) return renderExpandedToolResult(rendered, theme, isError);
562
+ return new Text(
563
+ theme.fg(isError ? "error" : "muted", renderCollapsedToolResult(rendered, hint)),
564
+ 0,
565
+ 0,
566
+ );
567
+ },
568
+ };
569
+ }
570
+
571
+ /**
572
+ * Extension APIs are isolated per plugin, so replacing this extension's
573
+ * pi.registerTool cannot see SDK tools or tools registered by other plugins.
574
+ * ToolExecutionComponent is shared by the TUI and exported by pi; patch its
575
+ * renderer lookup once so every generic tool uses the same compact shell.
576
+ * Only subagent tools keep their specialized renderers. Every other tool,
577
+ * including MCP and extension tools, uses the same compact ccstyle shell.
578
+ */
579
+ const GLOBAL_TOOL_RENDER_PATCH = Symbol.for("pi.ccstyle.global-tool-render-patch");
580
+ const COMPONENT_TOOL_RENDER_MODE = Symbol.for("pi.ccstyle.component-tool-render-mode");
581
+ const COMPONENT_TOOL_SELF_SHELL_MODE = Symbol.for("pi.ccstyle.component-tool-self-shell-mode");
582
+ const SUBAGENT_TOOL_NAMES = new Set(["Agent"]);
583
+ const globalToolRenderOwner = {};
584
+
585
+ type GlobalToolRenderPatch = {
586
+ prototype: any;
587
+ owner: object;
588
+ enabled: () => boolean;
589
+ wrap: (tool: any) => any;
590
+ byDefinition: WeakMap<object, any>;
591
+ byName: Map<string, any>;
592
+ originalHasRendererDefinition: (...args: any[]) => boolean;
593
+ originalGetRenderShell: (...args: any[]) => "default" | "self";
594
+ originalGetCallRenderer: (...args: any[]) => any;
595
+ originalGetResultRenderer: (...args: any[]) => any;
596
+ };
597
+
598
+ function isMcpToolDefinition(definition: any, toolName: string): boolean {
599
+ const label = typeof definition?.label === "string" ? definition.label : "";
600
+ return toolName === "mcp" || label === "MCP" || label.startsWith("MCP: ");
601
+ }
602
+
603
+ function preservesOriginalRenderer(_definition: any, toolName: string): boolean {
604
+ return SUBAGENT_TOOL_NAMES.has(toolName);
605
+ }
606
+
607
+ function shouldGloballyStyleTool(component: any, patch: GlobalToolRenderPatch): boolean {
608
+ const selectedMode = component[COMPONENT_TOOL_RENDER_MODE];
609
+ if (typeof selectedMode === "boolean") return selectedMode;
610
+
611
+ const definition = component.toolDefinition ?? component.builtInToolDefinition;
612
+ const toolName = String(component.toolName || definition?.name || "");
613
+ const useCcstyle =
614
+ patch.enabled() &&
615
+ !preservesOriginalRenderer(definition, toolName) &&
616
+ definition?.renderShell !== "self";
617
+ // ToolExecutionComponent chooses its child shell in the constructor. Keep that
618
+ // choice stable for this row so toggling ccstyle cannot switch containers later.
619
+ component[COMPONENT_TOOL_RENDER_MODE] = useCcstyle;
620
+ return useCcstyle;
621
+ }
622
+
623
+ function shouldUseSelfShell(component: any, patch: GlobalToolRenderPatch): boolean {
624
+ const selectedMode = component[COMPONENT_TOOL_SELF_SHELL_MODE];
625
+ if (typeof selectedMode === "boolean") return selectedMode;
626
+
627
+ const definition = component.toolDefinition ?? component.builtInToolDefinition;
628
+ const toolName = String(component.toolName || definition?.name || "");
629
+ const useSelfShell =
630
+ patch.enabled() &&
631
+ preservesOriginalRenderer(definition, toolName) &&
632
+ definition?.renderShell !== "self";
633
+ component[COMPONENT_TOOL_SELF_SHELL_MODE] = useSelfShell;
634
+ return useSelfShell;
635
+ }
636
+
637
+ function getGloballyStyledTool(component: any, patch: GlobalToolRenderPatch): any {
638
+ const definition = component.toolDefinition ?? component.builtInToolDefinition;
639
+ if (definition && typeof definition === "object") {
640
+ let wrapped = patch.byDefinition.get(definition);
641
+ if (!wrapped) {
642
+ wrapped = patch.wrap(definition);
643
+ patch.byDefinition.set(definition, wrapped);
644
+ }
645
+ return wrapped;
646
+ }
647
+
648
+ const name = String(component.toolName || "tool");
649
+ let wrapped = patch.byName.get(name);
650
+ if (!wrapped) {
651
+ wrapped = patch.wrap({ name, label: name });
652
+ patch.byName.set(name, wrapped);
653
+ }
654
+ return wrapped;
655
+ }
656
+
657
+ function installGlobalToolRendering() {
658
+ const prototype = (ToolExecutionComponent as any).prototype;
659
+ const host = globalThis as any;
660
+ let patch = host[GLOBAL_TOOL_RENDER_PATCH] as GlobalToolRenderPatch | undefined;
661
+
662
+ if (!patch || patch.prototype !== prototype) {
663
+ patch = {
664
+ prototype,
665
+ owner: globalToolRenderOwner,
666
+ enabled: () => config.enabled,
667
+ wrap: createCcstyleTool,
668
+ byDefinition: new WeakMap(),
669
+ byName: new Map(),
670
+ originalHasRendererDefinition: prototype.hasRendererDefinition,
671
+ originalGetRenderShell: prototype.getRenderShell,
672
+ originalGetCallRenderer: prototype.getCallRenderer,
673
+ originalGetResultRenderer: prototype.getResultRenderer,
674
+ };
675
+
676
+ host[GLOBAL_TOOL_RENDER_PATCH] = patch;
677
+ }
678
+
679
+ patch.owner = globalToolRenderOwner;
680
+ patch.enabled = () => config.enabled;
681
+ patch.wrap = createCcstyleTool;
682
+ patch.byDefinition = new WeakMap();
683
+ patch.byName.clear();
684
+
685
+ // Rebind on every load. /reload preserves the shared prototype and global
686
+ // patch object, so leaving these closures installed only in the initialization
687
+ // branch would keep the previous extension version's rendering logic alive.
688
+ prototype.hasRendererDefinition = function (...args: any[]) {
689
+ if (shouldGloballyStyleTool(this, patch!)) return true;
690
+ return patch!.originalHasRendererDefinition.apply(this, args);
691
+ };
692
+ prototype.getRenderShell = function (...args: any[]) {
693
+ if (shouldUseSelfShell(this, patch!) || shouldGloballyStyleTool(this, patch!)) return "self";
694
+ return patch!.originalGetRenderShell.apply(this, args);
695
+ };
696
+ prototype.getCallRenderer = function (...args: any[]) {
697
+ if (shouldGloballyStyleTool(this, patch!)) return getGloballyStyledTool(this, patch!).renderCall;
698
+ return patch!.originalGetCallRenderer.apply(this, args);
699
+ };
700
+ prototype.getResultRenderer = function (...args: any[]) {
701
+ if (shouldGloballyStyleTool(this, patch!)) return getGloballyStyledTool(this, patch!).renderResult;
702
+ return patch!.originalGetResultRenderer.apply(this, args);
703
+ };
704
+ }
705
+
706
+ function deactivateGlobalToolRendering() {
707
+ const patch = (globalThis as any)[GLOBAL_TOOL_RENDER_PATCH] as GlobalToolRenderPatch | undefined;
708
+ if (patch?.owner !== globalToolRenderOwner) return;
709
+ patch.enabled = () => false;
710
+ patch.byDefinition = new WeakMap();
711
+ patch.byName.clear();
712
+ }
713
+
714
+ const GLOBAL_COMPACTION_RENDER_PATCH = Symbol.for("pi.ccstyle.compaction-render-patch");
715
+
716
+ type LegacyCompactionRenderPatch = {
717
+ enabled?: () => boolean;
718
+ };
719
+
720
+ /** Disable the pre-native compaction monkey patch left alive by /reload. */
721
+ function deactivateLegacyCompactionRendering() {
722
+ const patch = (globalThis as any)[GLOBAL_COMPACTION_RENDER_PATCH] as LegacyCompactionRenderPatch | undefined;
723
+ if (patch) patch.enabled = () => false;
724
+ }
725
+
726
+ function registerWrappedTool(pi: ExtensionAPI, name: keyof ReturnType<typeof createBuiltInTools>, renderer: {
727
+ call: (args: any, theme: any) => string;
728
+ result: (result: any, options: any, theme: any, context: any) => string;
729
+ diff?: (args: any, theme: any, context: any) => string;
730
+ /** Use pi's built-in call/result renderers, including native diff panels. */
731
+ defaultRenderer?: boolean;
732
+ defaultResult?: boolean;
733
+ diffAfterResult?: boolean;
734
+ }) {
735
+ WRAPPED_BUILTINS.add(name);
736
+ const initial = getBuiltInTools(process.cwd())[name] as any;
737
+
738
+ pi.registerTool({
739
+ // Spread the full definition instead of copying a subset. In particular,
740
+ // edit requires prepareArguments and tools may declare executionMode.
741
+ ...initial,
742
+ name,
743
+ label: initial.label ?? name,
744
+ renderShell: "self",
745
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
746
+ const tool = (getBuiltInTools(ctx.cwd)[name] as any);
747
+ if (config.enabled && (name === "edit" || name === "write")) {
748
+ // Await the old-file snapshot before mutation to avoid races, while
749
+ // keeping all filesystem and diff work out of the TUI renderer.
750
+ diffPreviewByCall.set(toolCallId, await buildFileDiffPreview(name, params, ctx.cwd));
751
+ }
752
+ let result: any;
753
+ try {
754
+ result = await tool.execute(toolCallId, params, signal, onUpdate, ctx);
755
+ } catch (error) {
756
+ diffPreviewByCall.delete(toolCallId);
757
+ throw error;
758
+ }
759
+ if (name === "edit" && typeof result?.details?.diff === "string") {
760
+ const actualDiff = result.details.diff as string;
761
+ diffPreviewByCall.set(toolCallId,
762
+ Buffer.byteLength(actualDiff, "utf8") <= MAX_DIFF_INPUT_BYTES
763
+ ? diffPreview(actualDiff)
764
+ : { diff: "", notice: "Diff omitted: result exceeds 2 MiB" },
765
+ );
766
+ }
767
+ return result;
768
+ },
769
+ renderCall(args, theme, context) {
770
+ const tool = (getBuiltInTools(context.cwd)[name] as any);
771
+ if (!config.enabled || renderer.defaultRenderer) {
772
+ return renderDefault(tool, "renderCall", [args, theme, context], String(name));
773
+ }
774
+
775
+ const toolName = String(name);
776
+ const visualState = resolveToolVisualState(context);
777
+ const isPending = visualState === "pending" || (!visualState && (context?.isPartial || context?.executionStarted));
778
+ if (isPending) scheduleAnimation(context);
779
+ const rawIcon = isPending ? pendingIcon(toolName) : settledIcon(toolName, visualState);
780
+ const icon = visualState === "success"
781
+ ? `${BRIGHT_GREEN}${rawIcon}${ANSI_RESET}`
782
+ : theme.fg(toolIconColor(context), rawIcon);
783
+ const title = `${icon} ${theme.fg("toolTitle", renderer.call(args, theme))}`;
784
+ // Prime the per-tool snapshot, but keep the call row stable while arguments
785
+ // stream in. The diff is rendered only after the result is finalized below.
786
+ if (renderer.diffAfterResult) renderer.diff?.(args, theme, context);
787
+ return new Text(title, 0, 0);
788
+ },
789
+ renderResult(result, options, theme, context) {
790
+ const tool = (getBuiltInTools(context.cwd)[name] as any);
791
+ if (!config.enabled || renderer.defaultResult) {
792
+ diffPreviewByCall.delete(context.toolCallId);
793
+ return renderDefault(tool, "renderResult", [result, options, theme, context], textFromResult(result));
794
+ }
795
+
796
+ if (options?.isPartial) {
797
+ return new Text(theme.fg("muted", " ⎿ Pending…"), 0, 0);
798
+ }
799
+
800
+ const isError = options?.isError || context?.isError;
801
+ if (isError) {
802
+ diffPreviewByCall.delete(context.toolCallId);
803
+ if (context.state) context.state.ccstyleDiffPreview = undefined;
804
+ }
805
+ setToolVisualState(context, isError ? "error" : "success");
806
+ const expanded = isToolExpanded(options, context);
807
+ // Hydrate the cached preview before building the summary so edit uses
808
+ // the authoritative result.details.diff rather than its estimate.
809
+ const diff = !isError && renderer.diffAfterResult
810
+ ? renderer.diff?.(context.args, theme, context)
811
+ : "";
812
+ const rendered = renderer.result(result, { ...options, expanded }, theme, context);
813
+ if (!rendered) return new Text("", 0, 0);
814
+ const fullText = textFromResult(result);
815
+ const preview = context?.state?.ccstyleDiffPreview as FileDiffPreview | undefined;
816
+ const hint = !expanded && (hasExpandableResult(fullText) || hasExpandableDiff(preview))
817
+ ? expandHint(theme)
818
+ : "";
819
+ const body = `${rendered}${diff ? `\n${diff}` : ""}`;
820
+ if (expanded) return renderExpandedToolResult(body, theme, isError);
821
+ const output = ` ⎿ ${rendered}${hint}${diff ? `\n${diff}` : ""}`;
822
+ return new Text(
823
+ theme.fg(isError ? "error" : "muted", output),
824
+ 0,
825
+ 0,
826
+ );
827
+ },
828
+ });
829
+ }
830
+
831
+ export default function (pi: ExtensionAPI) {
832
+ installGlobalToolRendering();
833
+ deactivateLegacyCompactionRendering();
834
+
835
+ // Bundle the full powerline footer into ccstyle so it is loaded as one plugin.
836
+ const powerline = powerlineFooter(pi);
837
+
838
+ pi.registerCommand("ccstyle", {
839
+ description: "Configure Claude Code style and Powerline preset",
840
+ handler: async (args, ctx) => {
841
+ const arg = args.trim().toLowerCase();
842
+ const parts = arg.split(/\s+/).filter(Boolean);
843
+ if (parts[0] === "powerline") {
844
+ const requested = parts[1] === "mode" ? parts[2] : parts[1];
845
+ if (!requested) {
846
+ ctx.ui.notify(`Powerline preset: ${powerline.getPreset()}. Available: ${powerline.getPresets().join(", ")}`, "info");
847
+ return;
848
+ }
849
+ const result = powerline.setPreset(requested, ctx);
850
+ if (!result.valid) {
851
+ ctx.ui.notify(`Unknown Powerline preset: ${requested}. Available: ${powerline.getPresets().join(", ")}`, "warning");
852
+ return;
853
+ }
854
+ ctx.ui.notify(
855
+ `Powerline preset set to: ${requested}${result.persisted ? "" : " (not persisted; check settings.json)"}`,
856
+ result.persisted ? "info" : "warning",
857
+ );
858
+ return;
859
+ }
860
+ if (arg === "on" || arg === "enable") config.enabled = true;
861
+ else if (arg === "off" || arg === "disable") config.enabled = false;
862
+ else if (arg === "minimal") {
863
+ config.enabled = true;
864
+ config.mode = "minimal";
865
+ } else if (arg === "compact") {
866
+ config.enabled = true;
867
+ config.mode = "compact";
868
+ } else if (arg === "status") {
869
+ updateStatus(ctx);
870
+ ctx.ui.notify(
871
+ `Claude Code style: ${config.enabled ? "on" : "off"}, mode=${config.mode}, powerline=${powerline.getPreset()}`,
872
+ "info",
873
+ );
874
+ return;
875
+ } else {
876
+ config.enabled = !config.enabled;
877
+ }
878
+ saveConfig();
879
+ updateStatus(ctx);
880
+ ctx.ui.notify(`Claude Code style: ${config.enabled ? "on" : "off"}, mode=${config.mode}`, "info");
881
+ },
882
+ });
883
+
884
+ pi.registerShortcut("ctrl+shift+o", {
885
+ description: "Toggle Claude Code-like output style",
886
+ handler: async (ctx) => {
887
+ config.enabled = !config.enabled;
888
+ saveConfig();
889
+ updateStatus(ctx);
890
+ ctx.ui.notify(`Claude Code style: ${config.enabled ? "on" : "off"}`, "info");
891
+ },
892
+ });
893
+
894
+ pi.on("session_start", async (_event, ctx) => {
895
+ diffPreviewByCall.clear();
896
+ updateStatus(ctx);
897
+ });
898
+
899
+ pi.on("session_shutdown", async () => {
900
+ deactivateGlobalToolRendering();
901
+ deactivateLegacyCompactionRendering();
902
+ clearAllAnimations();
903
+ diffPreviewByCall.clear();
904
+ toolCache.clear();
905
+ });
906
+
907
+ registerWrappedTool(pi, "read", {
908
+ call: (args) => fileAction(args, "Read"),
909
+ result: (result, { expanded }) => {
910
+ const text = textFromResult(result);
911
+ if (config.mode === "minimal" && !expanded) return "";
912
+ if (!expanded) return `${countLines(text)} lines read`;
913
+ return text;
914
+ },
915
+ });
916
+
917
+ registerWrappedTool(pi, "bash", {
918
+ call: (args) => `Bash(${oneLine(args?.command, 86) || "..."})`,
919
+ result: (result, { expanded }) => {
920
+ const text = textFromResult(result).trim();
921
+ if (config.mode === "minimal" && !expanded) return "";
922
+ if (!expanded) return summarizeBash(text);
923
+ return text;
924
+ },
925
+ });
926
+
927
+ registerWrappedTool(pi, "edit", {
928
+ call: (args) => fileAction(args, "Edit"),
929
+ diff: (args, theme, context) => renderFileDiffPreview("edit", args, theme, context),
930
+ diffAfterResult: true,
931
+ result: (result, { expanded }, _theme, context) => {
932
+ const text = textFromResult(result).trim();
933
+ if (config.mode === "minimal" && !expanded) return "";
934
+ return summarizeDiffStats(context?.state?.ccstyleDiffPreview) ?? summarizeEdit(text);
935
+ },
936
+ });
937
+
938
+ registerWrappedTool(pi, "write", {
939
+ call: (args) => {
940
+ const path = shortenPath(args?.path || "...");
941
+ const lines = args?.content ? countLines(args.content) : 0;
942
+ return `Write(${path}${lines ? `, ${lines} lines` : ""})`;
943
+ },
944
+ diff: (args, theme, context) => renderFileDiffPreview("write", args, theme, context),
945
+ diffAfterResult: true,
946
+ result: (result, { expanded }, _theme, context) => {
947
+ const text = textFromResult(result).trim();
948
+ if (config.mode === "minimal" && !expanded) return "";
949
+ return summarizeDiffStats(context?.state?.ccstyleDiffPreview) ?? (text ? oneLine(text, 96) : "Written");
950
+ },
951
+ });
952
+
953
+ registerWrappedTool(pi, "find", {
954
+ call: (args) => `Find(${args?.pattern || "..."}${args?.path ? ` in ${shortenPath(args.path)}` : ""})`,
955
+ result: (result, { expanded }) => {
956
+ const text = textFromResult(result).trim();
957
+ if (config.mode === "minimal" && !expanded) return "";
958
+ if (!expanded) return `${countLines(text)} files`;
959
+ return text;
960
+ },
961
+ });
962
+
963
+ registerWrappedTool(pi, "grep", {
964
+ call: (args) => `Grep(${args?.pattern ? `/${oneLine(args.pattern, 48)}/` : "..."})`,
965
+ result: (result, { expanded }) => {
966
+ const text = textFromResult(result).trim();
967
+ if (config.mode === "minimal" && !expanded) return "";
968
+ if (!expanded) {
969
+ const matches = countLines(text);
970
+ const files = parsePathCount(text);
971
+ return files ? `Found ${matches} matches in ${files} files` : `${matches} matches`;
972
+ }
973
+ return text;
974
+ },
975
+ });
976
+
977
+ registerWrappedTool(pi, "ls", {
978
+ call: (args) => `List(${shortenPath(args?.path || ".")})`,
979
+ result: (result, { expanded }) => {
980
+ const text = textFromResult(result).trim();
981
+ if (config.mode === "minimal" && !expanded) return "";
982
+ if (!expanded) return `${countLines(text)} entries`;
983
+ return text;
984
+ },
985
+ });
986
+
987
+ }