@xynogen/pix-display 0.1.6 → 0.1.8

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.
package/README.md CHANGED
@@ -1,16 +1,18 @@
1
1
  # pix-display
2
2
 
3
- Pi core extension — paste chip rendering and thinking block display.
3
+ Pi core extension — paste chips, thinking blocks, and polished code snippets.
4
4
 
5
5
  ## What it does
6
6
 
7
- Two features, always on when installed:
7
+ Three features, always on when installed:
8
8
 
9
9
  **Paste chips.** Replaces Pi's paste markers (`[paste #1 2232 chars]`) with styled icon chips: `image #1` for image pastes (blue), `text +N lines` / `text Nk chars` for text pastes (green). Collapses pasted image paths into markers in the buffer while showing human-readable labels on screen. The display rewrite is purely visual — the buffer keeps the real path for the model. Expansion wraps each paste in `<paste>…</paste>` so adjacent pastes don't merge into one wall in the model-facing text.
10
10
 
11
11
  **Thinking blocks.** Converts leaked reasoning tags (`<think>`/`<thinking>`) from some providers into native Pi `thinking` content blocks, which render dim + italic via the `thinkingText` theme token. No ANSI injection, no markdown blockquote shim. Applies during streaming (`message_update`) and finalization (`message_end`).
12
12
 
13
- Both features are registered at session start and cleaned up at session shutdown. In non-interactive (JSON/RPC) mode they are no-ops.
13
+ **Code snippets.** Renders every fenced code block in assistant responses inside a themed, language-labeled frame—including Python, TypeScript, JSON, YAML, Rust, Go, SQL, shell, and arbitrary custom language tags. Untagged fences use a `code` label. Pi's native syntax highlighting remains intact for recognized languages, while long lines are safely clipped to the terminal width.
14
+
15
+ The features are registered at session start. TUI-only display changes are no-ops in JSON/RPC/print modes.
14
16
 
15
17
  ## Install
16
18
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@xynogen/pix-display",
3
- "version": "0.1.6",
4
- "description": "Pi core extension — paste chip rendering and thinking block display",
3
+ "version": "0.1.8",
4
+ "description": "Pi core extension — paste chips, thinking blocks, and framed code rendering",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
7
7
  "scripts": {
@@ -23,6 +23,8 @@
23
23
  "pi-extension",
24
24
  "paste-chips",
25
25
  "thinking",
26
+ "code-rendering",
27
+ "syntax-highlighting",
26
28
  "display"
27
29
  ],
28
30
  "author": "xynogen",
