@narumitw/pi-inline 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # @narumitw/pi-inline
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - b4d2c30: Remove the extension name and identifier from the prompt guidance. Keep a generic badge label and a Markdown file citation example. Rendering and wikilink behavior are unchanged.
8
+
9
+ ## 0.1.0
10
+
11
+ Package the former project-local extension for independent installation. Wikilinks
12
+ resolve in Pi's working directory rather than the extension's installation directory.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 narumiruna
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,143 @@
1
- # Temporary Holding Version
1
+ # 🔖 pi-inline — Inline Badges and File Previews for Pi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@narumitw/pi-inline)](https://www.npmjs.com/package/@narumitw/pi-inline) [![Pi extension](https://img.shields.io/badge/Pi-extension-blue)](https://pi.dev) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
4
+
5
+ Style badges and preview local file citations in Pi's terminal transcript without changing stored messages.
6
+ `pi-inline` is inspired by [pi-emphasis](https://github.com/johnlindquist/pi-emphasis).
7
+
8
+ ## ✨ Features
9
+
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 an image, a text file, or a range of source lines.
12
+ - Turn on filename lookup for wikilinks in the current session.
13
+
14
+ ## 📦 Install
15
+
16
+ Pi extensions run with your user permissions. Load only code you trust.
17
+
18
+ `@narumitw/pi-inline` is not yet published to npm. From the repository root,
19
+ install dependencies and try it without a build:
20
+
21
+ ```bash
22
+ npm install
23
+ pi -e ./packages/pi-inline
24
+ ```
25
+
26
+ To keep this checkout installed:
27
+
28
+ ```bash
29
+ pi install ./packages/pi-inline
30
+ ```
31
+
32
+ After the first npm release, install or try it with:
33
+
34
+ ```bash
35
+ pi install npm:@narumitw/pi-inline
36
+ pi -e npm:@narumitw/pi-inline
37
+ ```
38
+
39
+ ### Migrate from pi-inline-markup
40
+
41
+ `pi update` does not switch to the new npm name. After the first release, run
42
+ `pi remove npm:@narumitw/pi-inline-markup` in the original scope, then run
43
+ `pi install npm:@narumitw/pi-inline` in that same scope. Add `-l` to both commands for a
44
+ project install.
45
+
46
+ If you load the old checkout path, replace it with `./packages/pi-inline`.
47
+ Remove any explicit entry for the former `.pi/extensions/pi-inline-markup/`
48
+ extension. Do not load both copies. The `/inline-markup` command is unchanged.
49
+
50
+ ## 🚀 Quick start
51
+
52
+ Start Pi in a directory with a `README.md` file. Send a message containing
53
+ `[README](./README.md)` to see a file icon next to the label. In fullscreen mode,
54
+ hover over the link to preview the file. If Pi detects Kitty graphics support,
55
+ hover over an image link such as `[Cat Photo](./cat.png)` to see the image.
56
+
57
+ ## 💬 Commands
58
+
59
+ Run `/inline-markup` with no arguments in the terminal UI. Select **On** or **Off**
60
+ to toggle wikilinks immediately, or press Escape to leave the value unchanged.
61
+ Wikilinks start off in each new session and after `/reload`. Turning them off
62
+ stops file indexing and closes any open preview.
63
+
64
+ ## 🔗 Link and badge syntax
65
+
66
+ ```markdown
67
+ [[README]]
68
+ [[[README](./README.md)]]
69
+ [[[README]]](./README.md)
70
+ [`runTests()`](./scripts/run-tests.mjs#L12-L20)
71
+ ```
72
+
73
+ - `[[label]]` is decorative unless you enable wikilinks. With wikilinks off, the
74
+ badge does not look up, open, or preview a file.
75
+ - The two linked badge forms are equivalent. Both use standard local Markdown
76
+ destinations and support hover previews whether or not wikilinks are enabled.
77
+ - Ordinary Markdown links use a file icon (📄). Use a plain-text or inline-code
78
+ label and a path relative to Pi's working directory or an absolute path within
79
+ it. Hidden paths work too, for example `[CI workflow](./.github/workflows/ci.yml#L1)`.
80
+ Encode spaces as `%20`.
81
+ - Use `#L12` for one source line or `#L12-L20` for an inclusive range. Hover also
82
+ accepts `#L12-20`. These previews show literal source rather than rendered Markdown.
83
+
84
+ When wikilinks are on, `[[README]]` looks up files under Pi's working directory,
85
+ `[[README.md|Guide]]` sets a custom label, and `[[./README.md]]` selects an exact
86
+ path. If a bare filename matches several Markdown files, the badge previews up
87
+ to three. Clicking opens the file at the working directory root if present, or
88
+ the only match if the filename is unique. If there is no root match and several
89
+ files match, the badge previews files but is not clickable. Unresolved names
90
+ also stay non-clickable. The index skips hidden paths, starts on first lookup,
91
+ and refreshes five seconds after each scan.
92
+
93
+ ## 🔒 Security and privacy
94
+
95
+ Previews are local. They exclude files outside Pi's working directory,
96
+ `node_modules`, and symbolic links. Hovering over an explicit Markdown link
97
+ can display a hidden workspace file, including dotfiles that may contain secrets.
98
+ The extension does not add file contents to the model context.
99
+
100
+ In the terminal UI, the extension adds a fixed system prompt hint about badge
101
+ labels and Markdown file citations. The hint uses a placeholder path and contains
102
+ no extension name or workspace data. Updating the hint does not rewrite existing
103
+ session history.
104
+
105
+ ## 🚧 Limitations
106
+
107
+ - Rounded badges require a font with Powerline glyphs.
108
+ - Hover previews require fullscreen mode, OSC 8 hyperlinks, and mouse movement
109
+ reports without a button press. Pi does not request these reports in tmux,
110
+ Zellij, or GNU Screen.
111
+ - Text previews show up to 16 KiB of a regular UTF-8 file. For a line-anchored
112
+ preview, the first requested line must start within the first 256 KiB.
113
+ - Image previews require Kitty graphics and display a static PNG, JPEG, GIF, or
114
+ WebP image. The preview keeps the original pixel dimensions when the image fits
115
+ above or below its link. Otherwise, it scales down without changing the aspect
116
+ ratio. The extension has no fixed source size limit, but the image decoder
117
+ and available memory still set practical limits. If a preview is unavailable,
118
+ you can still open the link.
119
+
120
+ ## 📋 First publication
121
+
122
+ Maintainers must review the regenerated Version PR for `@narumitw/pi-inline`
123
+ before merging it and coordinate the merge with the approved first publication.
124
+ Do not merge a Version PR that still targets `@narumitw/pi-inline-markup`. Leave
125
+ the old npm package and its tags intact. After publication, verify the public
126
+ version and npm-source loading, confirm npm Trusted Publishing for later releases,
127
+ and update the install status in both READMEs.
128
+
129
+ ## 🗂️ Package layout
130
+
131
+ - `src/index.ts` forwards the extension factory to Pi. The rest of `src/` owns
132
+ transcript rendering, hover previews, and the wikilink index.
133
+ - `test/` covers rendering, session cleanup, file boundaries, and workspace lookups.
134
+
135
+ The package ships its TypeScript source and needs no build step.
136
+
137
+ ## 🔎 Keywords
138
+
139
+ Pi extension, terminal Markdown, inline badges, wikilinks, file citations, hover previews.
140
+
141
+ ## 📄 License
142
+
143
+ MIT. See [`LICENSE`](./LICENSE).
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@narumitw/pi-inline",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Style inline badges and preview local file links in Pi's terminal UI.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "keywords": [
9
+ "pi-package",
10
+ "pi-extension",
11
+ "markdown",
12
+ "wikilinks",
13
+ "file-preview"
14
+ ],
15
+ "files": [
16
+ "src",
17
+ "README.md",
18
+ "CHANGELOG.md",
19
+ "LICENSE"
20
+ ],
21
+ "pi": {
22
+ "extensions": [
23
+ "./src/index.ts"
24
+ ]
25
+ },
26
+ "scripts": {
27
+ "check": "biome check . && npm run typecheck",
28
+ "format": "biome check --write .",
29
+ "typecheck": "tsc --noEmit"
30
+ },
31
+ "peerDependencies": {
32
+ "@earendil-works/pi-coding-agent": "*",
33
+ "@earendil-works/pi-tui": "*"
34
+ },
35
+ "devDependencies": {
36
+ "@earendil-works/pi-coding-agent": "1.5.0",
37
+ "@earendil-works/pi-tui": "1.5.0",
38
+ "@types/node": "26.6.6",
39
+ "typescript": "7.0.2"
40
+ },
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/narumiruna/pi-extensions",
44
+ "directory": "packages/pi-inline"
45
+ },
46
+ "dependencies": {
47
+ "sharp": "0.35.5"
48
+ }
49
+ }
package/src/badge.ts ADDED
@@ -0,0 +1,67 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
3
+ import {
4
+ backgroundAnsi,
5
+ type Color,
6
+ colorToRgb,
7
+ foregroundAnsi,
8
+ getCapabilities,
9
+ hyperlink,
10
+ rgbColor,
11
+ stripTerminalSequences,
12
+ } from "@earendil-works/pi-tui";
13
+
14
+ const palette: readonly ThemeColor[] = [
15
+ "accent",
16
+ "mdLink",
17
+ "success",
18
+ "mdHeading",
19
+ "error",
20
+ "syntaxString",
21
+ "syntaxVariable",
22
+ "thinkingXhigh",
23
+ ];
24
+
25
+ function textColorForFill(fill: Color): Color {
26
+ // Compare black and white against the fill's relative luminance (WCAG 2.2).
27
+ const { r, g, b } = colorToRgb(fill);
28
+ const linear = (channel: number) => {
29
+ const srgb = Math.round(channel) / 255;
30
+ return srgb <= 0.04045 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4;
31
+ };
32
+ const luminance = 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
33
+ const blackContrast = (luminance + 0.05) / 0.05;
34
+ const whiteContrast = 1.05 / (luminance + 0.05);
35
+ const channel = blackContrast >= whiteContrast ? 0 : 255;
36
+ return rgbColor(channel, channel, channel);
37
+ }
38
+
39
+ export function cleanBadgeLabel(label: string): string {
40
+ return stripTerminalSequences(label)
41
+ .replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/gu, " ")
42
+ .trim();
43
+ }
44
+
45
+ /** Renders a badge as ANSI text with an optional terminal link or hover target. */
46
+ export function renderBadge(
47
+ label: string,
48
+ theme: Theme,
49
+ userMessage: boolean,
50
+ href?: string,
51
+ groupId?: string,
52
+ ): string {
53
+ const caps = getCapabilities();
54
+ const mode = caps.trueColor ? "truecolor" : "256color";
55
+ const key = createHash("sha256").update(label.normalize("NFC")).digest()[0];
56
+ const fill = theme.colors[palette[key % palette.length]];
57
+ const edge = foregroundAnsi(fill, mode);
58
+ const body = backgroundAnsi(fill, mode) + foregroundAnsi(textColorForFill(fill), mode);
59
+ const resetFill = (userMessage && theme.getBgAnsi("userMessageBg")) || "\x1b[49m";
60
+ const padded = `\u00a0${label.replaceAll(" ", "\u00a0")}\u00a0`;
61
+ // Rounded Powerline caps require glyph support from the terminal or its font.
62
+ const badge = `${edge}\uE0B6${body}${padded}${resetFill}${edge}\uE0B4\x1b[39m`;
63
+ if (!caps.hyperlinks) return badge;
64
+ // An empty group URL allows a preview without a click destination.
65
+ if (groupId) return `\x1b]8;id=${groupId};${href ?? ""}\x1b\\${badge}\x1b]8;;\x1b\\`;
66
+ return href ? hyperlink(badge, href) : badge;
67
+ }
@@ -0,0 +1,199 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, open, realpath } from "node:fs/promises";
3
+ import { basename, isAbsolute, relative, resolve, sep } from "node:path";
4
+ import { getMarkdownTheme, type Theme } from "@earendil-works/pi-coding-agent";
5
+ import { Markdown, stripTerminalSequences, truncateToWidth } from "@earendil-works/pi-tui";
6
+
7
+ const MAX_BYTES = 16 * 1024;
8
+ const MAX_LINE_SCAN_BYTES = 256 * 1024;
9
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: OSC 8 uses ESC and BEL.
10
+ const OSC_8 = /\x1b\]8;[^\x07\x1b]*(?:\x07|\x1b\\)/g;
11
+
12
+ export interface LineRange {
13
+ start: number;
14
+ end: number;
15
+ }
16
+
17
+ export interface PreviewExcerpt {
18
+ filename: string;
19
+ text: string;
20
+ clipped: boolean;
21
+ lineRange?: LineRange;
22
+ }
23
+
24
+ function workspacePath(root: string, path: string): string | undefined {
25
+ const local = relative(root, path);
26
+ if (!local || isAbsolute(local) || local === ".." || local.startsWith(`..${sep}`)) return undefined;
27
+ if (local.split(sep).includes("node_modules")) return undefined;
28
+ return local;
29
+ }
30
+
31
+ export function resolveLinkPath(root: string, href: string): string | undefined {
32
+ // Interpret Markdown destinations as filesystem paths, not as URLs to fetch.
33
+ // Leave URI schemes (including file:) and protocol-relative links to Pi.
34
+ const invalid = /[\\\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/u;
35
+ if (invalid.test(href)) return undefined;
36
+ const [encoded] = href.split(/[?#]/, 1);
37
+ try {
38
+ const path = decodeURIComponent(encoded);
39
+ if (!path || path.startsWith("//") || invalid.test(path)) return undefined;
40
+ if (/^[a-z][a-z\d+.-]*:/i.test(path) && !isAbsolute(path)) return undefined;
41
+ const target = resolve(root, path);
42
+ return workspacePath(root, target) ? target : undefined;
43
+ } catch {
44
+ return undefined; // Malformed percent escape.
45
+ }
46
+ }
47
+
48
+ export function parseLineRange(href: string): LineRange | undefined {
49
+ const match = /#L([1-9]\d*)(?:-L?([1-9]\d*))?$/.exec(href);
50
+ if (!match || match.index !== href.indexOf("#")) return undefined;
51
+ const start = Number(match[1]);
52
+ const end = match[2] ? Number(match[2]) : start;
53
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end < start) return undefined;
54
+ return { start, end };
55
+ }
56
+
57
+ function selectLines(
58
+ bytes: Buffer,
59
+ { start, end }: LineRange,
60
+ moreBytes: boolean,
61
+ ): { bytes: Buffer; clipped: boolean } | undefined {
62
+ let line = 1;
63
+ let offset = 0;
64
+ let from = 0;
65
+ while (offset < bytes.length) {
66
+ const byte = bytes[offset++];
67
+ if (byte !== 10 && byte !== 13) continue;
68
+ if (byte === 13 && bytes[offset] === 10) offset++;
69
+ if (line === end) {
70
+ return { bytes: bytes.subarray(from, Math.min(offset, from + MAX_BYTES)), clipped: offset - from > MAX_BYTES };
71
+ }
72
+ if (++line === start) from = offset;
73
+ }
74
+ if (line < start || from === bytes.length) return undefined;
75
+ return {
76
+ bytes: bytes.subarray(from, from + MAX_BYTES),
77
+ clipped: moreBytes || bytes.length - from > MAX_BYTES,
78
+ };
79
+ }
80
+
81
+ /** Opens a regular workspace file without following symlinks. The caller owns the handle. */
82
+ export async function openPreviewFile(root: string, path: string, signal: AbortSignal) {
83
+ try {
84
+ const local = workspacePath(root, path);
85
+ if (!local || signal.aborted) return undefined;
86
+ const project = await realpath(root);
87
+ if (signal.aborted) return undefined;
88
+ const candidate = resolve(project, local);
89
+ if ((await realpath(candidate)) !== candidate || signal.aborted) return undefined;
90
+ if (!(await lstat(candidate)).isFile() || signal.aborted) return undefined;
91
+
92
+ const file = await open(candidate, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
93
+ let keepOpen = false;
94
+ try {
95
+ if (signal.aborted) return undefined;
96
+ const stat = await file.stat();
97
+ if (signal.aborted || !stat.isFile()) return undefined;
98
+ keepOpen = true;
99
+ return {
100
+ file,
101
+ size: stat.size,
102
+ filename: basename(candidate).replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/gu, " "),
103
+ };
104
+ } finally {
105
+ if (!keepOpen) await file.close();
106
+ }
107
+ } catch {
108
+ // A file can be missing or unreadable.
109
+ return undefined;
110
+ }
111
+ }
112
+
113
+ export async function readExcerpt(
114
+ root: string,
115
+ path: string,
116
+ signal: AbortSignal,
117
+ lineRange?: LineRange,
118
+ ): Promise<PreviewExcerpt | undefined> {
119
+ const source = await openPreviewFile(root, path, signal);
120
+ if (!source) return undefined;
121
+ const { file, size, filename } = source;
122
+ try {
123
+ if (signal.aborted) return undefined;
124
+ const buffer = Buffer.alloc(Math.min(size, lineRange ? MAX_LINE_SCAN_BYTES : MAX_BYTES));
125
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
126
+ if (signal.aborted) return undefined;
127
+ const bytes = buffer.subarray(0, bytesRead);
128
+ const moreBytes = size > bytesRead;
129
+ const excerpt = lineRange ? selectLines(bytes, lineRange, moreBytes) : { bytes, clipped: moreBytes };
130
+ if (!excerpt) return undefined;
131
+ const { clipped } = excerpt;
132
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(excerpt.bytes, { stream: clipped });
133
+ if (text.includes("\0")) return undefined;
134
+ const clean = stripTerminalSequences(text)
135
+ .replace(/\r\n?/g, "\n")
136
+ .replace(/[\p{Zl}\p{Zp}]/gu, " ")
137
+ .replace(/(?![\n\t])[\p{Cc}\p{Bidi_Control}]/gu, "");
138
+ return { filename, text: clean, clipped, lineRange };
139
+ } catch {
140
+ return undefined; // Unreadable file or invalid UTF-8.
141
+ } finally {
142
+ await file.close().catch(() => undefined);
143
+ }
144
+ }
145
+
146
+ export function renderFilePreview(theme: Theme, excerpt: PreviewExcerpt, width: number, height: number): string[] {
147
+ if (width < 5 || height < 4) return [];
148
+ const contentWidth = width - 4;
149
+ // Anchors refer to source lines, not to the rendered Markdown document.
150
+ const markdown = !excerpt.lineRange && /\.(md|markdown)$/i.test(excerpt.filename);
151
+ const lines = markdown
152
+ ? new Markdown(
153
+ excerpt.text,
154
+ 0,
155
+ 0,
156
+ { ...getMarkdownTheme(), linkUrl: () => "", highlightCode: undefined },
157
+ { color: (text) => theme.fg("text", text) },
158
+ { renderLatex: false },
159
+ )
160
+ .render(contentWidth)
161
+ .map((line) => line.replace(OSC_8, ""))
162
+ : excerpt.text
163
+ .replace(/\n$/, "")
164
+ .split("\n")
165
+ .map((line) => line.replaceAll("\t", " "));
166
+ const limit = height - 3;
167
+ const body = lines.slice(0, limit);
168
+ if (excerpt.clipped || lines.length > limit) {
169
+ const last = body.pop() ?? "";
170
+ body.push(truncateToWidth(last, contentWidth - 1, "") + theme.fg("muted", "…"));
171
+ }
172
+ const { filename, lineRange } = excerpt;
173
+ const caption = lineRange
174
+ ? `${filename}#L${lineRange.start}${lineRange.end === lineRange.start ? "" : `-L${lineRange.end}`}`
175
+ : filename;
176
+ return renderPreviewFrame(theme, [theme.fg("accent", caption), ...body], width, 1);
177
+ }
178
+
179
+ export function renderPreviewFrame(
180
+ theme: Theme,
181
+ content: string[],
182
+ width: number,
183
+ padding: number,
184
+ rounded = false,
185
+ ): string[] {
186
+ const border = (text: string) => theme.fg("borderMuted", text);
187
+ const edge = "─".repeat(width - 2);
188
+ const gap = " ".repeat(padding);
189
+ const contentWidth = width - 2 - 2 * padding;
190
+ const rows = content.map(
191
+ (text) => `${border("│")}${gap}${truncateToWidth(text, contentWidth, "…", true)}${gap}${border("│")}`,
192
+ );
193
+ const [topLeft, topRight, bottomLeft, bottomRight] = rounded ? "╭╮╰╯" : "┌┐└┘";
194
+ const background = theme.getBgAnsi("toolPendingBg");
195
+ // Truncation adds full SGR resets before the ellipsis and padding.
196
+ return [border(`${topLeft}${edge}${topRight}`), ...rows, border(`${bottomLeft}${edge}${bottomRight}`)].map((line) =>
197
+ theme.bg("toolPendingBg", line.replaceAll("\x1b[0m", `\x1b[0m${background}`)),
198
+ );
199
+ }