@narumitw/pi-inline 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/LICENSE +21 -0
- package/README.md +129 -2
- package/package.json +47 -4
- package/src/badge.ts +67 -0
- package/src/filelinks.ts +199 -0
- package/src/hover-preview.ts +196 -0
- package/src/image-preview.ts +124 -0
- package/src/image-thumbnail-worker.mjs +27 -0
- package/src/index.ts +1 -0
- package/src/inline-markup-extension.ts +102 -0
- package/src/inline-markup.ts +186 -0
- package/src/prompt.ts +2 -0
- package/src/wikilink-index.ts +103 -0
- package/src/wikilinks.ts +182 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import {
|
|
4
|
+
type Component,
|
|
5
|
+
getOsc8LinkAtColumn,
|
|
6
|
+
type OverlayHandle,
|
|
7
|
+
StdinBuffer,
|
|
8
|
+
type TUI,
|
|
9
|
+
TuiAltScreen,
|
|
10
|
+
} from "@earendil-works/pi-tui";
|
|
11
|
+
import { parseLineRange, readExcerpt, renderFilePreview, resolveLinkPath } from "./filelinks.js";
|
|
12
|
+
import { prepareImagePreview, previewImageMime } from "./image-preview.js";
|
|
13
|
+
import {
|
|
14
|
+
hoverLinkLine,
|
|
15
|
+
renderWikiGroupPreview,
|
|
16
|
+
renderWikiPreview,
|
|
17
|
+
type WikiPreview,
|
|
18
|
+
wikiGroupSourceLimit,
|
|
19
|
+
} from "./wikilinks.js";
|
|
20
|
+
|
|
21
|
+
const HOVER_DELAY_MS = 250;
|
|
22
|
+
const MAX_HEIGHT = 12;
|
|
23
|
+
const MIN_HEIGHT = 4;
|
|
24
|
+
|
|
25
|
+
interface Point {
|
|
26
|
+
row: number;
|
|
27
|
+
col: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface Hover extends Point {
|
|
31
|
+
href: string;
|
|
32
|
+
path?: string;
|
|
33
|
+
preview?: WikiPreview;
|
|
34
|
+
controller: AbortController;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function createHoverPreview(
|
|
38
|
+
tui: TUI,
|
|
39
|
+
theme: Theme,
|
|
40
|
+
cwd: string,
|
|
41
|
+
findWikiPreview: (href: string) => WikiPreview | undefined,
|
|
42
|
+
): Component & { dismiss(): void; dispose(): void } {
|
|
43
|
+
let hover: Hover | undefined;
|
|
44
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
45
|
+
let overlay: OverlayHandle | undefined;
|
|
46
|
+
let viewport: { columns: number; rows: number } | undefined;
|
|
47
|
+
let disposed = false;
|
|
48
|
+
|
|
49
|
+
function hide(): void {
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
hover?.controller.abort();
|
|
52
|
+
hover = undefined;
|
|
53
|
+
overlay?.hide();
|
|
54
|
+
overlay = undefined;
|
|
55
|
+
viewport = undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function linkAt({ row, col }: Point): string | undefined {
|
|
59
|
+
if (!(tui instanceof TuiAltScreen)) return undefined;
|
|
60
|
+
return getOsc8LinkAtColumn(hoverLinkLine(tui.getScreenLines()[row] ?? ""), col);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function stillOnLink(target: Hover): boolean {
|
|
64
|
+
return linkAt(target) === target.href && findWikiPreview(target.href) === target.preview;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function show(target: Hover): Promise<void> {
|
|
68
|
+
const { preview, path, controller } = target;
|
|
69
|
+
const { columns, rows } = tui.terminal;
|
|
70
|
+
const below = rows - target.row - 1;
|
|
71
|
+
const above = target.row;
|
|
72
|
+
const imageMime = !preview && path ? previewImageMime(path) : undefined;
|
|
73
|
+
const placeBelow = below >= above || (!imageMime && below >= MAX_HEIGHT);
|
|
74
|
+
const availableRows = placeBelow ? below : above;
|
|
75
|
+
const width = imageMime ? columns : Math.min(columns, preview ? 56 : 60);
|
|
76
|
+
const height = imageMime ? availableRows : Math.min(availableRows, MAX_HEIGHT);
|
|
77
|
+
if (width < (imageMime ? 2 : preview ? 20 : 16) || height < (imageMime ? 1 : MIN_HEIGHT)) return;
|
|
78
|
+
viewport = { columns, rows };
|
|
79
|
+
|
|
80
|
+
// The image moves its terminal cursor to an absolute column, so use the
|
|
81
|
+
// same column for rendering and placement even if the pointer moves.
|
|
82
|
+
let imageColumn: number | undefined;
|
|
83
|
+
let draw: () => { width: number; lines: string[] } | undefined;
|
|
84
|
+
if (path && imageMime) {
|
|
85
|
+
const image = await prepareImagePreview(cwd, path, imageMime, width, height, controller.signal);
|
|
86
|
+
if (!image) return;
|
|
87
|
+
const column = Math.min(target.col, columns - image.width);
|
|
88
|
+
imageColumn = column;
|
|
89
|
+
draw = () => ({ width: image.width, lines: image.render(column) });
|
|
90
|
+
} else if (preview && "sources" in preview) {
|
|
91
|
+
const candidates = preview.sources.slice(0, wikiGroupSourceLimit(preview.sources.length, height));
|
|
92
|
+
const excerpts = await Promise.all(
|
|
93
|
+
candidates.map((source) => readExcerpt(cwd, resolve(cwd, source), controller.signal)),
|
|
94
|
+
);
|
|
95
|
+
draw = () => renderWikiGroupPreview(preview, excerpts, theme, width, height);
|
|
96
|
+
} else {
|
|
97
|
+
if (!path) return;
|
|
98
|
+
const lineRange = preview ? undefined : parseLineRange(target.href);
|
|
99
|
+
const excerpt = await readExcerpt(cwd, path, controller.signal, lineRange);
|
|
100
|
+
if (!excerpt) return;
|
|
101
|
+
draw = () =>
|
|
102
|
+
preview
|
|
103
|
+
? renderWikiPreview(excerpt, theme, width, height)
|
|
104
|
+
: { width, lines: renderFilePreview(theme, excerpt, width, height) };
|
|
105
|
+
}
|
|
106
|
+
if (hover !== target || tui.hasOverlay() || !stillOnLink(target)) return;
|
|
107
|
+
if (tui.terminal.columns !== columns || tui.terminal.rows !== rows) {
|
|
108
|
+
hide();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const card = draw();
|
|
112
|
+
if (!card?.lines.length) return;
|
|
113
|
+
|
|
114
|
+
let lines = card.lines;
|
|
115
|
+
overlay = tui.showOverlay(
|
|
116
|
+
{
|
|
117
|
+
render: () => lines,
|
|
118
|
+
invalidate() {
|
|
119
|
+
lines = draw()?.lines ?? [];
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
nonCapturing: true,
|
|
124
|
+
width: card.width,
|
|
125
|
+
...(placeBelow ? { row: target.row + 1 } : { anchor: "bottom-left", margin: { bottom: rows - target.row } }),
|
|
126
|
+
col: imageColumn ?? Math.min(target.col, columns - card.width),
|
|
127
|
+
visible: (w, h) => w === columns && h === rows,
|
|
128
|
+
},
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function observe(data: string): void {
|
|
133
|
+
// SGR motion reports with no mouse button pressed. Ignore drag reports.
|
|
134
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: SGR starts with ESC.
|
|
135
|
+
const move = /^\x1b\[<35;(\d+);(\d+)M$/.exec(data);
|
|
136
|
+
if (!move) {
|
|
137
|
+
if (hover) hide();
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const point = { row: Number(move[2]) - 1, col: Number(move[1]) - 1 };
|
|
142
|
+
if (point.col < 0 || point.col >= tui.terminal.columns || point.row < 0 || point.row >= tui.terminal.rows) {
|
|
143
|
+
hide();
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const href = linkAt(point);
|
|
147
|
+
const preview = href ? findWikiPreview(href) : undefined;
|
|
148
|
+
if (hover && href === hover.href && point.row === hover.row && preview === hover.preview) {
|
|
149
|
+
hover.col = point.col;
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
hide();
|
|
153
|
+
if (!href || tui.hasOverlay()) return;
|
|
154
|
+
const path = preview ? ("path" in preview ? preview.path : undefined) : resolveLinkPath(cwd, href);
|
|
155
|
+
if (!preview && !path) return;
|
|
156
|
+
|
|
157
|
+
const target: Hover = { ...point, href, path, preview, controller: new AbortController() };
|
|
158
|
+
hover = target;
|
|
159
|
+
timer = setTimeout(() => void show(target), HOVER_DELAY_MS);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Pi consumes mouse reports before extension input listeners. Observe stdin
|
|
163
|
+
// without replacing Pi's handler, taking focus, or changing terminal modes.
|
|
164
|
+
const input = new StdinBuffer();
|
|
165
|
+
input.on("data", observe);
|
|
166
|
+
input.on("paste", hide);
|
|
167
|
+
const onData = (data: string | Buffer) => {
|
|
168
|
+
if (!disposed && process.stdin.isRaw && tui instanceof TuiAltScreen) input.process(data);
|
|
169
|
+
};
|
|
170
|
+
process.stdin.on("data", onData);
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
dismiss: hide,
|
|
174
|
+
render(): string[] {
|
|
175
|
+
if (hover && viewport) {
|
|
176
|
+
const current = hover;
|
|
177
|
+
const size = viewport;
|
|
178
|
+
// The screen buffer changes after the widget has rendered.
|
|
179
|
+
queueMicrotask(() => {
|
|
180
|
+
if (hover !== current || viewport !== size) return;
|
|
181
|
+
const { columns, rows } = tui.terminal;
|
|
182
|
+
if (columns !== size.columns || rows !== size.rows || !stillOnLink(current)) hide();
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return [];
|
|
186
|
+
},
|
|
187
|
+
invalidate() {},
|
|
188
|
+
dispose() {
|
|
189
|
+
if (disposed) return;
|
|
190
|
+
disposed = true;
|
|
191
|
+
process.stdin.off("data", onData);
|
|
192
|
+
input.destroy();
|
|
193
|
+
hide();
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { extname } from "node:path";
|
|
2
|
+
import { Worker } from "node:worker_threads";
|
|
3
|
+
import {
|
|
4
|
+
allocateImageId,
|
|
5
|
+
getCapabilities,
|
|
6
|
+
getCellDimensions,
|
|
7
|
+
type ImageDimensions,
|
|
8
|
+
renderImage,
|
|
9
|
+
} from "@earendil-works/pi-tui";
|
|
10
|
+
import { openPreviewFile } from "./filelinks.js";
|
|
11
|
+
|
|
12
|
+
type ImageMime = "image/png" | "image/jpeg" | "image/gif" | "image/webp";
|
|
13
|
+
|
|
14
|
+
export function previewImageMime(path: string): ImageMime | undefined {
|
|
15
|
+
switch (extname(path).toLowerCase()) {
|
|
16
|
+
case ".png":
|
|
17
|
+
return "image/png";
|
|
18
|
+
case ".jpg":
|
|
19
|
+
case ".jpeg":
|
|
20
|
+
return "image/jpeg";
|
|
21
|
+
case ".gif":
|
|
22
|
+
return "image/gif";
|
|
23
|
+
case ".webp":
|
|
24
|
+
return "image/webp";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function readImage(cwd: string, path: string, signal: AbortSignal): Promise<Buffer | undefined> {
|
|
29
|
+
const source = await openPreviewFile(cwd, path, signal);
|
|
30
|
+
if (!source) return undefined;
|
|
31
|
+
try {
|
|
32
|
+
if (signal.aborted) return undefined;
|
|
33
|
+
const bytes = await source.file.readFile({ signal });
|
|
34
|
+
if (!signal.aborted && bytes.length === source.size) return bytes;
|
|
35
|
+
} catch {
|
|
36
|
+
// An unreadable or cancelled preview is not shown.
|
|
37
|
+
} finally {
|
|
38
|
+
await source.file.close().catch(() => undefined);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface Thumbnail extends ImageDimensions {
|
|
43
|
+
data: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function resizeForTerminal(
|
|
47
|
+
bytes: Buffer,
|
|
48
|
+
mime: ImageMime,
|
|
49
|
+
maxWidth: number,
|
|
50
|
+
maxHeight: number,
|
|
51
|
+
signal: AbortSignal,
|
|
52
|
+
): Promise<Thumbnail | undefined> {
|
|
53
|
+
const worker = new Worker(new URL("./image-thumbnail-worker.mjs", import.meta.url), {
|
|
54
|
+
workerData: {
|
|
55
|
+
bytes,
|
|
56
|
+
format: mime.slice("image/".length),
|
|
57
|
+
maxWidth,
|
|
58
|
+
maxHeight,
|
|
59
|
+
},
|
|
60
|
+
// Transfer a whole buffer. Do not detach a shared allocation for a slice.
|
|
61
|
+
transferList:
|
|
62
|
+
bytes.buffer instanceof ArrayBuffer && bytes.byteLength === bytes.buffer.byteLength ? [bytes.buffer] : [],
|
|
63
|
+
});
|
|
64
|
+
const result = Promise.withResolvers<Thumbnail | undefined>();
|
|
65
|
+
const abort = () => result.resolve(undefined);
|
|
66
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
67
|
+
worker.once("message", result.resolve);
|
|
68
|
+
worker.on("error", abort);
|
|
69
|
+
worker.once("exit", abort);
|
|
70
|
+
try {
|
|
71
|
+
return await result.promise;
|
|
72
|
+
} finally {
|
|
73
|
+
signal.removeEventListener("abort", abort);
|
|
74
|
+
void worker.terminate().catch(() => undefined);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Prepares a viewport-sized PNG; Pi owns the terminal image placement and cleanup. */
|
|
79
|
+
export async function prepareImagePreview(
|
|
80
|
+
cwd: string,
|
|
81
|
+
path: string,
|
|
82
|
+
mime: ImageMime,
|
|
83
|
+
width: number,
|
|
84
|
+
height: number,
|
|
85
|
+
signal: AbortSignal,
|
|
86
|
+
): Promise<{ width: number; render(column: number): string[] } | undefined> {
|
|
87
|
+
if (width < 2 || height < 1 || getCapabilities().images !== "kitty") return undefined;
|
|
88
|
+
// Pi drops ANSI sequences at the exclusive end of an overlay. Reserve one
|
|
89
|
+
// column after the image to keep the Kitty upload and cursor restore intact.
|
|
90
|
+
const maxWidth = width - 1;
|
|
91
|
+
const bytes = await readImage(cwd, path, signal);
|
|
92
|
+
if (!bytes?.length || signal.aborted) return undefined;
|
|
93
|
+
const cell = getCellDimensions();
|
|
94
|
+
const thumbnail = await resizeForTerminal(bytes, mime, maxWidth * cell.widthPx, height * cell.heightPx, signal).catch(
|
|
95
|
+
() => undefined,
|
|
96
|
+
);
|
|
97
|
+
if (!thumbnail || signal.aborted || getCapabilities().images !== "kitty") return undefined;
|
|
98
|
+
|
|
99
|
+
const currentCell = getCellDimensions();
|
|
100
|
+
const columns = Math.ceil(thumbnail.widthPx / currentCell.widthPx);
|
|
101
|
+
const rows = Math.ceil(thumbnail.heightPx / currentCell.heightPx);
|
|
102
|
+
if (columns > maxWidth || rows > height) return undefined;
|
|
103
|
+
// Register the occupied cells with Pi for redraw and cleanup. Remove the
|
|
104
|
+
// Kitty sizing controls so the terminal displays the PNG at its pixel size.
|
|
105
|
+
const image = renderImage(
|
|
106
|
+
thumbnail.data,
|
|
107
|
+
{ widthPx: columns * currentCell.widthPx, heightPx: rows * currentCell.heightPx },
|
|
108
|
+
{ maxWidthCells: columns, maxHeightCells: rows, imageId: allocateImageId(), moveCursor: false },
|
|
109
|
+
);
|
|
110
|
+
if (!image) return undefined;
|
|
111
|
+
const headerEnd = image.sequence.indexOf(";");
|
|
112
|
+
const sequence = image.sequence.slice(0, headerEnd).replace(/,[cr]=\d+/g, "") + image.sequence.slice(headerEnd);
|
|
113
|
+
return {
|
|
114
|
+
width: columns + 1,
|
|
115
|
+
render(column) {
|
|
116
|
+
if (getCapabilities().images !== "kitty") return [];
|
|
117
|
+
// Clear the covered cells, place the image, and restore the cursor for
|
|
118
|
+
// the compositor's padding and trailing text. Pi preserves CSI G.
|
|
119
|
+
const start = column + 1;
|
|
120
|
+
const firstLine = `${" ".repeat(columns)}\x1b[${start}G${sequence}\x1b[${start + columns}G`;
|
|
121
|
+
return [firstLine, ...Array<string>(rows - 1).fill("")];
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
2
|
+
import sharp from "sharp";
|
|
3
|
+
|
|
4
|
+
function matchesFormat(bytes, format) {
|
|
5
|
+
switch (format) {
|
|
6
|
+
case "png":
|
|
7
|
+
return bytes.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"));
|
|
8
|
+
case "jpeg":
|
|
9
|
+
return bytes[0] === 0xff && bytes[1] === 0xd8;
|
|
10
|
+
case "gif":
|
|
11
|
+
return ["GIF87a", "GIF89a"].includes(bytes.toString("latin1", 0, 6));
|
|
12
|
+
case "webp":
|
|
13
|
+
return bytes.toString("latin1", 0, 4) === "RIFF" && bytes.toString("latin1", 8, 12) === "WEBP";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const { bytes, format, maxWidth, maxHeight } = workerData;
|
|
18
|
+
const input = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
19
|
+
// Only pass the advertised image format to the decoder.
|
|
20
|
+
if (matchesFormat(input, format)) {
|
|
21
|
+
const { data, info } = await sharp(input)
|
|
22
|
+
.autoOrient()
|
|
23
|
+
.resize({ width: maxWidth, height: maxHeight, fit: "inside", withoutEnlargement: true })
|
|
24
|
+
.png()
|
|
25
|
+
.toBuffer({ resolveWithObject: true });
|
|
26
|
+
parentPort.postMessage({ data: data.toString("base64"), widthPx: info.width, heightPx: info.height });
|
|
27
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { inlineMarkupExtension as default } from "./inline-markup-extension.js";
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { TUI } from "@earendil-works/pi-tui";
|
|
3
|
+
import { createHoverPreview } from "./hover-preview.js";
|
|
4
|
+
import { renderInlineMarkup } from "./inline-markup.js";
|
|
5
|
+
import { INLINE_FORMATTING_PROMPT } from "./prompt.js";
|
|
6
|
+
import { createWikilinks } from "./wikilinks.js";
|
|
7
|
+
|
|
8
|
+
const WIDGET_KEY = "pi-inline-markup.preview";
|
|
9
|
+
|
|
10
|
+
interface Session {
|
|
11
|
+
cwd: string;
|
|
12
|
+
theme: Theme;
|
|
13
|
+
tui: TUI;
|
|
14
|
+
dismissPreview(): void;
|
|
15
|
+
wiki?: ReturnType<typeof createWikilinks>;
|
|
16
|
+
menu?: AbortController;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function inlineMarkupExtension(pi: ExtensionAPI): void {
|
|
20
|
+
let session: Session | undefined;
|
|
21
|
+
|
|
22
|
+
pi.on("session_start", (_event, { mode, cwd, ui }) => {
|
|
23
|
+
if (mode !== "tui") return;
|
|
24
|
+
ui.setWidget(
|
|
25
|
+
WIDGET_KEY,
|
|
26
|
+
(tui, theme) => {
|
|
27
|
+
const preview = createHoverPreview(tui, theme, cwd, (href) => current.wiki?.findPreview(href));
|
|
28
|
+
const current: Session = { cwd, theme, tui, dismissPreview: preview.dismiss };
|
|
29
|
+
session = current;
|
|
30
|
+
const widget = {
|
|
31
|
+
...preview,
|
|
32
|
+
dispose() {
|
|
33
|
+
if (session === current) session = undefined;
|
|
34
|
+
current.menu?.abort();
|
|
35
|
+
preview.dispose();
|
|
36
|
+
current.wiki?.dispose();
|
|
37
|
+
current.wiki = undefined;
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
try {
|
|
41
|
+
// Restored messages may have rendered before Pi started the extension.
|
|
42
|
+
tui.invalidate();
|
|
43
|
+
return widget;
|
|
44
|
+
} catch (error) {
|
|
45
|
+
widget.dispose();
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
{ placement: "belowEditor" },
|
|
50
|
+
);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
54
|
+
if (ctx.mode === "tui") ctx.ui.setWidget(WIDGET_KEY, undefined);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
pi.registerCommand("inline-markup", {
|
|
58
|
+
description: "Turn wikilinks on or off for this session",
|
|
59
|
+
async handler(args, ctx) {
|
|
60
|
+
if (args.trim()) throw new Error("Usage: /inline-markup (no arguments)");
|
|
61
|
+
if (ctx.mode !== "tui") throw new Error("/inline-markup is available only in the terminal UI.");
|
|
62
|
+
const current = session;
|
|
63
|
+
if (!current || current.menu) return;
|
|
64
|
+
const menu = new AbortController();
|
|
65
|
+
current.menu = menu;
|
|
66
|
+
try {
|
|
67
|
+
const choice = await ctx.ui.select(`Wikilinks: ${current.wiki ? "On" : "Off"} (this session)`, ["On", "Off"], {
|
|
68
|
+
signal: menu.signal,
|
|
69
|
+
});
|
|
70
|
+
if (session !== current || menu.signal.aborted || (choice !== "On" && choice !== "Off")) return;
|
|
71
|
+
if ((choice === "On") === Boolean(current.wiki)) return;
|
|
72
|
+
|
|
73
|
+
current.dismissPreview();
|
|
74
|
+
if (choice === "On") {
|
|
75
|
+
current.wiki = createWikilinks(current.cwd, () => {
|
|
76
|
+
current.tui.invalidate();
|
|
77
|
+
current.tui.requestRender();
|
|
78
|
+
});
|
|
79
|
+
} else {
|
|
80
|
+
current.wiki?.dispose();
|
|
81
|
+
current.wiki = undefined;
|
|
82
|
+
}
|
|
83
|
+
current.tui.invalidate();
|
|
84
|
+
current.tui.requestRender();
|
|
85
|
+
} finally {
|
|
86
|
+
current.menu = undefined;
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
92
|
+
if (ctx.mode !== "tui" || !session) return;
|
|
93
|
+
event.systemPromptOptions.sections.inline_formatting = INLINE_FORMATTING_PROMPT;
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
// Pi 1.5.0 does not accept messageTypes registration options.
|
|
97
|
+
pi.registerMarkdownTransformer((markdown, { messageType }) => {
|
|
98
|
+
if (!session || (messageType !== "user" && messageType !== "assistant")) return markdown;
|
|
99
|
+
const { cwd, theme, wiki } = session;
|
|
100
|
+
return renderInlineMarkup(markdown, cwd, theme, messageType === "user", wiki);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { getCapabilities, hyperlink, Marked } from "@earendil-works/pi-tui";
|
|
3
|
+
import { cleanBadgeLabel, renderBadge } from "./badge.js";
|
|
4
|
+
import { resolveLinkPath } from "./filelinks.js";
|
|
5
|
+
import type { createWikilinks } from "./wikilinks.js";
|
|
6
|
+
|
|
7
|
+
const START =
|
|
8
|
+
/(?<![![])\[\[\[([^[\]\r\n]+)\]\]\]\(|(?<![![])\[\[([^[\]\r\n]+)\]\](?|\[(?:\\[^\r\n]|[^[\]\\\r\n])+\]\(/g;
|
|
9
|
+
const MARKER = /(\uE000+)(\d+)\uE001/g;
|
|
10
|
+
const BADGE_MARKER = /\[\[(\uE000+)(\d+)\uE001\]\]/g;
|
|
11
|
+
const WORD_JOINER = "\u2060";
|
|
12
|
+
const parser = new Marked();
|
|
13
|
+
|
|
14
|
+
interface MarkupStart {
|
|
15
|
+
offset: number;
|
|
16
|
+
end: number;
|
|
17
|
+
taggedOffset: number;
|
|
18
|
+
marker: string;
|
|
19
|
+
badge?: string;
|
|
20
|
+
linkedBadge?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface Replacement {
|
|
24
|
+
offset: number;
|
|
25
|
+
end: number;
|
|
26
|
+
text: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function asCodeSpan(text: string): string {
|
|
30
|
+
// Carry ANSI styling through Pi's Markdown renderer without parsing the label.
|
|
31
|
+
let ticks = 1;
|
|
32
|
+
for (const [run] of text.matchAll(/`+/g)) ticks = Math.max(ticks, run.length + 1);
|
|
33
|
+
const fence = "`".repeat(ticks);
|
|
34
|
+
return fence + text + fence;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function renderFileLabel(label: string, href: string, theme: Theme, inlineCode: boolean): string {
|
|
38
|
+
const text = inlineCode
|
|
39
|
+
? theme.fg("mdLink", "📄\u00a0") + theme.fg("mdCode", label)
|
|
40
|
+
: theme.fg("mdLink", `📄\u00a0${label}`);
|
|
41
|
+
return getCapabilities().hyperlinks ? hyperlink(text, href) : text;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function isEscaped(source: string, offset: number): boolean {
|
|
45
|
+
let start = offset;
|
|
46
|
+
while (source[start - 1] === "\\") start--;
|
|
47
|
+
return (offset - start) % 2 === 1;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isWrappedLink(source: string, offset: number, end: number): boolean {
|
|
51
|
+
return (
|
|
52
|
+
offset >= 2 &&
|
|
53
|
+
source.startsWith("[[", offset - 2) &&
|
|
54
|
+
source.startsWith("]]", end) &&
|
|
55
|
+
source[offset - 3] !== "[" &&
|
|
56
|
+
source[offset - 3] !== "!" &&
|
|
57
|
+
source[end + 2] !== "]" &&
|
|
58
|
+
source[end + 2] !== "(" &&
|
|
59
|
+
!isEscaped(source, offset - 2)
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Styles prose badges and local Markdown links without changing their destinations. */
|
|
64
|
+
export function renderInlineMarkup(
|
|
65
|
+
markdown: string,
|
|
66
|
+
root: string,
|
|
67
|
+
theme: Theme,
|
|
68
|
+
userMessage: boolean,
|
|
69
|
+
wiki?: ReturnType<typeof createWikilinks>,
|
|
70
|
+
): string {
|
|
71
|
+
if (!markdown.includes("[[") && !markdown.includes("](")) return markdown;
|
|
72
|
+
|
|
73
|
+
// Tag each occurrence so the lexer can separate prose from code, link titles, and image labels.
|
|
74
|
+
let prefix = "\uE000";
|
|
75
|
+
while (markdown.includes(prefix)) prefix += "\uE000";
|
|
76
|
+
const starts: MarkupStart[] = [];
|
|
77
|
+
let added = 0;
|
|
78
|
+
const tagged = markdown.replace(
|
|
79
|
+
START,
|
|
80
|
+
(raw, linkedBadge: string | undefined, badge: string | undefined, offset: number) => {
|
|
81
|
+
if (markdown.charCodeAt(offset - 1) === 0x1b || isEscaped(markdown, offset)) return raw;
|
|
82
|
+
const marker = `${prefix}${starts.length}\uE001`;
|
|
83
|
+
starts.push({ offset, end: offset + raw.length, taggedOffset: offset + added, marker, badge, linkedBadge });
|
|
84
|
+
// Present `[ [[label]] ](path)` without the inner brackets to Marked.
|
|
85
|
+
const replacement =
|
|
86
|
+
linkedBadge !== undefined
|
|
87
|
+
? `[${marker}](`
|
|
88
|
+
: badge !== undefined
|
|
89
|
+
? `[[${marker}]]`
|
|
90
|
+
: `[${marker}${raw.slice(1)}`;
|
|
91
|
+
added += replacement.length - raw.length;
|
|
92
|
+
return replacement;
|
|
93
|
+
},
|
|
94
|
+
);
|
|
95
|
+
if (!starts.length) return markdown;
|
|
96
|
+
|
|
97
|
+
const untag = (text: string) =>
|
|
98
|
+
text.replace(MARKER, (tag, marker: string, id: string) => {
|
|
99
|
+
if (marker !== prefix) return tag;
|
|
100
|
+
const { badge, linkedBadge } = starts[Number(id)];
|
|
101
|
+
return linkedBadge === undefined ? (badge ?? "") : `[[${linkedBadge}]]`;
|
|
102
|
+
});
|
|
103
|
+
const proseBadges = new Set<number>();
|
|
104
|
+
const blocked = new Set<number>();
|
|
105
|
+
const replacements = new Map<number, Replacement>();
|
|
106
|
+
parser.walkTokens(parser.lexer(tagged), (token) => {
|
|
107
|
+
if (token.type === "text" && !token.tokens && !token.escaped) {
|
|
108
|
+
for (const [, marker, id] of token.raw.matchAll(BADGE_MARKER)) {
|
|
109
|
+
if (marker === prefix) proseBadges.add(Number(id));
|
|
110
|
+
}
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (token.type !== "link" && token.type !== "image") return;
|
|
115
|
+
for (const [, marker, id] of token.raw.matchAll(MARKER)) {
|
|
116
|
+
if (marker === prefix && (token.type === "image" || starts[Number(id)].badge !== undefined))
|
|
117
|
+
blocked.add(Number(id));
|
|
118
|
+
}
|
|
119
|
+
if (token.type !== "link") return;
|
|
120
|
+
|
|
121
|
+
const match = /^\[(\uE000+)(\d+)\uE001/.exec(token.raw);
|
|
122
|
+
if (!match || match[1] !== prefix) return;
|
|
123
|
+
const id = Number(match[2]);
|
|
124
|
+
const start = starts[id];
|
|
125
|
+
if (!start || start.badge !== undefined || !tagged.startsWith(token.raw, start.taggedOffset)) return;
|
|
126
|
+
const href = untag(token.href);
|
|
127
|
+
if (!token.text.startsWith(start.marker) || !resolveLinkPath(root, href)) return;
|
|
128
|
+
const { offset } = start;
|
|
129
|
+
const end = offset + untag(token.raw).length;
|
|
130
|
+
if (start.linkedBadge !== undefined) {
|
|
131
|
+
const label = cleanBadgeLabel(start.linkedBadge);
|
|
132
|
+
if (label) replacements.set(id, { offset, end, text: renderBadge(label, theme, userMessage, href) });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const parts = token.tokens;
|
|
136
|
+
if (!parts) return;
|
|
137
|
+
const [marker, span] = parts;
|
|
138
|
+
const code =
|
|
139
|
+
parts.length === 2 && marker?.type === "text" && marker.text === start.marker && span?.type === "codespan"
|
|
140
|
+
? span.text
|
|
141
|
+
: undefined;
|
|
142
|
+
// Leave other rich labels to Pi.
|
|
143
|
+
if (code === undefined && parts.some(({ type }) => type !== "text" && type !== "escape")) return;
|
|
144
|
+
const label =
|
|
145
|
+
code ??
|
|
146
|
+
parts
|
|
147
|
+
.map((part) => ("text" in part ? part.text : ""))
|
|
148
|
+
.join("")
|
|
149
|
+
.slice(start.marker.length)
|
|
150
|
+
.trim();
|
|
151
|
+
if (!label || /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/u.test(label)) return;
|
|
152
|
+
const wrapped = isWrappedLink(markdown, offset, end);
|
|
153
|
+
replacements.set(id, {
|
|
154
|
+
offset: wrapped ? offset - 2 : offset,
|
|
155
|
+
end: wrapped ? end + 2 : end,
|
|
156
|
+
text: wrapped
|
|
157
|
+
? renderBadge(label, theme, userMessage, href)
|
|
158
|
+
: renderFileLabel(label, href, theme, code !== undefined),
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
let result = "";
|
|
163
|
+
let cursor = 0;
|
|
164
|
+
for (const [id, start] of starts.entries()) {
|
|
165
|
+
if (blocked.has(id)) continue;
|
|
166
|
+
let replacement = replacements.get(id);
|
|
167
|
+
if (start.badge !== undefined && proseBadges.has(id)) {
|
|
168
|
+
const note = wiki?.resolve(start.badge);
|
|
169
|
+
const label = cleanBadgeLabel(note?.label ?? start.badge);
|
|
170
|
+
if (label) {
|
|
171
|
+
replacement = {
|
|
172
|
+
offset: start.offset,
|
|
173
|
+
end: start.end,
|
|
174
|
+
text: renderBadge(label, theme, userMessage, note?.href, note?.groupId),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (!replacement || replacement.offset < cursor) continue;
|
|
179
|
+
result += markdown.slice(cursor, replacement.offset);
|
|
180
|
+
if (result.endsWith("`")) result += WORD_JOINER;
|
|
181
|
+
result += asCodeSpan(replacement.text);
|
|
182
|
+
cursor = replacement.end;
|
|
183
|
+
if (markdown[cursor] === "`") result += WORD_JOINER;
|
|
184
|
+
}
|
|
185
|
+
return result + markdown.slice(cursor);
|
|
186
|
+
}
|
package/src/prompt.ts
ADDED