@@ -0,0 +1,164 @@
1
+ import {
2
+ AssistantMessageComponent,
3
+ type ExtensionAPI,
4
+ type Theme,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
7
+
8
+ const OPENING_FENCE_RE = /^```([^`]*)$/;
9
+ const CLOSING_FENCE_RE = /^```\s*$/;
10
+ const DEFAULT_LABEL = "code";
11
+ const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]/g;
12
+ const OSC_RE = /\x1b\][^\x07]*(?:\x07|\x1b\\)/g;
13
+ const PATCHED = Symbol.for("@xynogen/pix-display:code-block-renderer");
14
+
15
+ type CodeFrameTheme = Pick<Theme, "bg" | "bold" | "fg" | "getBgAnsi">;
16
+
17
+ type PatchablePrototype = {
18
+ [PATCHED]?: boolean;
19
+ render(width: number): string[];
20
+ };
21
+
22
+ let activeTheme: CodeFrameTheme | undefined;
23
+
24
+ function plainText(line: string): string {
25
+ return line.replace(OSC_RE, "").replace(ANSI_RE, "");
26
+ }
27
+
28
+ function oscSequences(line: string): string {
29
+ return line.match(OSC_RE)?.join("") ?? "";
30
+ }
31
+
32
+ function leadingSpaces(line: string): number {
33
+ return plainText(line).match(/^ */)?.[0].length ?? 0;
34
+ }
35
+
36
+ function stripLayoutWhitespace(line: string, count: number): string {
37
+ let remaining = count;
38
+ return line
39
+ .replace(OSC_RE, "")
40
+ .replace(/^(?:\x1b\[[0-?]*[ -/]*[@-~]| )+/, (prefix) =>
41
+ prefix.replace(/ /g, (space) => {
42
+ if (remaining <= 0) return space;
43
+ remaining--;
44
+ return "";
45
+ }),
46
+ )
47
+ .replace(/ +$/, "");
48
+ }
49
+
50
+ function paintFrame(theme: CodeFrameTheme, text: string): string {
51
+ try {
52
+ const bg = theme.getBgAnsi("toolSuccessBg");
53
+ const preserved = text.replace(/\x1b\[([0-9;]*)m/g, (sequence, params: string) =>
54
+ params === "0" || params.split(";").includes("49") ? `${sequence}${bg}` : sequence,
55
+ );
56
+ return `${bg}${preserved}\x1b[49m`;
57
+ } catch {
58
+ return theme.bg("toolSuccessBg", text);
59
+ }
60
+ }
61
+
62
+ function fenceLabel(line: string): string | undefined {
63
+ const match = plainText(line).trim().match(OPENING_FENCE_RE);
64
+ if (!match) return undefined;
65
+ const info = (match[1] ?? "").trim();
66
+ return info.split(/\s+/, 1)[0] || DEFAULT_LABEL;
67
+ }
68
+
69
+ function topBorder(width: number, language: string, theme: CodeFrameTheme): string {
70
+ const available = Math.max(1, width - 6);
71
+ const displayLanguage = truncateToWidth(language, available, "…");
72
+ const label = theme.bold(theme.fg("accent", ` ${displayLanguage} `));
73
+ const ruleWidth = Math.max(0, width - visibleWidth(label) - 3);
74
+ return paintFrame(
75
+ theme,
76
+ `${theme.fg("borderMuted", "╭─")}${label}${theme.fg("borderMuted", `${"─".repeat(ruleWidth)}╮`)}`,
77
+ );
78
+ }
79
+
80
+ function bottomBorder(width: number, theme: CodeFrameTheme): string {
81
+ return paintFrame(theme, theme.fg("borderMuted", `╰${"─".repeat(Math.max(0, width - 2))}╯`));
82
+ }
83
+
84
+ function bodyLine(
85
+ line: string,
86
+ width: number,
87
+ layoutIndent: number,
88
+ theme: CodeFrameTheme,
89
+ ): string {
90
+ const innerWidth = Math.max(1, width - 4);
91
+ const content = truncateToWidth(stripLayoutWhitespace(line, layoutIndent), innerWidth, "…");
92
+ const padding = " ".repeat(Math.max(0, innerWidth - visibleWidth(content)));
93
+ return paintFrame(
94
+ theme,
95
+ `${theme.fg("borderMuted", "│")} ${content}${padding} ${theme.fg("borderMuted", "│")}`,
96
+ );
97
+ }
98
+
99
+ /**
100
+ * Replace native Markdown fence rows with a themed code frame while preserving
101
+ * the syntax-highlighted ANSI content produced by Pi for every language.
102
+ */
103
+ export function renderCodeFences(lines: string[], width: number, theme: CodeFrameTheme): string[] {
104
+ if (width < 12) return lines;
105
+
106
+ const out = [...lines];
107
+ for (let start = 0; start < out.length; start++) {
108
+ const language = fenceLabel(out[start] ?? "");
109
+ if (!language) continue;
110
+
111
+ let end = start + 1;
112
+ while (end < out.length && !CLOSING_FENCE_RE.test(plainText(out[end] ?? "").trim())) {
113
+ end++;
114
+ }
115
+ if (end >= out.length) continue;
116
+
117
+ const pad = Math.min(leadingSpaces(out[start] ?? ""), Math.floor((width - 12) / 2));
118
+ const frameWidth = Math.max(12, width - pad * 2);
119
+ const body = out.slice(start + 1, end);
120
+ const bodyIndent = Math.min(
121
+ ...body
122
+ .map((line) => plainText(line))
123
+ .filter((line) => line.trim().length > 0)
124
+ .map((line) => leadingSpaces(line)),
125
+ pad,
126
+ );
127
+ const left = " ".repeat(pad);
128
+ const right = " ".repeat(Math.max(0, width - pad - frameWidth));
129
+ const framed: string[] = [];
130
+
131
+ framed.push(
132
+ `${oscSequences(out[start] ?? "")}${left}${topBorder(frameWidth, language, theme)}${right}`,
133
+ );
134
+ for (let index = start + 1; index < end; index++) {
135
+ framed.push(
136
+ `${oscSequences(out[index] ?? "")}${left}${bodyLine(out[index] ?? "", frameWidth, bodyIndent, theme)}${right}`,
137
+ );
138
+ }
139
+ framed.push(`${oscSequences(out[end] ?? "")}${left}${bottomBorder(frameWidth, theme)}${right}`);
140
+
141
+ out.splice(start, end - start + 1, ...framed);
142
+ start += framed.length - 1;
143
+ }
144
+ return out;
145
+ }
146
+
147
+ function patchAssistantRenderer(): void {
148
+ const prototype = AssistantMessageComponent.prototype as PatchablePrototype;
149
+ if (prototype[PATCHED]) return;
150
+
151
+ const nativeRender = prototype.render;
152
+ prototype.render = function renderWithCodeFrames(width: number): string[] {
153
+ const lines = nativeRender.call(this, width);
154
+ return activeTheme ? renderCodeFences(lines, width, activeTheme) : lines;
155
+ };
156
+ prototype[PATCHED] = true;
157
+ }
158
+
159
+ export default function codeBlocksExtension(pi: ExtensionAPI): void {
160
+ patchAssistantRenderer();
161
+ pi.on("session_start", (_event, ctx) => {
162
+ activeTheme = ctx.mode === "tui" ? ctx.ui.theme : undefined;
163
+ });
164
+ }
package/src/index.ts CHANGED
@@ -1,20 +1,23 @@
1
1
  /**
2
- * pix-display — Pi core extension: paste chip rendering + thinking block display.
2
+ * pix-display — Pi core extension: paste chips, thinking, and code-block display.
3
3
  *
4
- * Entry point: activates both paste-chips and thinking extensions at
5
- * session start. In non-interactive modes (JSON/RPC) both are no-ops.
4
+ * Entry point: activates paste-chip, thinking, and code-block extensions.
5
+ * Terminal-only rendering behavior stays inactive outside TUI mode.
6
6
  *
7
7
  * Modules:
8
8
  * paste-chips.ts ChipEditor overlay, marker restyling, image path collapse
9
9
  * thinking.ts Leaked reasoning tag → native thinking content blocks
10
+ * code-blocks.ts Framed, syntax-highlighted code fences in LLM output
10
11
  */
11
12
 
12
13
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
13
14
 
15
+ import codeBlocksExtension from "./code-blocks.js";
14
16
  import pasteChipsExtension from "./paste-chips.js";
15
17
  import thinkingExtension from "./thinking.js";
16
18
 
17
19
  export default function pixDisplayExtension(pi: ExtensionAPI): void {
18
20
  pasteChipsExtension(pi);
19
21
  thinkingExtension(pi);
22
+ codeBlocksExtension(pi);
20
23
  }
@@ -13,10 +13,7 @@
13
13
  * The display rewrite is purely visual (render layer); buffer is untouched.
14
14
  */
15
15
 
16
- import type {
17
- ExtensionAPI,
18
- KeybindingsManager,
19
- } from "@earendil-works/pi-coding-agent";
16
+ import type { ExtensionAPI, KeybindingsManager } from "@earendil-works/pi-coding-agent";
20
17
  import { CustomEditor } from "@earendil-works/pi-coding-agent";
21
18
  import type { EditorTheme, TUI } from "@earendil-works/pi-tui";
22
19
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
@@ -97,10 +94,7 @@ type ExpandPasteHandler = { expandPasteMarkers(text: string): string };
97
94
 
98
95
  // Mirror of the base Editor's paste-marker grammar, per-id at expand time.
99
96
  function markerReFor(pasteId: number): RegExp {
100
- return new RegExp(
101
- `\\[paste #${pasteId}( (\\+\\d+ lines|\\d+ chars))?\\]`,
102
- "g",
103
- );
97
+ return new RegExp(`\\[paste #${pasteId}( (\\+\\d+ lines|\\d+ chars))?\\]`, "g");
104
98
  }
