@xynogen/pix-display 0.4.1 → 0.4.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xynogen/pix-display",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Pi core extension — inline chips, thinking blocks, and framed code rendering",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -38,8 +38,8 @@
38
38
  "access": "public"
39
39
  },
40
40
  "dependencies": {
41
- "@xynogen/pix-pretty": "^3.0.2",
42
- "@xynogen/pix-runtime": "^0.22.3"
41
+ "@xynogen/pix-pretty": "^3.1.0",
42
+ "@xynogen/pix-runtime": "^0.22.4"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@mathjax/src": "4.1.3",
@@ -5,6 +5,7 @@ import {
5
5
  visibleWidth,
6
6
  } from "@xynogen/pix-pretty/tui";
7
7
  import type { ExtensionAPI } from "@xynogen/pix-runtime/host";
8
+ import { wrapMethod } from "@xynogen/pix-runtime/patch";
8
9
 
9
10
  const OPENING_FENCE_RE = /^```([^`]*)$/;
10
11
  const CLOSING_FENCE_RE = /^```\s*$/;
@@ -12,17 +13,10 @@ const DEFAULT_LABEL = "code";
12
13
  const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]/g;
13
14
  const BACKGROUND_ANSI_RE = /\x1b\[(?:4[0-9]|48)(?:;[^m]*)?m/g;
14
15
  const OSC_RE = /\x1b\][^\x07]*(?:\x07|\x1b\\)/g;
15
- const PATCHED = Symbol.for("@xynogen/pix-display:code-block-renderer");
16
16
 
17
17
  type CodeFrameTheme = Pick<Theme, "bold" | "fg">;
18
18
  type RenderMode = "tui" | "rpc" | "json" | "print";
19
19
 
20
- type PatchablePrototype = {
21
- [PATCHED]?: boolean;
22
- render(width: number): readonly string[];
23
- invalidate(): void;
24
- };
25
-
26
20
  let activeTheme: CodeFrameTheme | undefined;
27
21
 
28
22
  /**
@@ -138,13 +132,9 @@ export function renderCodeFences(
138
132
  }
139
133
 
140
134
  function patchAssistantRenderer(): void {
141
- const prototype = AssistantMessageComponent.prototype as PatchablePrototype;
142
- if (prototype[PATCHED]) return;
143
-
144
- const nativeRender = prototype.render;
145
- const nativeInvalidate = prototype.invalidate;
135
+ const prototype = AssistantMessageComponent.prototype;
146
136
  const cache = new WeakMap<
147
- PatchablePrototype,
137
+ object,
148
138
  {
149
139
  width: number;
150
140
  theme: CodeFrameTheme;
@@ -152,28 +142,37 @@ function patchAssistantRenderer(): void {
152
142
  output: readonly string[];
153
143
  }
154
144
  >();
155
- prototype.invalidate = function invalidateCodeFrames(): void {
156
- cache.delete(this);
157
- nativeInvalidate.call(this);
158
- };
159
- prototype.render = function renderWithCodeFrames(width: number): readonly string[] {
160
- const lines = nativeRender.call(this, width);
161
- if (!activeTheme) return lines;
162
- const previous = cache.get(this);
163
- if (
164
- previous &&
165
- previous.width === width &&
166
- previous.theme === activeTheme &&
167
- previous.input.length === lines.length &&
168
- lines.every((line, i) => line === previous.input[i])
169
- ) {
170
- return previous.output;
171
- }
172
- const output = renderCodeFences(lines, width, activeTheme);
173
- cache.set(this, { width, theme: activeTheme, input: [...lines], output });
174
- return output;
175
- };
176
- prototype[PATCHED] = true;
145
+ wrapMethod(
146
+ prototype,
147
+ "invalidate",
148
+ (native) =>
149
+ function invalidateCodeFrames(this: object): void {
150
+ cache.delete(this);
151
+ native.call(this);
152
+ },
153
+ );
154
+ wrapMethod(
155
+ prototype,
156
+ "render",
157
+ (native) =>
158
+ function renderWithCodeFrames(this: object, width: number): readonly string[] {
159
+ const lines: readonly string[] = native.call(this, width);
160
+ if (!activeTheme) return lines;
161
+ const previous = cache.get(this);
162
+ if (
163
+ previous &&
164
+ previous.width === width &&
165
+ previous.theme === activeTheme &&
166
+ previous.input.length === lines.length &&
167
+ lines.every((line, i) => line === previous.input[i])
168
+ ) {
169
+ return previous.output;
170
+ }
171
+ const output = renderCodeFences(lines, width, activeTheme);
172
+ cache.set(this, { width, theme: activeTheme, input: [...lines], output });
173
+ return output;
174
+ },
175
+ );
177
176
  }
178
177
 
179
178
  export default function codeBlocksExtension(pi: ExtensionAPI): void {
package/src/directives.ts CHANGED
@@ -13,6 +13,7 @@
13
13
  * inline code stay literal.
14
14
  */
15
15
  import { BOLD, FG_BLUE, FG_DIM, FG_GREEN, FG_RED, FG_YELLOW, RST } from "@xynogen/pix-pretty/ansi";
16
+ import { setMarkdownTransform } from "@xynogen/pix-pretty/markdown-transform";
16
17
  import {
17
18
  getCapabilities,
18
19
  getMarkdownTheme,
@@ -477,13 +478,16 @@ export function renderDirectives(markdown: string, width: number): string {
477
478
  return out.join("\n");
478
479
  }
479
480
 
481
+ /** The display pipeline for assistant Markdown: Mermaid, math, then directives. */
482
+ export function renderDisplayMarkdown(markdown: string, width: number): string {
483
+ return renderDirectives(renderMathBlocks(renderMermaidBlocks(markdown, width), width), width);
484
+ }
485
+
480
486
  export default function directivesExtension(pi: ExtensionAPI): void {
481
487
  pi.registerMarkdownTransformer?.(
482
- (markdown, { availableWidth }) =>
483
- renderDirectives(
484
- renderMathBlocks(renderMermaidBlocks(markdown, availableWidth), availableWidth),
485
- availableWidth,
486
- ),
488
+ (markdown, { availableWidth }) => renderDisplayMarkdown(markdown, availableWidth),
487
489
  { messageTypes: ["assistant"] },
488
490
  );
491
+ // Entry renderers (the /btw card) bypass Pi's chain; share the same pipeline.
492
+ setMarkdownTransform(renderDisplayMarkdown);
489
493
  }
package/src/image.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { basename } from "node:path";
9
9
  import { FG_DIM, RST } from "@xynogen/pix-pretty/ansi";
10
- import { getImageDimensions, Image } from "@xynogen/pix-pretty/tui";
10
+ import { getCapabilities, getImageDimensions, Image } from "@xynogen/pix-pretty/tui";
11
11
  import { readFileSync, statSync } from "@xynogen/pix-runtime/fs";
12
12
  import { localFilePath } from "@xynogen/pix-runtime/paths";
13
13
 
@@ -96,3 +96,44 @@ export function renderImageRows(
96
96
  .render(width)
97
97
  .map((row) => row || NBSP);
98
98
  }
99
+
100
+ // Space between an image and its frame: columns left/right, rows above/below.
101
+ const PAD_X = 2;
102
+ const PAD_Y = 1;
103
+ /** Columns the frame adds around an image. */
104
+ export const FRAME_COLS = 2 + 2 * PAD_X;
105
+
106
+ /**
107
+ * Box image rows in a dim rounded frame, like the `::card` cards, when it fits in
108
+ * `width`. Kitty only: it draws without moving the cursor, so each row writes spaces
109
+ * over the image cells to reach the right border. Spaces, not a cursor jump: a jump
110
+ * leaves the cells unpainted, so a card background has a hole there and old text
111
+ * shows through a transparent image. Kitty keeps an image when text is written
112
+ * under it. iTerm2 draws from the last row with its own cursor movement, so it
113
+ * stays unframed.
114
+ */
115
+ export function frameImage(image: string[], width: number): string[] {
116
+ // The columns Pi's Image actually drew, which can differ from the requested cap.
117
+ const cols = Number(/[;,]c=(\d+)/.exec(image[0] ?? "")?.[1]);
118
+ if (getCapabilities().images !== "kitty" || !(cols > 0) || cols + FRAME_COLS > width) {
119
+ return image;
120
+ }
121
+ const pad = " ".repeat(PAD_X);
122
+ const under = " ".repeat(cols);
123
+ const side = `${FG_DIM}│${RST}`;
124
+ const rule = "─".repeat(cols + 2 * PAD_X);
125
+ const blank = `${side}${pad}${under}${pad}${side}`;
126
+ // Markdown indents every row by its paddingX except image rows, so indent that one here.
127
+ // ponytail: assumes Markdown spans its parent with equal paddingX on both sides (Pi's
128
+ // transcript, and cards that pad their Markdown rather than their Box).
129
+ const margin = " ".repeat(Math.max(0, ((process.stdout.columns ?? width) - width) >> 1));
130
+ return [
131
+ `${FG_DIM}╭${rule}╮${RST}`,
132
+ ...Array<string>(PAD_Y).fill(blank),
133
+ ...image.map((row, i) =>
134
+ i === 0 ? `${margin}${side}${pad}${row}${under}${pad}${side}` : blank,
135
+ ),
136
+ ...Array<string>(PAD_Y).fill(blank),
137
+ `${FG_DIM}╰${rule}╯${RST}`,
138
+ ];
139
+ }
package/src/math.ts CHANGED
@@ -12,13 +12,12 @@
12
12
  * support, engine not installed or loaded, a TeX error, or a formula wider than the screen.
13
13
  */
14
14
  import { dirname, join } from "node:path";
15
- import { FG_DIM, RST } from "@xynogen/pix-pretty/ansi";
16
15
  import { type ConfirmUI, confirmOverlay } from "@xynogen/pix-pretty/confirm";
17
16
  import { getCapabilities, getCellDimensions } from "@xynogen/pix-pretty/tui";
18
17
  import { readFile } from "@xynogen/pix-runtime/fs";
19
18
  import { installIntoPrefix } from "@xynogen/pix-runtime/npm-prefix";
20
19
  import { agentDir, importFile, requireFrom } from "@xynogen/pix-runtime/paths";
21
- import { renderImageRows } from "./image.ts";
20
+ import { frameImage, renderImageRows } from "./image.ts";
22
21
 
23
22
  /** SVG plus its natural size in `ex`, the unit MathJax lays math out in. */
24
23
  type Typeset = (tex: string) => { svg: string; widthEx: number; heightEx: number } | undefined;
@@ -43,9 +42,6 @@ const INK = "#e6e6e6";
43
42
  // One `ex` is about half a text row, so text-size math is `heightEx / 2` rows tall.
44
43
  const ROWS_PER_EX = 0.5;
45
44
  const MAX_ROWS = 8;
46
- // Space between the formula and its frame: columns left/right, rows above/below.
47
- const PAD_X = 2;
48
- const PAD_Y = 1;
49
45
  const MAX_CACHE = 32;
50
46
  const cache = new Map<string, string[]>();
51
47
 
@@ -180,35 +176,6 @@ export async function offerMathInstall(
180
176
  );
181
177
  }
182
178
 
183
- /**
184
- * Box the image in a dim rounded frame, like the `::card` cards. Kitty only: it
185
- * draws without moving the cursor, so each row jumps the cursor past the image
186
- * (`CSI n C`) to reach the right border. iTerm2 draws from the last row with its
187
- * own cursor movement, so it stays unframed.
188
- */
189
- function frame(image: string[], width: number): string[] {
190
- // The columns Pi's Image actually drew, which can differ from the requested cap.
191
- const cols = Number(/[;,]c=(\d+)/.exec(image[0] ?? "")?.[1]);
192
- if (getCapabilities().images !== "kitty" || !(cols > 0)) return image;
193
- const pad = " ".repeat(PAD_X);
194
- const skip = `\x1b[${cols}C`;
195
- const side = `${FG_DIM}│${RST}`;
196
- const rule = "─".repeat(cols + 2 * PAD_X);
197
- const blank = `${side}${pad}${skip}${pad}${side}`;
198
- // Markdown indents every row by Pi's outputPad except image rows, so indent that one here.
199
- // ponytail: assumes the reply spans the terminal (true for Pi's transcript).
200
- const margin = " ".repeat(Math.max(0, ((process.stdout.columns ?? width) - width) >> 1));
201
- return [
202
- `${FG_DIM}╭${rule}╮${RST}`,
203
- ...Array<string>(PAD_Y).fill(blank),
204
- ...image.map((row, i) =>
205
- i === 0 ? `${margin}${side}${pad}${row}${skip}${pad}${side}` : blank,
206
- ),
207
- ...Array<string>(PAD_Y).fill(blank),
208
- `${FG_DIM}╰${rule}╯${RST}`,
209
- ];
210
- }
211
-
212
179
  /** Image rows for one display formula, or undefined to keep Pi's own rendering. */
213
180
  export function renderMath(tex: string, width: number): string[] | undefined {
214
181
  if (!engine || !getCapabilities().images) return undefined;
@@ -233,7 +200,7 @@ export function renderMath(tex: string, width: number): string[] | undefined {
233
200
  maxWidthCells: cols,
234
201
  maxHeightCells: rows,
235
202
  });
236
- const lines = cols + 2 + 2 * PAD_X <= width ? frame(image, width) : image;
203
+ const lines = frameImage(image, width);
237
204
  cache.set(key, lines);
238
205
  if (cache.size > MAX_CACHE) cache.delete(cache.keys().next().value ?? "");
239
206
  return lines;
package/src/mermaid.ts CHANGED
@@ -16,11 +16,11 @@
16
16
  import { join } from "node:path";
17
17
  import { type ConfirmUI, confirmOverlay } from "@xynogen/pix-pretty/confirm";
18
18
  import { getCapabilities, getCellDimensions } from "@xynogen/pix-pretty/tui";
19
- import { writeFileAtomicSync } from "@xynogen/pix-runtime/atomic-write";
20
19
  import { existsSync, readFile, readFileSync } from "@xynogen/pix-runtime/fs";
21
20
  import { installIntoPrefix } from "@xynogen/pix-runtime/npm-prefix";
22
21
  import { agentDir, importFile, requireFrom } from "@xynogen/pix-runtime/paths";
23
- import { renderImageRows } from "./image.ts";
22
+ import { setPiSettings } from "@xynogen/pix-runtime/pi-settings";
23
+ import { FRAME_COLS, frameImage, renderImageRows } from "./image.ts";
24
24
 
25
25
  type Svg = (source: string) => string;
26
26
  type Text = (source: string) => string;
@@ -51,8 +51,9 @@ const COLORS = {
51
51
  accent: "#7aa2f7",
52
52
  muted: "#565f89",
53
53
  };
54
- // Node labels are 13px in beautiful-mermaid's layout: that size becomes one text row.
54
+ // Node labels are 13px in beautiful-mermaid's layout; ZOOM sets how many text rows that is.
55
55
  const TEXT_PX = 13;
56
+ const ZOOM = 1;
56
57
  const MAX_ROWS = 40;
57
58
  const MAX_CACHE = 16;
58
59
  const cache = new Map<string, string[]>();
@@ -150,8 +151,8 @@ async function load(): Promise<void> {
150
151
  rasterise: (svg, heightPx) =>
151
152
  new resvg.Resvg(svg, {
152
153
  fitTo: { mode: "height", value: heightPx },
153
- // Opaque: kitty draws over the cells, so a transparent image shows old text through it.
154
- background: COLORS.bg,
154
+ // Transparent, like math: frameImage writes spaces under the image, so the cells
155
+ // hold the surrounding background (a card's color) and no old text.
155
156
  font: { fontBuffers, defaultFontFamily: "Inter", loadSystemFonts: false },
156
157
  })
157
158
  .render()
@@ -187,14 +188,8 @@ export function hasMermaid(messages: readonly TextMessage[]): boolean {
187
188
  * this extension. Returns "changed", "already" when it was off, or "failed".
188
189
  */
189
190
  function disablePiMermaid(): "changed" | "already" | "failed" {
190
- const path = join(agentDir(), "settings.json");
191
191
  try {
192
- const text = existsSync(path) ? readFileSync(path, "utf-8").replace(/^\uFEFF/, "") : "{}";
193
- const settings = JSON.parse(text) as { markdown?: Record<string, unknown> };
194
- if (settings.markdown?.mermaid === "off") return "already";
195
- settings.markdown = { ...settings.markdown, mermaid: "off" };
196
- writeFileAtomicSync(path, `${JSON.stringify(settings, null, 2)}\n`);
197
- return "changed";
192
+ return setPiSettings({ markdown: { mermaid: "off" } }) ? "changed" : "already";
198
193
  } catch {
199
194
  return "failed";
200
195
  }
@@ -276,13 +271,13 @@ export function renderMermaidImage(source: string, width: number): string[] | un
276
271
  }
277
272
  const [, , w, h] = (/viewBox="([^"]+)"/.exec(svg)?.[1] ?? "").split(/\s+/).map(Number);
278
273
  if (!(w && h && w > 0 && h > 0)) return undefined;
279
- // Size from the diagram, like math.ts: its label text lands at one text row.
274
+ // Size from the diagram, like math.ts: its label text lands at ZOOM text rows.
280
275
  const cell = getCellDimensions();
281
- const scale = cell.heightPx / TEXT_PX;
276
+ const scale = (ZOOM * cell.heightPx) / TEXT_PX;
282
277
  let cols = Math.ceil((w * scale) / cell.widthPx);
283
278
  let rows = Math.ceil((h * scale) / cell.heightPx);
284
- // Too wide or tall: shrink to fit; the text gets smaller than a row.
285
- const shrink = Math.min(1, width / cols, MAX_ROWS / rows);
279
+ // Too wide or tall: shrink to fit, frame included; the text gets smaller than a row.
280
+ const shrink = Math.min(1, (width - FRAME_COLS) / cols, MAX_ROWS / rows);
286
281
  cols = Math.max(1, Math.floor(cols * shrink));
287
282
  rows = Math.max(1, Math.floor(rows * shrink));
288
283
  // Rasterise at 2× the displayed height so text and lines stay sharp.
@@ -292,10 +287,11 @@ export function renderMermaidImage(source: string, width: number): string[] | un
292
287
  } catch {
293
288
  return undefined;
294
289
  }
295
- const lines = renderImageRows(Buffer.from(png).toString("base64"), "image/png", width, {
290
+ const image = renderImageRows(Buffer.from(png).toString("base64"), "image/png", width, {
296
291
  maxWidthCells: cols,
297
292
  maxHeightCells: rows,
298
293
  });
294
+ const lines = frameImage(image, width);
299
295
  cache.set(key, lines);
300
296
  if (cache.size > MAX_CACHE) cache.delete(cache.keys().next().value ?? "");
301
297
  return lines;
package/src/tables.ts CHANGED
@@ -1,22 +1,18 @@
1
1
  import { Markdown, sliceByColumn, type Theme, visibleWidth } from "@xynogen/pix-pretty/tui";
2
2
  import type { ExtensionAPI } from "@xynogen/pix-runtime/host";
3
+ import { wrapMethod } from "@xynogen/pix-runtime/patch";
3
4
  import { themeAfterSessionStart } from "./code-blocks.ts";
4
5
 
5
6
  type TableTheme = Pick<Theme, "bold" | "fg">;
6
7
  type Align = "left" | "center" | "right" | null;
7
- type RenderTable = (
8
- this: unknown,
9
- token: { align?: readonly Align[] },
10
- ...rest: unknown[]
11
- ) => string[];
12
8
 
13
- const NATIVE = Symbol.for("@xynogen/pix-display:native-render-table");
14
9
  const CORNERS: Record<string, string> = { "┌": "╭", "┐": "╮", "└": "╰", "┘": "╯" };
10
+ const HEAVY: Record<string, string> = { "├": "┝", "─": "━", "┼": "┿", "┤": "┥" };
15
11
  // Pi pads each cell with plain spaces, sometimes inside its closing style codes.
16
12
  const TRAILING_PAD_RE = /(?: |\x1b\[[0-9;]*m)+$/;
17
- // Same text-style reset Pi uses between wrapped cell fragments; the slice drops a
18
- // style close that sits exactly on the column edge.
19
- const STYLE_RESET = "\x1b[22;23;24;25;27;28;29;39m";
13
+ // Pi's text-style reset between wrapped cell fragments, plus the background: the slice
14
+ // drops a style close that sits exactly on the column edge, such as a badge's tint.
15
+ const STYLE_RESET = "\x1b[22;23;24;25;27;28;29;39;49m";
20
16
 
21
17
  let activeTheme: TableTheme | undefined;
22
18
 
@@ -29,7 +25,8 @@ function alignCell(cell: string, width: number, align: Align | undefined): strin
29
25
  }
30
26
 
31
27
  /**
32
- * Restyle Pi's box table: dim rounded borders, column alignment and an accent header.
28
+ * Restyle Pi's box table: dim rounded borders, column alignment, an accent header and a
29
+ * heavy rule under it.
33
30
  * No background fill: a cell-wide fill overhangs the half-cell `│` borders, and some
34
31
  * themes and terminals show it barely or not at all, so the table looks the same everywhere.
35
32
  */
@@ -50,7 +47,10 @@ export function styleTable(
50
47
  let header = true;
51
48
  return lines.map((line) => {
52
49
  if (!line.startsWith("│")) {
53
- if (line.startsWith("├")) header = false;
50
+ if (header && line.startsWith("├")) {
51
+ header = false;
52
+ return border(line.replace(/[├─┼┤]/g, (c) => HEAVY[c] ?? c));
53
+ }
54
54
  return line && border(line.replace(/^[┌└]|[┐┘]$/g, (c) => CORNERS[c] ?? c));
55
55
  }
56
56
  let col = 2;
@@ -64,18 +64,20 @@ export function styleTable(
64
64
  }
65
65
 
66
66
  function patchTableRenderer(): void {
67
- const prototype = Markdown.prototype;
68
- // Pi's own renderTable, kept on the prototype: /reload loads a new module that must
69
- // replace the previous wrapper, not wrap it or skip patching.
70
- const native: unknown = Reflect.get(prototype, NATIVE) ?? Reflect.get(prototype, "renderTable");
71
67
  // A Pi release without this private method keeps its own table rendering.
72
- if (typeof native !== "function") return;
73
- const renderStyledTable: RenderTable = function renderStyledTable(token, ...rest) {
74
- const lines: string[] = native.call(this, token, ...rest);
75
- return activeTheme ? styleTable(lines, token.align ?? [], activeTheme) : lines;
76
- };
77
- Reflect.set(prototype, NATIVE, native);
78
- Reflect.set(prototype, "renderTable", renderStyledTable);
68
+ wrapMethod(
69
+ Markdown.prototype,
70
+ "renderTable",
71
+ (native) =>
72
+ function renderStyledTable(
73
+ this: unknown,
74
+ token: { align?: readonly Align[] },
75
+ ...rest: unknown[]
76
+ ) {
77
+ const lines: string[] = native.call(this, token, ...rest);
78
+ return activeTheme ? styleTable(lines, token.align ?? [], activeTheme) : lines;
79
+ },
80
+ );
79
81
  }
80
82
 
81
83
  export default function tablesExtension(pi: ExtensionAPI): void {