@narumitw/pi-inline 0.3.0 → 0.4.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 +10 -0
- package/README.md +35 -9
- package/package.json +1 -1
- package/src/external-link-marker.ts +25 -0
- package/src/filelinks.ts +55 -14
- package/src/hover-preview.ts +58 -15
- package/src/inline-markup-extension.ts +35 -7
- package/src/inline-markup.ts +16 -10
- package/src/preview-settings.ts +52 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# @narumitw/pi-inline
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 2722e8a: Style explicit Markdown file links outside the workspace. Allow bounded text previews in approved directories when users set `externalPreviewRoots` in their user settings. External previews remain off by default.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- 913bf63: Show a picture icon on ordinary Markdown file links to PNG, JPEG, GIF, and WebP paths. Other file icons, linked badges, and hover preview rules stay the same.
|
|
12
|
+
|
|
3
13
|
## 0.3.0
|
|
4
14
|
|
|
5
15
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ Style badges and preview local file citations in Pi's terminal transcript withou
|
|
|
8
8
|
## ✨ Features
|
|
9
9
|
|
|
10
10
|
- Display decorative badges, linked badges, and local Markdown links in user and assistant messages.
|
|
11
|
-
- Hover over a file link in fullscreen mode to preview
|
|
11
|
+
- Hover over a file link in fullscreen mode to preview a workspace image or text file, or text in an approved external directory.
|
|
12
12
|
- Turn on filename lookup for wikilinks in the current session.
|
|
13
13
|
|
|
14
14
|
## 📦 Install
|
|
@@ -64,16 +64,18 @@ stops file indexing and closes any open preview.
|
|
|
64
64
|
[[[README](./README.md)]]
|
|
65
65
|
[[[README]]](./README.md)
|
|
66
66
|
[`runTests()`](./scripts/run-tests.mjs#L12-L20)
|
|
67
|
+
[rename plan](/home/alex/.agents/plans/rename%20plan.md#L2-L5)
|
|
67
68
|
```
|
|
68
69
|
|
|
69
70
|
- `[[label]]` is decorative unless you enable wikilinks. With wikilinks off, the
|
|
70
71
|
badge does not look up, open, or preview a file.
|
|
71
72
|
- The two linked badge forms are equivalent. Both use standard local Markdown
|
|
72
73
|
destinations and support hover previews whether or not wikilinks are enabled.
|
|
73
|
-
- Ordinary Markdown links use
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
Encode spaces
|
|
74
|
+
- Ordinary Markdown file links use an image icon (🖼️) for PNG, JPEG, GIF, and
|
|
75
|
+
WebP paths and a file icon (📄) for other paths. Use a plain-text or inline-code
|
|
76
|
+
label with an absolute path or a path relative to Pi's working directory.
|
|
77
|
+
Paths can point outside that directory, including with `../`. Encode spaces
|
|
78
|
+
as `%20`. The icon does not indicate that a file exists or has a preview.
|
|
77
79
|
- Use `#L12` for one source line or `#L12-L20` for an inclusive range. Hover also
|
|
78
80
|
accepts `#L12-20`. These previews show literal source rather than rendered Markdown.
|
|
79
81
|
|
|
@@ -86,12 +88,36 @@ files match, the badge previews files but is not clickable. Unresolved names
|
|
|
86
88
|
also stay non-clickable. The index skips hidden paths, starts on first lookup,
|
|
87
89
|
and refreshes five seconds after each scan.
|
|
88
90
|
|
|
91
|
+
## ⚙️ Settings
|
|
92
|
+
|
|
93
|
+
To allow external text previews, edit the user file `pi-inline.json` in Pi's agent
|
|
94
|
+
directory (by default `~/.pi/agent/`):
|
|
95
|
+
|
|
96
|
+
```json
|
|
97
|
+
{
|
|
98
|
+
"externalPreviewRoots": ["/home/alex/.agents/plans"]
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
A conversation link can trigger a file read inside an approved directory when
|
|
103
|
+
you hover over it. Approve only narrow directories you control, not shared
|
|
104
|
+
directories. Use existing absolute directories without symbolic links. Do not
|
|
105
|
+
use globs, a filesystem root, your home directory, or a directory that contains
|
|
106
|
+
your home directory.
|
|
107
|
+
|
|
108
|
+
The default is `[]` and project settings are ignored. Invalid or unreadable
|
|
109
|
+
settings leave external previews off. Use a regular file, not a symbolic link.
|
|
110
|
+
Changes take effect on session start or
|
|
111
|
+
`/reload`. To revoke access, remove the field or set it to `[]`, then run
|
|
112
|
+
`/reload`. Link icons do not depend on this setting.
|
|
113
|
+
|
|
89
114
|
## 🔒 Security and privacy
|
|
90
115
|
|
|
91
|
-
|
|
92
|
-
`node_modules
|
|
93
|
-
|
|
94
|
-
The extension does not add
|
|
116
|
+
Hover can show hidden files, including files that contain secrets. Previews
|
|
117
|
+
exclude `node_modules` and symbolic links. External previews are text-only.
|
|
118
|
+
External PNG, JPEG, GIF, and WebP links can be opened but never start an image
|
|
119
|
+
preview. The extension does not add preview contents to model context or
|
|
120
|
+
stored messages.
|
|
95
121
|
|
|
96
122
|
In the terminal UI, the extension adds a fixed system prompt hint about badge
|
|
97
123
|
labels and Markdown file citations. The hint uses a placeholder path and contains
|
package/package.json
CHANGED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
2
|
+
import { getOsc8LinkAtColumn } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
// Match Pi's OSC 8 parameters, URL, and terminator without changing cell widths.
|
|
5
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: OSC 8 uses ESC and BEL.
|
|
6
|
+
const OSC_8 = /\x1b\]8;([^;\x07\x1b]*);([^\x07\x1b]*)(\x07|\x1b\\)/g;
|
|
7
|
+
|
|
8
|
+
/** Proves that an external hover target came from this session's Markdown renderer. */
|
|
9
|
+
export function createExternalLinkMarker() {
|
|
10
|
+
const key = randomBytes(32);
|
|
11
|
+
const id = (href: string) => `id=pi-inline-external-${createHmac("sha256", key).update(href).digest("hex")}`;
|
|
12
|
+
return {
|
|
13
|
+
mark(text: string, href: string): string {
|
|
14
|
+
// Set OSC 8 metadata, not the click destination.
|
|
15
|
+
return text.startsWith("\x1b]8;;") ? text.replace("\x1b]8;;", `\x1b]8;${id(href)};`) : text;
|
|
16
|
+
},
|
|
17
|
+
matches(line: string, column: number, href: string): boolean {
|
|
18
|
+
const expected = id(href);
|
|
19
|
+
const marked = line.replace(OSC_8, (sequence, params: string, url: string, end: string) =>
|
|
20
|
+
params === expected && url === href ? sequence : `\x1b]8;;${end}`,
|
|
21
|
+
);
|
|
22
|
+
return getOsc8LinkAtColumn(marked, column) === href;
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
}
|
package/src/filelinks.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { constants } from "node:fs";
|
|
1
|
+
import { type BigIntStats, constants } from "node:fs";
|
|
2
2
|
import { lstat, open, realpath } from "node:fs/promises";
|
|
3
3
|
import { basename, isAbsolute, relative, resolve, sep } from "node:path";
|
|
4
4
|
import { getMarkdownTheme, type Theme } from "@earendil-works/pi-coding-agent";
|
|
@@ -21,14 +21,19 @@ export interface PreviewExcerpt {
|
|
|
21
21
|
lineRange?: LineRange;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
export interface ExternalPreviewRoot {
|
|
25
|
+
path: string;
|
|
26
|
+
identity: Pick<BigIntStats, "dev" | "ino">;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function relativePreviewPath(root: string, path: string): string | undefined {
|
|
25
30
|
const local = relative(root, path);
|
|
26
31
|
if (!local || isAbsolute(local) || local === ".." || local.startsWith(`..${sep}`)) return undefined;
|
|
27
32
|
if (local.split(sep).includes("node_modules")) return undefined;
|
|
28
33
|
return local;
|
|
29
34
|
}
|
|
30
35
|
|
|
31
|
-
|
|
36
|
+
function localLinkPath(root: string, href: string): string | undefined {
|
|
32
37
|
// Interpret Markdown destinations as filesystem paths, not as URLs to fetch.
|
|
33
38
|
// Leave URI schemes (including file:) and protocol-relative links to Pi.
|
|
34
39
|
const invalid = /[\\\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/u;
|
|
@@ -38,13 +43,28 @@ export function resolveLinkPath(root: string, href: string): string | undefined
|
|
|
38
43
|
const path = decodeURIComponent(encoded);
|
|
39
44
|
if (!path || path.startsWith("//") || invalid.test(path)) return undefined;
|
|
40
45
|
if (/^[a-z][a-z\d+.-]*:/i.test(path) && !isAbsolute(path)) return undefined;
|
|
41
|
-
|
|
42
|
-
return workspacePath(root, target) ? target : undefined;
|
|
46
|
+
return resolve(root, path);
|
|
43
47
|
} catch {
|
|
44
48
|
return undefined; // Malformed percent escape.
|
|
45
49
|
}
|
|
46
50
|
}
|
|
47
51
|
|
|
52
|
+
export function resolveLinkPath(root: string, href: string): string | undefined {
|
|
53
|
+
const path = localLinkPath(root, href);
|
|
54
|
+
return path && relativePreviewPath(root, path) ? path : undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Classifies local links for display without checking whether a file exists. */
|
|
58
|
+
export function classifyLinkPath(
|
|
59
|
+
root: string,
|
|
60
|
+
href: string,
|
|
61
|
+
): { kind: "workspace" | "external"; path: string } | undefined {
|
|
62
|
+
const path = localLinkPath(root, href);
|
|
63
|
+
if (!path || path === resolve(root)) return undefined;
|
|
64
|
+
if (relativePreviewPath(root, path)) return { kind: "workspace", path };
|
|
65
|
+
return path.split(sep).includes("node_modules") ? undefined : { kind: "external", path };
|
|
66
|
+
}
|
|
67
|
+
|
|
48
68
|
export function parseLineRange(href: string): LineRange | undefined {
|
|
49
69
|
const match = /#L([1-9]\d*)(?:-L?([1-9]\d*))?$/.exec(href);
|
|
50
70
|
if (!match || match.index !== href.indexOf("#")) return undefined;
|
|
@@ -78,27 +98,48 @@ function selectLines(
|
|
|
78
98
|
};
|
|
79
99
|
}
|
|
80
100
|
|
|
81
|
-
|
|
82
|
-
|
|
101
|
+
function sameFile(a: ExternalPreviewRoot["identity"], b: ExternalPreviewRoot["identity"]): boolean {
|
|
102
|
+
return a.dev === b.dev && a.ino === b.ino;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function isCurrentRoot(root: ExternalPreviewRoot, signal: AbortSignal): Promise<boolean> {
|
|
106
|
+
if (signal.aborted || (await realpath(root.path)) !== root.path || signal.aborted) return false;
|
|
107
|
+
const stat = await lstat(root.path, { bigint: true });
|
|
108
|
+
return !signal.aborted && stat.isDirectory() && sameFile(stat, root.identity);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Opens a regular preview file without following symlinks. The caller owns the handle. */
|
|
112
|
+
export async function openPreviewFile(root: string | ExternalPreviewRoot, path: string, signal: AbortSignal) {
|
|
83
113
|
try {
|
|
84
|
-
const
|
|
114
|
+
const external = typeof root === "string" ? undefined : root;
|
|
115
|
+
const rootPath = typeof root === "string" ? root : root.path;
|
|
116
|
+
const local = relativePreviewPath(rootPath, path);
|
|
85
117
|
if (!local || signal.aborted) return undefined;
|
|
86
|
-
|
|
118
|
+
if (external && !(await isCurrentRoot(external, signal))) return undefined;
|
|
119
|
+
const directory = external ? rootPath : await realpath(rootPath);
|
|
87
120
|
if (signal.aborted) return undefined;
|
|
88
|
-
const candidate = resolve(
|
|
121
|
+
const candidate = resolve(directory, local);
|
|
89
122
|
if ((await realpath(candidate)) !== candidate || signal.aborted) return undefined;
|
|
90
|
-
|
|
123
|
+
const verified = await lstat(candidate, { bigint: true });
|
|
124
|
+
if (!verified.isFile() || signal.aborted) return undefined;
|
|
125
|
+
if (external && !(await isCurrentRoot(external, signal))) return undefined;
|
|
126
|
+
if (signal.aborted) return undefined;
|
|
91
127
|
|
|
92
128
|
const file = await open(candidate, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
93
129
|
let keepOpen = false;
|
|
94
130
|
try {
|
|
95
131
|
if (signal.aborted) return undefined;
|
|
96
|
-
const stat = await file.stat();
|
|
132
|
+
const stat = await file.stat({ bigint: true });
|
|
97
133
|
if (signal.aborted || !stat.isFile()) return undefined;
|
|
134
|
+
// Do not read a different file if the target changed between lstat and open.
|
|
135
|
+
if (external) {
|
|
136
|
+
if (!sameFile(verified, stat) || !(await isCurrentRoot(external, signal)) || signal.aborted) return undefined;
|
|
137
|
+
if ((await realpath(candidate)) !== candidate || signal.aborted) return undefined;
|
|
138
|
+
}
|
|
98
139
|
keepOpen = true;
|
|
99
140
|
return {
|
|
100
141
|
file,
|
|
101
|
-
size: stat.size,
|
|
142
|
+
size: Number(stat.size),
|
|
102
143
|
filename: basename(candidate).replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/gu, " "),
|
|
103
144
|
};
|
|
104
145
|
} finally {
|
|
@@ -111,7 +152,7 @@ export async function openPreviewFile(root: string, path: string, signal: AbortS
|
|
|
111
152
|
}
|
|
112
153
|
|
|
113
154
|
export async function readExcerpt(
|
|
114
|
-
root: string,
|
|
155
|
+
root: string | ExternalPreviewRoot,
|
|
115
156
|
path: string,
|
|
116
157
|
signal: AbortSignal,
|
|
117
158
|
lineRange?: LineRange,
|
package/src/hover-preview.ts
CHANGED
|
@@ -8,7 +8,16 @@ import {
|
|
|
8
8
|
type TUI,
|
|
9
9
|
TuiAltScreen,
|
|
10
10
|
} from "@earendil-works/pi-tui";
|
|
11
|
-
import {
|
|
11
|
+
import type { createExternalLinkMarker } from "./external-link-marker.js";
|
|
12
|
+
import {
|
|
13
|
+
classifyLinkPath,
|
|
14
|
+
type ExternalPreviewRoot,
|
|
15
|
+
parseLineRange,
|
|
16
|
+
readExcerpt,
|
|
17
|
+
relativePreviewPath,
|
|
18
|
+
renderFilePreview,
|
|
19
|
+
resolveLinkPath,
|
|
20
|
+
} from "./filelinks.js";
|
|
12
21
|
import { prepareImagePreview, previewImageMime } from "./image-preview.js";
|
|
13
22
|
import {
|
|
14
23
|
hoverLinkLine,
|
|
@@ -30,6 +39,7 @@ interface Point {
|
|
|
30
39
|
interface Hover extends Point {
|
|
31
40
|
href: string;
|
|
32
41
|
path?: string;
|
|
42
|
+
externalRoot?: ExternalPreviewRoot;
|
|
33
43
|
preview?: WikiPreview;
|
|
34
44
|
controller: AbortController;
|
|
35
45
|
}
|
|
@@ -39,6 +49,10 @@ export function createHoverPreview(
|
|
|
39
49
|
theme: Theme,
|
|
40
50
|
cwd: string,
|
|
41
51
|
findWikiPreview: (href: string) => WikiPreview | undefined,
|
|
52
|
+
external: {
|
|
53
|
+
marker: ReturnType<typeof createExternalLinkMarker>;
|
|
54
|
+
roots(): readonly ExternalPreviewRoot[];
|
|
55
|
+
},
|
|
42
56
|
): Component & { dismiss(): void; dispose(): void } {
|
|
43
57
|
let hover: Hover | undefined;
|
|
44
58
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -55,27 +69,41 @@ export function createHoverPreview(
|
|
|
55
69
|
viewport = undefined;
|
|
56
70
|
}
|
|
57
71
|
|
|
58
|
-
function
|
|
59
|
-
|
|
60
|
-
return getOsc8LinkAtColumn(hoverLinkLine(tui.getScreenLines()[row] ?? ""), col);
|
|
72
|
+
function screenLine(row: number): string {
|
|
73
|
+
return tui instanceof TuiAltScreen ? (tui.getScreenLines()[row] ?? "") : "";
|
|
61
74
|
}
|
|
62
75
|
|
|
63
|
-
function stillOnLink(
|
|
64
|
-
|
|
76
|
+
function stillOnLink({ row, col, href, preview, externalRoot }: Hover): boolean {
|
|
77
|
+
const line = screenLine(row);
|
|
78
|
+
return (
|
|
79
|
+
getOsc8LinkAtColumn(hoverLinkLine(line), col) === href &&
|
|
80
|
+
findWikiPreview(href) === preview &&
|
|
81
|
+
(!externalRoot || external.marker.matches(line, col, href))
|
|
82
|
+
);
|
|
65
83
|
}
|
|
66
84
|
|
|
67
85
|
async function show(target: Hover): Promise<void> {
|
|
68
|
-
const { preview, path, controller } = target;
|
|
86
|
+
const { preview, path, controller, externalRoot } = target;
|
|
87
|
+
if (hover !== target) return;
|
|
88
|
+
if (
|
|
89
|
+
!viewport ||
|
|
90
|
+
viewport.columns !== tui.terminal.columns ||
|
|
91
|
+
viewport.rows !== tui.terminal.rows ||
|
|
92
|
+
tui.hasOverlay() ||
|
|
93
|
+
!stillOnLink(target)
|
|
94
|
+
) {
|
|
95
|
+
hide();
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
69
98
|
const { columns, rows } = tui.terminal;
|
|
70
99
|
const below = rows - target.row - 1;
|
|
71
100
|
const above = target.row;
|
|
72
|
-
const imageMime = !preview && path ? previewImageMime(path) : undefined;
|
|
101
|
+
const imageMime = !externalRoot && !preview && path ? previewImageMime(path) : undefined;
|
|
73
102
|
const placeBelow = below >= above || (!imageMime && below >= MAX_HEIGHT);
|
|
74
103
|
const availableRows = placeBelow ? below : above;
|
|
75
104
|
const width = imageMime ? columns : Math.min(columns, preview ? 56 : 60);
|
|
76
105
|
const height = imageMime ? availableRows : Math.min(availableRows, MAX_HEIGHT);
|
|
77
106
|
if (width < (imageMime ? 2 : preview ? 20 : 16) || height < (imageMime ? 1 : MIN_HEIGHT)) return;
|
|
78
|
-
viewport = { columns, rows };
|
|
79
107
|
|
|
80
108
|
// The image moves its terminal cursor to an absolute column, so use the
|
|
81
109
|
// same column for rendering and placement even if the pointer moves.
|
|
@@ -96,7 +124,7 @@ export function createHoverPreview(
|
|
|
96
124
|
} else {
|
|
97
125
|
if (!path) return;
|
|
98
126
|
const lineRange = preview ? undefined : parseLineRange(target.href);
|
|
99
|
-
const excerpt = await readExcerpt(cwd, path, controller.signal, lineRange);
|
|
127
|
+
const excerpt = await readExcerpt(externalRoot ?? cwd, path, controller.signal, lineRange);
|
|
100
128
|
if (!excerpt) return;
|
|
101
129
|
draw = () =>
|
|
102
130
|
preview
|
|
@@ -143,19 +171,34 @@ export function createHoverPreview(
|
|
|
143
171
|
hide();
|
|
144
172
|
return;
|
|
145
173
|
}
|
|
146
|
-
const
|
|
174
|
+
const line = screenLine(point.row);
|
|
175
|
+
const href = getOsc8LinkAtColumn(hoverLinkLine(line), point.col);
|
|
147
176
|
const preview = href ? findWikiPreview(href) : undefined;
|
|
148
|
-
if (
|
|
177
|
+
if (
|
|
178
|
+
hover &&
|
|
179
|
+
href === hover.href &&
|
|
180
|
+
point.row === hover.row &&
|
|
181
|
+
preview === hover.preview &&
|
|
182
|
+
(!hover.externalRoot || external.marker.matches(line, point.col, href))
|
|
183
|
+
) {
|
|
149
184
|
hover.col = point.col;
|
|
150
185
|
return;
|
|
151
186
|
}
|
|
152
187
|
hide();
|
|
153
188
|
if (!href || tui.hasOverlay()) return;
|
|
154
|
-
|
|
155
|
-
|
|
189
|
+
let path = preview ? ("path" in preview ? preview.path : undefined) : resolveLinkPath(cwd, href);
|
|
190
|
+
let externalRoot: ExternalPreviewRoot | undefined;
|
|
191
|
+
if (!preview && !path) {
|
|
192
|
+
const local = classifyLinkPath(cwd, href);
|
|
193
|
+
if (local?.kind !== "external" || previewImageMime(local.path)) return;
|
|
194
|
+
externalRoot = external.roots().find((root) => relativePreviewPath(root.path, local.path));
|
|
195
|
+
if (!externalRoot || !external.marker.matches(line, point.col, href)) return;
|
|
196
|
+
path = local.path;
|
|
197
|
+
}
|
|
156
198
|
|
|
157
|
-
const target: Hover = { ...point, href, path, preview, controller: new AbortController() };
|
|
199
|
+
const target: Hover = { ...point, href, path, externalRoot, preview, controller: new AbortController() };
|
|
158
200
|
hover = target;
|
|
201
|
+
viewport = { columns: tui.terminal.columns, rows: tui.terminal.rows };
|
|
159
202
|
timer = setTimeout(() => void show(target), HOVER_DELAY_MS);
|
|
160
203
|
}
|
|
161
204
|
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import type { TUI } from "@earendil-works/pi-tui";
|
|
3
|
+
import { createExternalLinkMarker } from "./external-link-marker.js";
|
|
4
|
+
import type { ExternalPreviewRoot } from "./filelinks.js";
|
|
3
5
|
import { createHoverPreview } from "./hover-preview.js";
|
|
4
6
|
import { renderInlineMarkup } from "./inline-markup.js";
|
|
7
|
+
import { loadPreviewSettings } from "./preview-settings.js";
|
|
5
8
|
import { INLINE_FORMATTING_PROMPT } from "./prompt.js";
|
|
6
9
|
import { createWikilinks } from "./wikilinks.js";
|
|
7
10
|
|
|
@@ -11,6 +14,9 @@ interface Session {
|
|
|
11
14
|
cwd: string;
|
|
12
15
|
theme: Theme;
|
|
13
16
|
tui: TUI;
|
|
17
|
+
owner: ExtensionContext["sessionManager"];
|
|
18
|
+
marker: ReturnType<typeof createExternalLinkMarker>;
|
|
19
|
+
clearWidget(): void;
|
|
14
20
|
dismissPreview(): void;
|
|
15
21
|
wiki?: ReturnType<typeof createWikilinks>;
|
|
16
22
|
menu?: AbortController;
|
|
@@ -19,18 +25,35 @@ interface Session {
|
|
|
19
25
|
export function inlineMarkupExtension(pi: ExtensionAPI): void {
|
|
20
26
|
let session: Session | undefined;
|
|
21
27
|
|
|
22
|
-
pi.on("session_start", (_event, { mode, cwd, ui }) => {
|
|
28
|
+
pi.on("session_start", async (_event, { mode, cwd, ui, hasUI, sessionManager }) => {
|
|
29
|
+
session?.clearWidget();
|
|
23
30
|
if (mode !== "tui") return;
|
|
31
|
+
const settings = new AbortController();
|
|
32
|
+
const marker = createExternalLinkMarker();
|
|
33
|
+
let roots: readonly ExternalPreviewRoot[] = [];
|
|
24
34
|
ui.setWidget(
|
|
25
35
|
WIDGET_KEY,
|
|
26
36
|
(tui, theme) => {
|
|
27
|
-
const preview = createHoverPreview(tui, theme, cwd, (href) => current.wiki?.findPreview(href)
|
|
28
|
-
|
|
37
|
+
const preview = createHoverPreview(tui, theme, cwd, (href) => current.wiki?.findPreview(href), {
|
|
38
|
+
marker,
|
|
39
|
+
roots: () => roots,
|
|
40
|
+
});
|
|
41
|
+
const current: Session = {
|
|
42
|
+
cwd,
|
|
43
|
+
theme,
|
|
44
|
+
tui,
|
|
45
|
+
owner: sessionManager,
|
|
46
|
+
marker,
|
|
47
|
+
clearWidget: () => ui.setWidget(WIDGET_KEY, undefined),
|
|
48
|
+
dismissPreview: preview.dismiss,
|
|
49
|
+
};
|
|
29
50
|
session = current;
|
|
30
51
|
const widget = {
|
|
31
52
|
...preview,
|
|
32
53
|
dispose() {
|
|
33
54
|
if (session === current) session = undefined;
|
|
55
|
+
settings.abort();
|
|
56
|
+
roots = [];
|
|
34
57
|
current.menu?.abort();
|
|
35
58
|
preview.dispose();
|
|
36
59
|
current.wiki?.dispose();
|
|
@@ -48,10 +71,15 @@ export function inlineMarkupExtension(pi: ExtensionAPI): void {
|
|
|
48
71
|
},
|
|
49
72
|
{ placement: "belowEditor" },
|
|
50
73
|
);
|
|
74
|
+
const snapshot = await loadPreviewSettings(settings.signal);
|
|
75
|
+
if (settings.signal.aborted || session?.marker !== marker) return;
|
|
76
|
+
roots = snapshot.roots;
|
|
77
|
+
if (snapshot.invalid && hasUI)
|
|
78
|
+
ui.notify("pi-inline: Invalid or unreadable settings. External previews are off.", "warning");
|
|
51
79
|
});
|
|
52
80
|
|
|
53
81
|
pi.on("session_shutdown", (_event, ctx) => {
|
|
54
|
-
if (ctx.mode === "tui"
|
|
82
|
+
if (session && ctx.mode === "tui" && session.owner === ctx.sessionManager) session.clearWidget();
|
|
55
83
|
});
|
|
56
84
|
|
|
57
85
|
pi.registerCommand("inline-markup", {
|
|
@@ -96,7 +124,7 @@ export function inlineMarkupExtension(pi: ExtensionAPI): void {
|
|
|
96
124
|
// Pi 1.5.0 does not accept messageTypes registration options.
|
|
97
125
|
pi.registerMarkdownTransformer((markdown, { messageType }) => {
|
|
98
126
|
if (!session || (messageType !== "user" && messageType !== "assistant")) return markdown;
|
|
99
|
-
const { cwd, theme, wiki } = session;
|
|
100
|
-
return renderInlineMarkup(markdown, cwd, theme, messageType === "user", wiki);
|
|
127
|
+
const { cwd, theme, wiki, marker } = session;
|
|
128
|
+
return renderInlineMarkup(markdown, cwd, theme, messageType === "user", wiki, marker);
|
|
101
129
|
});
|
|
102
130
|
}
|
package/src/inline-markup.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { getCapabilities, hyperlink, Marked } from "@earendil-works/pi-tui";
|
|
3
3
|
import { cleanBadgeLabel, renderBadge } from "./badge.js";
|
|
4
|
-
import {
|
|
4
|
+
import type { createExternalLinkMarker } from "./external-link-marker.js";
|
|
5
|
+
import { classifyLinkPath } from "./filelinks.js";
|
|
6
|
+
import { previewImageMime } from "./image-preview.js";
|
|
5
7
|
import type { createWikilinks } from "./wikilinks.js";
|
|
6
8
|
|
|
7
9
|
const START =
|
|
@@ -34,10 +36,9 @@ function asCodeSpan(text: string): string {
|
|
|
34
36
|
return fence + text + fence;
|
|
35
37
|
}
|
|
36
38
|
|
|
37
|
-
function renderFileLabel(label: string, href: string, theme: Theme, inlineCode: boolean): string {
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
: theme.fg("mdLink", `📄\u00a0${label}`);
|
|
39
|
+
function renderFileLabel(label: string, href: string, path: string, theme: Theme, inlineCode: boolean): string {
|
|
40
|
+
const prefix = previewImageMime(path) ? "🖼️\u00a0" : "📄\u00a0";
|
|
41
|
+
const text = inlineCode ? theme.fg("mdLink", prefix) + theme.fg("mdCode", label) : theme.fg("mdLink", prefix + label);
|
|
41
42
|
return getCapabilities().hyperlinks ? hyperlink(text, href) : text;
|
|
42
43
|
}
|
|
43
44
|
|
|
@@ -67,6 +68,7 @@ export function renderInlineMarkup(
|
|
|
67
68
|
theme: Theme,
|
|
68
69
|
userMessage: boolean,
|
|
69
70
|
wiki?: ReturnType<typeof createWikilinks>,
|
|
71
|
+
externalLinkMarker?: ReturnType<typeof createExternalLinkMarker>,
|
|
70
72
|
): string {
|
|
71
73
|
if (!markdown.includes("[[") && !markdown.includes("](")) return markdown;
|
|
72
74
|
|
|
@@ -124,12 +126,14 @@ export function renderInlineMarkup(
|
|
|
124
126
|
const start = starts[id];
|
|
125
127
|
if (!start || start.badge !== undefined || !tagged.startsWith(token.raw, start.taggedOffset)) return;
|
|
126
128
|
const href = untag(token.href);
|
|
127
|
-
|
|
129
|
+
const target = classifyLinkPath(root, href);
|
|
130
|
+
if (!token.text.startsWith(start.marker) || !target) return;
|
|
131
|
+
const mark = (text: string) => (target.kind === "external" ? (externalLinkMarker?.mark(text, href) ?? text) : text);
|
|
128
132
|
const { offset } = start;
|
|
129
133
|
const end = offset + untag(token.raw).length;
|
|
130
134
|
if (start.linkedBadge !== undefined) {
|
|
131
135
|
const label = cleanBadgeLabel(start.linkedBadge);
|
|
132
|
-
if (label) replacements.set(id, { offset, end, text: renderBadge(label, theme, userMessage, href) });
|
|
136
|
+
if (label) replacements.set(id, { offset, end, text: mark(renderBadge(label, theme, userMessage, href)) });
|
|
133
137
|
return;
|
|
134
138
|
}
|
|
135
139
|
const parts = token.tokens;
|
|
@@ -153,9 +157,11 @@ export function renderInlineMarkup(
|
|
|
153
157
|
replacements.set(id, {
|
|
154
158
|
offset: wrapped ? offset - 2 : offset,
|
|
155
159
|
end: wrapped ? end + 2 : end,
|
|
156
|
-
text:
|
|
157
|
-
|
|
158
|
-
|
|
160
|
+
text: mark(
|
|
161
|
+
wrapped
|
|
162
|
+
? renderBadge(label, theme, userMessage, href)
|
|
163
|
+
: renderFileLabel(label, href, target.path, theme, code !== undefined),
|
|
164
|
+
),
|
|
159
165
|
});
|
|
160
166
|
});
|
|
161
167
|
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { isAbsolute, join, parse, resolve } from "node:path";
|
|
4
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { type ExternalPreviewRoot, relativePreviewPath } from "./filelinks.js";
|
|
6
|
+
|
|
7
|
+
type PreviewSettings = { roots: readonly ExternalPreviewRoot[]; invalid?: true };
|
|
8
|
+
|
|
9
|
+
export async function loadPreviewSettings(signal: AbortSignal): Promise<PreviewSettings> {
|
|
10
|
+
const defaults = { roots: [] };
|
|
11
|
+
const invalid = { ...defaults, invalid: true } as const;
|
|
12
|
+
try {
|
|
13
|
+
const file = join(getAgentDir(), "pi-inline.json");
|
|
14
|
+
// Settings are a regular user file, not a project file, symlink, or stream.
|
|
15
|
+
const stat = await lstat(file).catch((error: NodeJS.ErrnoException) => {
|
|
16
|
+
if (error.code !== "ENOENT") throw error;
|
|
17
|
+
});
|
|
18
|
+
if (!stat || signal.aborted) return defaults;
|
|
19
|
+
if (!stat.isFile()) return invalid;
|
|
20
|
+
const source = await readFile(file, { encoding: "utf8", signal });
|
|
21
|
+
if (signal.aborted) return defaults;
|
|
22
|
+
const document: unknown = JSON.parse(source);
|
|
23
|
+
if (!document || typeof document !== "object" || Array.isArray(document)) return invalid;
|
|
24
|
+
if (!("externalPreviewRoots" in document)) return defaults;
|
|
25
|
+
const values = document.externalPreviewRoots;
|
|
26
|
+
if (!Array.isArray(values)) return invalid;
|
|
27
|
+
if (!values.length || signal.aborted) return defaults;
|
|
28
|
+
|
|
29
|
+
const home = resolve(homedir());
|
|
30
|
+
const realHome = await realpath(home).catch(() => home);
|
|
31
|
+
const roots: ExternalPreviewRoot[] = [];
|
|
32
|
+
for (const value of values) {
|
|
33
|
+
if (signal.aborted) return defaults;
|
|
34
|
+
if (
|
|
35
|
+
typeof value !== "string" ||
|
|
36
|
+
!isAbsolute(value) ||
|
|
37
|
+
/[*?[\]{}\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/u.test(value)
|
|
38
|
+
) {
|
|
39
|
+
return invalid;
|
|
40
|
+
}
|
|
41
|
+
const path = resolve(value);
|
|
42
|
+
if ([parse(path).root, home, realHome].includes(path) || relativePreviewPath(path, realHome)) return invalid;
|
|
43
|
+
const identity = await lstat(path, { bigint: true });
|
|
44
|
+
if (signal.aborted) return defaults;
|
|
45
|
+
if (!identity.isDirectory() || (await realpath(path)) !== path) return invalid;
|
|
46
|
+
roots.push({ path, identity });
|
|
47
|
+
}
|
|
48
|
+
return signal.aborted ? defaults : { roots };
|
|
49
|
+
} catch {
|
|
50
|
+
return signal.aborted ? defaults : invalid;
|
|
51
|
+
}
|
|
52
|
+
}
|