105
99
 
106
100
  /**
@@ -109,10 +103,7 @@ function markerReFor(pasteId: number): RegExp {
109
103
  * boundary per blob (text and image alike) so adjacent pastes can't merge
110
104
  * into one indistinguishable wall in the model-facing text.
111
105
  */
112
- export function expandPasteMarkers(
113
- text: string,
114
- pastes: Map<number, string>,
115
- ): string {
106
+ export function expandPasteMarkers(text: string, pastes: Map<number, string>): string {
116
107
  let result = text;
117
108
  for (const [pasteId, pasteContent] of pastes) {
118
109
  result = result.replace(
@@ -162,35 +153,22 @@ export function restyleMarkers(line: string, imageIds: Set<number>): string {
162
153
  // Strip cursor inversion codes the TUI embeds when the cursor
163
154
  // intersects a marker — plain MARKER_RE handles the rest.
164
155
  const clean = line.includes("\x1b") ? line.replace(CURSOR_RE, "") : line;
165
- return clean.replace(
166
- MARKER_RE,
167
- (_full, idStr, _g2, _g3, linesStr, charsStr) => {
168
- const id = Number.parseInt(idStr, 10);
169
- if (imageIds.has(id)) {
170
- return chip(FG_BLUE, icon("paste.image"), "image", `#${id}`);
171
- }
172
- if (linesStr) {
173
- return chip(FG_GREEN, icon("paste.text"), "text", `${linesStr} lines`);
174
- }
175
- if (charsStr) {
176
- return chip(
177
- FG_GREEN,
178
- icon("paste.text"),
179
- "text",
180
- `${compactNumber(charsStr)} chars`,
181
- );
182
- }
183
- return chip(FG_GREEN, icon("paste.text"), "text", `#${id}`);
184
- },
185
- );
156
+ return clean.replace(MARKER_RE, (_full, idStr, _g2, _g3, linesStr, charsStr) => {
157
+ const id = Number.parseInt(idStr, 10);
158
+ if (imageIds.has(id)) {
159
+ return chip(FG_BLUE, icon("paste.image"), "image", `#${id}`);
160
+ }
161
+ if (linesStr) {
162
+ return chip(FG_GREEN, icon("paste.text"), "text", `${linesStr} lines`);
163
+ }
164
+ if (charsStr) {
165
+ return chip(FG_GREEN, icon("paste.text"), "text", `${compactNumber(charsStr)} chars`);
166
+ }
167
+ return chip(FG_GREEN, icon("paste.text"), "text", `#${id}`);
168
+ });
186
169
  }
187
170
 
188
- function chip(
189
- color: string,
190
- icon: string,
191
- label: string,
192
- meta: string,
193
- ): string {
171
+ function chip(color: string, icon: string, label: string, meta: string): string {
194
172
  return `${color}${BOLD}${icon} ${label}${RST}${FG_DIM} ${meta}${RST}`;
195
173
  }
196
174
 
@@ -228,9 +206,7 @@ class ChipEditor extends CustomEditor {
228
206
  const replaced = replaceImagePaths(text, internals, this.imageIds);
229
207
  // Append a trailing space when the insertion ends with a paste marker so
230
208
  // the cursor lands after the chip rather than inside it.
231
- super.insertTextAtCursor(
232
- endsWithMarker(replaced) ? `${replaced} ` : replaced,
233
- );
209
+ super.insertTextAtCursor(endsWithMarker(replaced) ? `${replaced} ` : replaced);
234
210
  }
235
211
 
236
212
  /**
@@ -243,8 +219,7 @@ class ChipEditor extends CustomEditor {
243
219
  private patchExpandPasteMarkers(): void {
244
220
  const internals = this as unknown as ExpandInternals;
245
221
  const self = this as unknown as ExpandPasteHandler;
246
- self.expandPasteMarkers = (text: string): string =>
247
- expandPasteMarkers(text, internals.pastes);
222
+ self.expandPasteMarkers = (text: string): string => expandPasteMarkers(text, internals.pastes);
248
223
  }
249
224
 
250
225
  private patchHandlePaste(): void {
package/src/thinking.ts CHANGED
@@ -131,10 +131,7 @@ function splitThinking(text: string): Block[] {
131
131
  const openMatch = OPEN_TAIL_RE.exec(rest);
132
132
  if (openMatch) {
133
133
  // Leading text may still carry orphan tags (e.g. a stray `</think>`).
134
- pushText(
135
- blocks,
136
- openMatch.input.slice(0, openMatch.index).replace(ORPHAN_TAG_RE, ""),
137
- );
134
+ pushText(blocks, openMatch.input.slice(0, openMatch.index).replace(ORPHAN_TAG_RE, ""));
138
135
  pushThinking(blocks, (openMatch[2] ?? "").replace(ORPHAN_TAG_RE, ""));
139
136
  } else {
140
137
  // Strip any orphan tags from the trailing text.