@xynogen/pix-display 0.3.9 → 0.4.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.
- package/package.json +9 -3
- package/src/code-blocks.ts +13 -9
- package/src/directives.ts +489 -0
- package/src/image.ts +98 -0
- package/src/index.ts +24 -1
- package/src/math.ts +283 -0
- package/src/mermaid.ts +339 -0
- package/src/tables.ts +86 -0
package/src/index.ts
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
* @xynogen/pix-pretty/chips Inline chips (tag format, editor, sent messages)
|
|
9
9
|
* thinking.ts Leaked reasoning tag → native thinking content blocks
|
|
10
10
|
* code-blocks.ts Framed, syntax-highlighted code fences in LLM output
|
|
11
|
+
* directives.ts `::card[…]`, charts and inline directives in LLM output
|
|
12
|
+
* tables.ts Themed Markdown tables with column alignment
|
|
11
13
|
*/
|
|
12
14
|
|
|
13
15
|
import { registerChips } from "@xynogen/pix-pretty/chips";
|
|
@@ -15,14 +17,35 @@ import type { ExtensionAPI } from "@xynogen/pix-runtime/host";
|
|
|
15
17
|
import { once } from "@xynogen/pix-runtime/once";
|
|
16
18
|
|
|
17
19
|
import codeBlocksExtension from "./code-blocks.ts";
|
|
20
|
+
import directivesExtension from "./directives.ts";
|
|
21
|
+
import { hasDisplayMath, offerMathInstall, startMath } from "./math.ts";
|
|
22
|
+
import { hasMermaid, offerMermaidInstall, startMermaid } from "./mermaid.ts";
|
|
23
|
+
import tablesExtension from "./tables.ts";
|
|
18
24
|
import thinkingExtension from "./thinking.ts";
|
|
19
25
|
import workingExtension from "./working.ts";
|
|
20
26
|
|
|
21
|
-
export default function pixDisplayExtension(pi: ExtensionAPI): void {
|
|
27
|
+
export default async function pixDisplayExtension(pi: ExtensionAPI): Promise<void> {
|
|
22
28
|
once(pi, "pix-display", () => {
|
|
23
29
|
registerChips(pi);
|
|
24
30
|
thinkingExtension(pi);
|
|
25
31
|
codeBlocksExtension(pi);
|
|
32
|
+
tablesExtension(pi);
|
|
33
|
+
directivesExtension(pi);
|
|
26
34
|
workingExtension(pi);
|
|
35
|
+
pi.on("agent_end", (event, ctx) => {
|
|
36
|
+
if (ctx.mode !== "tui") return;
|
|
37
|
+
const fail = (what: string) => (err: unknown) =>
|
|
38
|
+
ctx.ui.notify(`${what} install failed: ${String(err)}`, "error");
|
|
39
|
+
// Not awaited: an install prompt must not hold up the next turn. One prompt at a
|
|
40
|
+
// time, so Mermaid waits for the math prompt to finish.
|
|
41
|
+
void (async () => {
|
|
42
|
+
if (hasDisplayMath(event.messages))
|
|
43
|
+
await offerMathInstall(ctx.ui).catch(fail("LaTeX engine"));
|
|
44
|
+
if (hasMermaid(event.messages))
|
|
45
|
+
await offerMermaidInstall(ctx.ui).catch(fail("Mermaid renderer"));
|
|
46
|
+
})();
|
|
47
|
+
});
|
|
27
48
|
});
|
|
49
|
+
// Markdown caches each render, so the engines must be ready before the transcript draws.
|
|
50
|
+
await Promise.all([startMath(), startMermaid()]);
|
|
28
51
|
}
|
package/src/math.ts
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Display math (`$$…$$`, `\[…\]`) in assistant replies, typeset as an image.
|
|
3
|
+
*
|
|
4
|
+
* MathJax turns the TeX into SVG and resvg (WASM) rasterises it to PNG, both in
|
|
5
|
+
* process, so the model writes plain LaTeX and needs no tool call. The image is
|
|
6
|
+
* sized to text height from the formula's own metrics, not stretched to the screen.
|
|
7
|
+
*
|
|
8
|
+
* The engine (~110 MB) is not a dependency: the first reply with display math asks
|
|
9
|
+
* once to install it into `<agentDir>/pix-display/math`, like ast-grep grammars.
|
|
10
|
+
*
|
|
11
|
+
* Pi's Unicode rendering stays whenever an image cannot be shown: no terminal image
|
|
12
|
+
* support, engine not installed or loaded, a TeX error, or a formula wider than the screen.
|
|
13
|
+
*/
|
|
14
|
+
import { dirname, join } from "node:path";
|
|
15
|
+
import { FG_DIM, RST } from "@xynogen/pix-pretty/ansi";
|
|
16
|
+
import { type ConfirmUI, confirmOverlay } from "@xynogen/pix-pretty/confirm";
|
|
17
|
+
import { getCapabilities, getCellDimensions } from "@xynogen/pix-pretty/tui";
|
|
18
|
+
import { readFile } from "@xynogen/pix-runtime/fs";
|
|
19
|
+
import { installIntoPrefix } from "@xynogen/pix-runtime/npm-prefix";
|
|
20
|
+
import { agentDir, importFile, requireFrom } from "@xynogen/pix-runtime/paths";
|
|
21
|
+
import { renderImageRows } from "./image.ts";
|
|
22
|
+
|
|
23
|
+
/** SVG plus its natural size in `ex`, the unit MathJax lays math out in. */
|
|
24
|
+
type Typeset = (tex: string) => { svg: string; widthEx: number; heightEx: number } | undefined;
|
|
25
|
+
type Rasterise = (svg: string, heightPx: number) => Uint8Array;
|
|
26
|
+
|
|
27
|
+
let engine: { typeset: Typeset; rasterise: Rasterise } | undefined;
|
|
28
|
+
let loading: Promise<void> | undefined;
|
|
29
|
+
// True when the engine packages are not installed (not when they fail to load).
|
|
30
|
+
let missing = false;
|
|
31
|
+
let offered = false;
|
|
32
|
+
|
|
33
|
+
// Pinned: the renderer depends on MathJax's SVG output and resvg's API.
|
|
34
|
+
const MATH_PACKAGES = ["@mathjax/src@4.1.3", "@resvg/resvg-wasm@2.6.2"];
|
|
35
|
+
const INSTALL_TIMEOUT_MS = 300_000;
|
|
36
|
+
const CONFIRM_TIMEOUT_MS = 60_000;
|
|
37
|
+
const DISPLAY_MATH = /^ {0,3}(\$\$|\\\[)/m;
|
|
38
|
+
|
|
39
|
+
const FENCE = /^\s*(```|~~~)/;
|
|
40
|
+
const OPEN = /^ {0,3}(\$\$|\\\[)/;
|
|
41
|
+
// Glyph color; resvg needs a concrete color, not currentColor.
|
|
42
|
+
const INK = "#e6e6e6";
|
|
43
|
+
// One `ex` is about half a text row, so text-size math is `heightEx / 2` rows tall.
|
|
44
|
+
const ROWS_PER_EX = 0.5;
|
|
45
|
+
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
|
+
const MAX_CACHE = 32;
|
|
50
|
+
const cache = new Map<string, string[]>();
|
|
51
|
+
|
|
52
|
+
/** Install prefix for the engine packages: `<agentDir>/pix-display/math`. */
|
|
53
|
+
export function mathCacheDir(): string {
|
|
54
|
+
return join(agentDir(), "pix-display", "math");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A `require` that finds both engine packages: the install prefix first, then this package (dev). */
|
|
58
|
+
function engineRequire(): NodeJS.Require | undefined {
|
|
59
|
+
for (const from of [join(mathCacheDir(), "package.json"), import.meta.url]) {
|
|
60
|
+
const req = requireFrom(from);
|
|
61
|
+
try {
|
|
62
|
+
req.resolve("@mathjax/src/mjs/mathjax.js");
|
|
63
|
+
req.resolve("@resvg/resvg-wasm/index_bg.wasm");
|
|
64
|
+
return req;
|
|
65
|
+
} catch (err) {
|
|
66
|
+
if ((err as NodeJS.ErrnoException).code !== "MODULE_NOT_FOUND") throw err;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function load(): Promise<void> {
|
|
73
|
+
const req = engineRequire();
|
|
74
|
+
missing = !req;
|
|
75
|
+
if (!req) return;
|
|
76
|
+
const at = <T>(spec: string): Promise<T> => importFile(req.resolve(spec));
|
|
77
|
+
const wasm = req.resolve("@resvg/resvg-wasm/index_bg.wasm");
|
|
78
|
+
const [{ mathjax }, { TeX }, { SVG }, { liteAdaptor }, { RegisterHTMLHandler }, resvg] =
|
|
79
|
+
await Promise.all([
|
|
80
|
+
at<typeof import("@mathjax/src/mjs/mathjax.js")>("@mathjax/src/mjs/mathjax.js"),
|
|
81
|
+
at<typeof import("@mathjax/src/mjs/input/tex.js")>("@mathjax/src/mjs/input/tex.js"),
|
|
82
|
+
at<typeof import("@mathjax/src/mjs/output/svg.js")>("@mathjax/src/mjs/output/svg.js"),
|
|
83
|
+
at<typeof import("@mathjax/src/mjs/adaptors/liteAdaptor.js")>(
|
|
84
|
+
"@mathjax/src/mjs/adaptors/liteAdaptor.js",
|
|
85
|
+
),
|
|
86
|
+
at<typeof import("@mathjax/src/mjs/handlers/html.js")>("@mathjax/src/mjs/handlers/html.js"),
|
|
87
|
+
// The ESM entry sits beside the WASM file; the package does not export its path.
|
|
88
|
+
importFile<typeof import("@resvg/resvg-wasm")>(join(dirname(wasm), "index.mjs")),
|
|
89
|
+
at("@mathjax/src/mjs/input/tex/base/BaseConfiguration.js"),
|
|
90
|
+
at("@mathjax/src/mjs/input/tex/ams/AmsConfiguration.js"),
|
|
91
|
+
]);
|
|
92
|
+
// Pi's /reload re-runs this module, but Node keeps resvg's module and its WASM
|
|
93
|
+
// instance, which refuses a second init. That instance is ready to use.
|
|
94
|
+
await resvg.initWasm(readFile(wasm)).catch((error: unknown) => {
|
|
95
|
+
if (!String(error).includes("Already initialized")) throw error;
|
|
96
|
+
});
|
|
97
|
+
const adaptor = liteAdaptor();
|
|
98
|
+
RegisterHTMLHandler(adaptor);
|
|
99
|
+
const doc = mathjax.document("", {
|
|
100
|
+
InputJax: new TeX({ packages: ["base", "ams"] }),
|
|
101
|
+
OutputJax: new SVG({ fontCache: "local" }),
|
|
102
|
+
});
|
|
103
|
+
engine = {
|
|
104
|
+
typeset: (tex) => {
|
|
105
|
+
const svg = adaptor.innerHTML(doc.convert(tex, { display: true }));
|
|
106
|
+
// MathJax reports TeX errors inside the SVG instead of throwing.
|
|
107
|
+
if (svg.includes("data-mjx-error")) return undefined;
|
|
108
|
+
const widthEx = Number(/width="([\d.]+)ex"/.exec(svg)?.[1]);
|
|
109
|
+
const heightEx = Number(/height="([\d.]+)ex"/.exec(svg)?.[1]);
|
|
110
|
+
if (!(widthEx > 0 && heightEx > 0)) return undefined;
|
|
111
|
+
return { svg: svg.replaceAll("currentColor", INK), widthEx, heightEx };
|
|
112
|
+
},
|
|
113
|
+
rasterise: (svg, heightPx) =>
|
|
114
|
+
new resvg.Resvg(svg, { fitTo: { mode: "height", value: heightPx } }).render().asPng(),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Load the engine in the background. Called at extension load so it is ready
|
|
120
|
+
* before the first reply; a failure leaves math on Pi's Unicode rendering.
|
|
121
|
+
*/
|
|
122
|
+
export function startMath(): Promise<void> {
|
|
123
|
+
loading ??= load().catch(() => undefined);
|
|
124
|
+
return loading;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
type TextMessage = { role?: string; content?: unknown };
|
|
128
|
+
|
|
129
|
+
/** True when an assistant message has a `$$` or `\[` display-math block. */
|
|
130
|
+
export function hasDisplayMath(messages: readonly TextMessage[]): boolean {
|
|
131
|
+
return messages.some(
|
|
132
|
+
(m) =>
|
|
133
|
+
m.role === "assistant" &&
|
|
134
|
+
Array.isArray(m.content) &&
|
|
135
|
+
m.content.some(
|
|
136
|
+
(b: { type?: string; text?: unknown }) =>
|
|
137
|
+
b?.type === "text" && typeof b.text === "string" && DISPLAY_MATH.test(b.text),
|
|
138
|
+
),
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Ask once per load to install the missing engine, then install it and load it.
|
|
144
|
+
* Skip, a timeout, a loaded engine or no terminal image support asks nothing.
|
|
145
|
+
*/
|
|
146
|
+
export async function offerMathInstall(
|
|
147
|
+
ui: ConfirmUI & { notify(message: string, type?: "info" | "warning" | "error"): void },
|
|
148
|
+
): Promise<void> {
|
|
149
|
+
if (engine || !missing || offered || !getCapabilities().images) return;
|
|
150
|
+
offered = true;
|
|
151
|
+
const ok = await confirmOverlay(ui, {
|
|
152
|
+
title: "Install LaTeX engine",
|
|
153
|
+
body: [
|
|
154
|
+
"This reply has display math. Typeset it as an image needs:",
|
|
155
|
+
...MATH_PACKAGES.map((pkg) => ` ${pkg}`),
|
|
156
|
+
"",
|
|
157
|
+
`Download about 110 MB into ${mathCacheDir()}?`,
|
|
158
|
+
"Skip keeps the plain-text rendering for this session.",
|
|
159
|
+
],
|
|
160
|
+
confirmLabel: "Install",
|
|
161
|
+
denyLabel: "Skip",
|
|
162
|
+
timeoutMs: CONFIRM_TIMEOUT_MS,
|
|
163
|
+
});
|
|
164
|
+
if (!ok) return;
|
|
165
|
+
ui.notify("Installing the LaTeX engine…", "info");
|
|
166
|
+
const result = await installIntoPrefix(mathCacheDir(), MATH_PACKAGES, {
|
|
167
|
+
timeoutMs: INSTALL_TIMEOUT_MS,
|
|
168
|
+
});
|
|
169
|
+
if (!result.ok) {
|
|
170
|
+
ui.notify(`LaTeX engine install failed: ${result.message ?? "unknown error"}`, "error");
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
loading = undefined;
|
|
174
|
+
await startMath();
|
|
175
|
+
ui.notify(
|
|
176
|
+
engine
|
|
177
|
+
? "LaTeX engine ready. New replies show typeset math; /reload redraws earlier ones."
|
|
178
|
+
: "LaTeX engine installed, but it failed to load.",
|
|
179
|
+
engine ? "info" : "error",
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
|
|
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
|
+
/** Image rows for one display formula, or undefined to keep Pi's own rendering. */
|
|
213
|
+
export function renderMath(tex: string, width: number): string[] | undefined {
|
|
214
|
+
if (!engine || !getCapabilities().images) return undefined;
|
|
215
|
+
const key = `${tex}\0${width}`;
|
|
216
|
+
const hit = cache.get(key);
|
|
217
|
+
if (hit) return hit;
|
|
218
|
+
let math: ReturnType<Typeset>;
|
|
219
|
+
try {
|
|
220
|
+
math = engine.typeset(tex);
|
|
221
|
+
} catch {
|
|
222
|
+
math = undefined;
|
|
223
|
+
}
|
|
224
|
+
if (!math) return undefined;
|
|
225
|
+
// Size from the formula, not the screen: Pi's Image fills its width cap otherwise.
|
|
226
|
+
const cell = getCellDimensions();
|
|
227
|
+
const rows = Math.max(1, Math.min(MAX_ROWS, Math.round(math.heightEx * ROWS_PER_EX)));
|
|
228
|
+
const cols = Math.ceil((rows * cell.heightPx * math.widthEx) / math.heightEx / cell.widthPx);
|
|
229
|
+
if (cols > width) return undefined;
|
|
230
|
+
// Rasterise at 2× the displayed height so the glyphs stay sharp.
|
|
231
|
+
const png = engine.rasterise(math.svg, rows * cell.heightPx * 2);
|
|
232
|
+
const image = renderImageRows(Buffer.from(png).toString("base64"), "image/png", width, {
|
|
233
|
+
maxWidthCells: cols,
|
|
234
|
+
maxHeightCells: rows,
|
|
235
|
+
});
|
|
236
|
+
const lines = cols + 2 + 2 * PAD_X <= width ? frame(image, width) : image;
|
|
237
|
+
cache.set(key, lines);
|
|
238
|
+
if (cache.size > MAX_CACHE) cache.delete(cache.keys().next().value ?? "");
|
|
239
|
+
return lines;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Index of the line that closes the block opened on line `start`, or -1. */
|
|
243
|
+
function blockEnd(lines: readonly string[], start: number, closer: string): number {
|
|
244
|
+
const first = (lines[start] ?? "").trim();
|
|
245
|
+
// `$$x$$` or `\[x\]` on one line.
|
|
246
|
+
if (first.length > 2 * closer.length && first.endsWith(closer)) return start;
|
|
247
|
+
for (let j = start + 1; j < lines.length; j++) {
|
|
248
|
+
if ((lines[j] ?? "").trimEnd().endsWith(closer)) return j;
|
|
249
|
+
}
|
|
250
|
+
return -1;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Replace display-math blocks with image rows; anything not rendered keeps its source. */
|
|
254
|
+
export function renderMathBlocks(markdown: string, width: number): string {
|
|
255
|
+
if (!engine || (!markdown.includes("$$") && !markdown.includes("\\["))) return markdown;
|
|
256
|
+
const lines = markdown.split("\n");
|
|
257
|
+
const out: string[] = [];
|
|
258
|
+
let fenced = false;
|
|
259
|
+
for (let i = 0; i < lines.length; i++) {
|
|
260
|
+
const line = lines[i] ?? "";
|
|
261
|
+
if (FENCE.test(line)) fenced = !fenced;
|
|
262
|
+
const opener = fenced ? undefined : OPEN.exec(line)?.[1];
|
|
263
|
+
const closer = opener === "$$" ? "$$" : "\\]";
|
|
264
|
+
const end = opener ? blockEnd(lines, i, closer) : -1;
|
|
265
|
+
const tex =
|
|
266
|
+
end < 0
|
|
267
|
+
? ""
|
|
268
|
+
: lines
|
|
269
|
+
.slice(i, end + 1)
|
|
270
|
+
.join("\n")
|
|
271
|
+
.trim()
|
|
272
|
+
.slice(opener?.length ?? 0, -closer.length)
|
|
273
|
+
.trim();
|
|
274
|
+
const rows = tex ? renderMath(tex, width) : undefined;
|
|
275
|
+
if (!rows) {
|
|
276
|
+
out.push(line);
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
out.push("", ...rows, "");
|
|
280
|
+
i = end;
|
|
281
|
+
}
|
|
282
|
+
return out.join("\n");
|
|
283
|
+
}
|
package/src/mermaid.ts
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mermaid diagrams (```mermaid fences) in assistant replies, drawn as an image.
|
|
3
|
+
*
|
|
4
|
+
* beautiful-mermaid lays the diagram out as SVG with no DOM, and resvg (WASM, shared
|
|
5
|
+
* with math.ts) rasterises it with the Inter font it is designed for. The image is
|
|
6
|
+
* sized from the diagram's own font size, so its text matches a text row.
|
|
7
|
+
*
|
|
8
|
+
* The engine (~17 MB) is not a dependency: the first reply with a diagram asks once to
|
|
9
|
+
* install it into `<agentDir>/pix-display/mermaid`. Installing also turns Pi's own text
|
|
10
|
+
* Mermaid off (`markdown.mermaid: "off"`), because Pi's transformer runs before
|
|
11
|
+
* extensions and would turn the fence into text first. It takes effect after /reload.
|
|
12
|
+
*
|
|
13
|
+
* Without the engine, image support, or a supported diagram, the block falls back to
|
|
14
|
+
* beautiful-mermaid's text drawing, or to the plain code block when that fails too.
|
|
15
|
+
*/
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { type ConfirmUI, confirmOverlay } from "@xynogen/pix-pretty/confirm";
|
|
18
|
+
import { getCapabilities, getCellDimensions } from "@xynogen/pix-pretty/tui";
|
|
19
|
+
import { writeFileAtomicSync } from "@xynogen/pix-runtime/atomic-write";
|
|
20
|
+
import { existsSync, readFile, readFileSync } from "@xynogen/pix-runtime/fs";
|
|
21
|
+
import { installIntoPrefix } from "@xynogen/pix-runtime/npm-prefix";
|
|
22
|
+
import { agentDir, importFile, requireFrom } from "@xynogen/pix-runtime/paths";
|
|
23
|
+
import { renderImageRows } from "./image.ts";
|
|
24
|
+
|
|
25
|
+
type Svg = (source: string) => string;
|
|
26
|
+
type Text = (source: string) => string;
|
|
27
|
+
type Rasterise = (svg: string, heightPx: number) => Uint8Array;
|
|
28
|
+
|
|
29
|
+
let engine: { svg: Svg; text: Text; rasterise: Rasterise } | undefined;
|
|
30
|
+
let loading: Promise<void> | undefined;
|
|
31
|
+
// True when the engine packages are not installed (not when they fail to load).
|
|
32
|
+
let missing = false;
|
|
33
|
+
let offered = false;
|
|
34
|
+
|
|
35
|
+
// Pinned: flatten() depends on beautiful-mermaid's SVG shape; Inter 3 ships TTF.
|
|
36
|
+
const MERMAID_PACKAGES = [
|
|
37
|
+
"beautiful-mermaid@1.1.3",
|
|
38
|
+
"@resvg/resvg-wasm@2.6.2",
|
|
39
|
+
"inter-font@3.19.0",
|
|
40
|
+
];
|
|
41
|
+
const INTER_WEIGHTS = ["Regular", "Medium", "SemiBold", "Bold"];
|
|
42
|
+
const INSTALL_TIMEOUT_MS = 300_000;
|
|
43
|
+
const CONFIRM_TIMEOUT_MS = 60_000;
|
|
44
|
+
|
|
45
|
+
const FENCE = /^ {0,3}(```|~~~)\s*mermaid\s*$/;
|
|
46
|
+
// Tokyo Night, beautiful-mermaid's own palette for Pix's default theme.
|
|
47
|
+
const COLORS = {
|
|
48
|
+
bg: "#1a1b26",
|
|
49
|
+
fg: "#a9b1d6",
|
|
50
|
+
line: "#3d59a1",
|
|
51
|
+
accent: "#7aa2f7",
|
|
52
|
+
muted: "#565f89",
|
|
53
|
+
};
|
|
54
|
+
// Node labels are 13px in beautiful-mermaid's layout: that size becomes one text row.
|
|
55
|
+
const TEXT_PX = 13;
|
|
56
|
+
const MAX_ROWS = 40;
|
|
57
|
+
const MAX_CACHE = 16;
|
|
58
|
+
const cache = new Map<string, string[]>();
|
|
59
|
+
|
|
60
|
+
/** Install prefix for the engine packages: `<agentDir>/pix-display/mermaid`. */
|
|
61
|
+
export function mermaidCacheDir(): string {
|
|
62
|
+
return join(agentDir(), "pix-display", "mermaid");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
type EnginePaths = { mermaid: string; resvg: string; wasm: string; fonts: string };
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Engine files, from the install prefix first, then this package (dev). Each package is
|
|
69
|
+
* resolved on its own: bun keeps every package in a separate folder.
|
|
70
|
+
*/
|
|
71
|
+
function enginePaths(): EnginePaths | undefined {
|
|
72
|
+
for (const base of [mermaidCacheDir(), import.meta.dirname]) {
|
|
73
|
+
const req = requireFrom(join(base, "package.json"));
|
|
74
|
+
try {
|
|
75
|
+
const wasm = req.resolve("@resvg/resvg-wasm/index_bg.wasm");
|
|
76
|
+
const fonts = join(req.resolve("inter-font/ttf/Inter-Regular.ttf"), "..");
|
|
77
|
+
// beautiful-mermaid has no require entry: walk up node_modules like Node does.
|
|
78
|
+
const mermaid = req.resolve
|
|
79
|
+
.paths("beautiful-mermaid")
|
|
80
|
+
?.map((dir) => join(dir, "beautiful-mermaid", "dist", "index.js"))
|
|
81
|
+
.find((file) => existsSync(file));
|
|
82
|
+
if (mermaid) return { mermaid, resvg: join(wasm, "..", "index.mjs"), wasm, fonts };
|
|
83
|
+
} catch (err) {
|
|
84
|
+
if ((err as NodeJS.ErrnoException).code !== "MODULE_NOT_FOUND") throw err;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** `#rrggbb` mixed with another, `pct` percent of the first (CSS color-mix in srgb). */
|
|
91
|
+
function mix(a: string, pct: number, b: string): string {
|
|
92
|
+
const channel = (hex: string, i: number) => Number.parseInt(hex.slice(1 + 2 * i, 3 + 2 * i), 16);
|
|
93
|
+
return `#${[0, 1, 2]
|
|
94
|
+
.map((i) =>
|
|
95
|
+
Math.round((channel(a, i) * pct + channel(b, i) * (100 - pct)) / 100)
|
|
96
|
+
.toString(16)
|
|
97
|
+
.padStart(2, "0"),
|
|
98
|
+
)
|
|
99
|
+
.join("")}`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const VAR = /var\((--[\w-]+)(?:,\s*([^()]*(?:\([^()]*\))?[^()]*))?\)/g;
|
|
103
|
+
const MIX = /color-mix\(in srgb,\s*(#[0-9a-f]{6})\s*(\d+)%,\s*(#[0-9a-f]{6})(?:\s*\d+%)?\)/gi;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Inline the SVG's CSS custom properties and `color-mix()` as hex: resvg evaluates
|
|
107
|
+
* neither. Drops the `<style>` block too, whose web-font `@import` resvg cannot load.
|
|
108
|
+
*/
|
|
109
|
+
export function flattenSvg(svg: string): string {
|
|
110
|
+
const defs = new Map<string, string>();
|
|
111
|
+
for (const m of svg.matchAll(/(--[\w-]+)\s*:\s*([^;"]+)[;"]/g)) {
|
|
112
|
+
if (m[1] && m[2] && !defs.has(m[1])) defs.set(m[1], m[2].trim());
|
|
113
|
+
}
|
|
114
|
+
const resolve = (text: string): string => {
|
|
115
|
+
// Variables nest a few levels deep (`--_line` → `--line` → hex); stop when stable.
|
|
116
|
+
for (let i = 0; i < 8; i++) {
|
|
117
|
+
const next = text
|
|
118
|
+
.replace(VAR, (_, name: string, fallback?: string) => defs.get(name) ?? fallback ?? "none")
|
|
119
|
+
.replace(MIX, (_, a: string, pct: string, b: string) =>
|
|
120
|
+
mix(a.toLowerCase(), Number(pct), b.toLowerCase()),
|
|
121
|
+
);
|
|
122
|
+
if (next === text) return next;
|
|
123
|
+
text = next;
|
|
124
|
+
}
|
|
125
|
+
return text;
|
|
126
|
+
};
|
|
127
|
+
for (const [key, value] of defs) defs.set(key, resolve(value));
|
|
128
|
+
return resolve(svg.replace(/<style>[\s\S]*?<\/style>/, "").replace(/\sstyle="[^"]*"/, ""));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function load(): Promise<void> {
|
|
132
|
+
const paths = enginePaths();
|
|
133
|
+
missing = !paths;
|
|
134
|
+
if (!paths) return;
|
|
135
|
+
const [bm, resvg] = await Promise.all([
|
|
136
|
+
importFile<typeof import("beautiful-mermaid")>(paths.mermaid),
|
|
137
|
+
importFile<typeof import("@resvg/resvg-wasm")>(paths.resvg),
|
|
138
|
+
]);
|
|
139
|
+
// Shared with math.ts: Node keeps one resvg WASM instance, which refuses a second init.
|
|
140
|
+
await resvg.initWasm(readFile(paths.wasm)).catch((error: unknown) => {
|
|
141
|
+
if (!String(error).includes("Already initialized")) throw error;
|
|
142
|
+
});
|
|
143
|
+
const fontBuffers = INTER_WEIGHTS.map((weight) =>
|
|
144
|
+
readFileSync(join(paths.fonts, `Inter-${weight}.ttf`)),
|
|
145
|
+
);
|
|
146
|
+
engine = {
|
|
147
|
+
svg: (source) =>
|
|
148
|
+
flattenSvg(bm.renderMermaidSVG(source, { ...COLORS, transparent: true, padding: 8 })),
|
|
149
|
+
text: (source) => bm.renderMermaidASCII(source),
|
|
150
|
+
rasterise: (svg, heightPx) =>
|
|
151
|
+
new resvg.Resvg(svg, {
|
|
152
|
+
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,
|
|
155
|
+
font: { fontBuffers, defaultFontFamily: "Inter", loadSystemFonts: false },
|
|
156
|
+
})
|
|
157
|
+
.render()
|
|
158
|
+
.asPng(),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Load the engine in the background; a failure keeps the plain code block. */
|
|
163
|
+
export function startMermaid(): Promise<void> {
|
|
164
|
+
loading ??= load().catch(() => undefined);
|
|
165
|
+
return loading;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
type TextMessage = { role?: string; content?: unknown };
|
|
169
|
+
|
|
170
|
+
/** True when an assistant message has a ```mermaid fence. */
|
|
171
|
+
export function hasMermaid(messages: readonly TextMessage[]): boolean {
|
|
172
|
+
return messages.some(
|
|
173
|
+
(m) =>
|
|
174
|
+
m.role === "assistant" &&
|
|
175
|
+
Array.isArray(m.content) &&
|
|
176
|
+
m.content.some(
|
|
177
|
+
(b: { type?: string; text?: unknown }) =>
|
|
178
|
+
b?.type === "text" &&
|
|
179
|
+
typeof b.text === "string" &&
|
|
180
|
+
b.text.split("\n").some((line) => FENCE.test(line)),
|
|
181
|
+
),
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Turn Pi's own text Mermaid off in the user's settings.json, so ```mermaid reaches
|
|
187
|
+
* this extension. Returns "changed", "already" when it was off, or "failed".
|
|
188
|
+
*/
|
|
189
|
+
function disablePiMermaid(): "changed" | "already" | "failed" {
|
|
190
|
+
const path = join(agentDir(), "settings.json");
|
|
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";
|
|
198
|
+
} catch {
|
|
199
|
+
return "failed";
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
type NotifyUI = { notify(message: string, type?: "info" | "warning" | "error"): void };
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* With the engine ready, make sure Pi's text Mermaid is off, and say once that /reload
|
|
207
|
+
* applies it. Covers an engine that was already there (dev, or an earlier install).
|
|
208
|
+
*/
|
|
209
|
+
function handOver(ui: NotifyUI): void {
|
|
210
|
+
const result = disablePiMermaid();
|
|
211
|
+
if (result === "already") return;
|
|
212
|
+
ui.notify(
|
|
213
|
+
result === "changed"
|
|
214
|
+
? 'Pix draws Mermaid now: Pi\'s markdown.mermaid is set to "off". Run /reload to apply.'
|
|
215
|
+
: 'Set "markdown": { "mermaid": "off" } in settings.json, then /reload, so Pix draws Mermaid.',
|
|
216
|
+
result === "changed" ? "info" : "warning",
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Ask once per load to install the missing engine, then install and load it.
|
|
222
|
+
* Skip, a timeout, a loaded engine or no terminal image support asks nothing.
|
|
223
|
+
*/
|
|
224
|
+
export async function offerMermaidInstall(ui: ConfirmUI & NotifyUI): Promise<void> {
|
|
225
|
+
if (offered || !getCapabilities().images) return;
|
|
226
|
+
if (engine) {
|
|
227
|
+
offered = true;
|
|
228
|
+
handOver(ui);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (!missing) return;
|
|
232
|
+
offered = true;
|
|
233
|
+
const ok = await confirmOverlay(ui, {
|
|
234
|
+
title: "Install Mermaid renderer",
|
|
235
|
+
body: [
|
|
236
|
+
"This reply has a Mermaid diagram. Drawing it as an image needs:",
|
|
237
|
+
...MERMAID_PACKAGES.map((pkg) => ` ${pkg}`),
|
|
238
|
+
"",
|
|
239
|
+
`Download about 17 MB into ${mermaidCacheDir()}?`,
|
|
240
|
+
'It also sets Pi\'s markdown.mermaid to "off" so Pix draws the diagrams.',
|
|
241
|
+
"Skip keeps the plain-text rendering for this session.",
|
|
242
|
+
],
|
|
243
|
+
confirmLabel: "Install",
|
|
244
|
+
denyLabel: "Skip",
|
|
245
|
+
timeoutMs: CONFIRM_TIMEOUT_MS,
|
|
246
|
+
});
|
|
247
|
+
if (!ok) return;
|
|
248
|
+
ui.notify("Installing the Mermaid renderer…", "info");
|
|
249
|
+
const result = await installIntoPrefix(mermaidCacheDir(), MERMAID_PACKAGES, {
|
|
250
|
+
timeoutMs: INSTALL_TIMEOUT_MS,
|
|
251
|
+
});
|
|
252
|
+
if (!result.ok) {
|
|
253
|
+
ui.notify(`Mermaid renderer install failed: ${result.message ?? "unknown error"}`, "error");
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
loading = undefined;
|
|
257
|
+
await startMermaid();
|
|
258
|
+
if (!engine) {
|
|
259
|
+
ui.notify("Mermaid renderer installed, but it failed to load.", "error");
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
handOver(ui);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Image rows for one diagram, or undefined when it cannot be drawn as an image. */
|
|
266
|
+
export function renderMermaidImage(source: string, width: number): string[] | undefined {
|
|
267
|
+
if (!engine || !getCapabilities().images) return undefined;
|
|
268
|
+
const key = `${source}\0${width}`;
|
|
269
|
+
const hit = cache.get(key);
|
|
270
|
+
if (hit) return hit;
|
|
271
|
+
let svg: string;
|
|
272
|
+
try {
|
|
273
|
+
svg = engine.svg(source);
|
|
274
|
+
} catch {
|
|
275
|
+
return undefined;
|
|
276
|
+
}
|
|
277
|
+
const [, , w, h] = (/viewBox="([^"]+)"/.exec(svg)?.[1] ?? "").split(/\s+/).map(Number);
|
|
278
|
+
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.
|
|
280
|
+
const cell = getCellDimensions();
|
|
281
|
+
const scale = cell.heightPx / TEXT_PX;
|
|
282
|
+
let cols = Math.ceil((w * scale) / cell.widthPx);
|
|
283
|
+
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);
|
|
286
|
+
cols = Math.max(1, Math.floor(cols * shrink));
|
|
287
|
+
rows = Math.max(1, Math.floor(rows * shrink));
|
|
288
|
+
// Rasterise at 2× the displayed height so text and lines stay sharp.
|
|
289
|
+
let png: Uint8Array;
|
|
290
|
+
try {
|
|
291
|
+
png = engine.rasterise(svg, rows * cell.heightPx * 2);
|
|
292
|
+
} catch {
|
|
293
|
+
return undefined;
|
|
294
|
+
}
|
|
295
|
+
const lines = renderImageRows(Buffer.from(png).toString("base64"), "image/png", width, {
|
|
296
|
+
maxWidthCells: cols,
|
|
297
|
+
maxHeightCells: rows,
|
|
298
|
+
});
|
|
299
|
+
cache.set(key, lines);
|
|
300
|
+
if (cache.size > MAX_CACHE) cache.delete(cache.keys().next().value ?? "");
|
|
301
|
+
return lines;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** beautiful-mermaid's text drawing as a plain code block, or undefined. */
|
|
305
|
+
function renderMermaidText(source: string, width: number): string[] | undefined {
|
|
306
|
+
if (!engine) return undefined;
|
|
307
|
+
let text: string;
|
|
308
|
+
try {
|
|
309
|
+
text = engine.text(source);
|
|
310
|
+
} catch {
|
|
311
|
+
return undefined;
|
|
312
|
+
}
|
|
313
|
+
const lines = text.replace(/\s+$/, "").split("\n");
|
|
314
|
+
if (lines.some((line) => line.length > width)) return undefined;
|
|
315
|
+
return ["```", ...lines, "```"];
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Replace ```mermaid fences with an image, or text when no image can be shown. */
|
|
319
|
+
export function renderMermaidBlocks(markdown: string, width: number): string {
|
|
320
|
+
if (!engine || !markdown.includes("mermaid")) return markdown;
|
|
321
|
+
const lines = markdown.split("\n");
|
|
322
|
+
const out: string[] = [];
|
|
323
|
+
for (let i = 0; i < lines.length; i++) {
|
|
324
|
+
const line = lines[i] ?? "";
|
|
325
|
+
const fence = FENCE.exec(line)?.[1];
|
|
326
|
+
const end = fence ? lines.findIndex((l, j) => j > i && l.trim() === fence) : -1;
|
|
327
|
+
const source = end < 0 ? "" : lines.slice(i + 1, end).join("\n");
|
|
328
|
+
const rows = source.trim()
|
|
329
|
+
? (renderMermaidImage(source, width) ?? renderMermaidText(source, width))
|
|
330
|
+
: undefined;
|
|
331
|
+
if (!rows) {
|
|
332
|
+
out.push(line);
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
out.push("", ...rows, "");
|
|
336
|
+
i = end;
|
|
337
|
+
}
|
|
338
|
+
return out.join("\n");
|
|
339
|
+
}
|