@xynogen/pix-display 0.1.17 → 0.2.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/README.md +2 -2
- package/package.json +4 -4
- package/src/index.ts +5 -5
- package/src/inline-chips.ts +205 -0
- package/src/paste-chips.ts +0 -300
package/README.md
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
# pix-display
|
|
4
4
|
|
|
5
|
-
Pi core extension —
|
|
5
|
+
Pi core extension — inline chips, thinking blocks, and polished code snippets.
|
|
6
6
|
|
|
7
7
|
## What it does
|
|
8
8
|
|
|
9
9
|
Three features, always on when installed:
|
|
10
10
|
|
|
11
|
-
**
|
|
11
|
+
**Inline chips.** Renders `<path>…</path>` spans (written by e.g. `pix-search`) as `@name` chips, and replaces Pi's paste markers (`[paste #1 2232 chars]`) with styled icon chips: `image #1` for image pastes (blue), `text +N lines` / `text Nk chars` for text pastes (green). Collapses pasted image paths into markers in the buffer while showing human-readable labels on screen. The display rewrite is purely visual — the buffer keeps the real path for the model. Expansion wraps each paste in `<paste>…</paste>` so adjacent pastes don't merge into one wall in the model-facing text. Sent user messages get the same treatment in the transcript (display-only, via Pi's Markdown transformer hook, Pi ≥ 0.85): `<paste>`/`<path>` spans collapse to inline chips, text pastes keep a head…tail glimpse.
|
|
12
12
|
|
|
13
13
|
**Thinking blocks.** Converts leaked reasoning tags (`<think>`/`<thinking>`) from some providers into native Pi `thinking` content blocks, which render dim + italic via the `thinkingText` theme token. No ANSI injection, no markdown blockquote shim. Applies during streaming (`message_update`) and finalization (`message_end`).
|
|
14
14
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xynogen/pix-display",
|
|
3
|
-
"version": "0.1
|
|
4
|
-
"description": "Pi core extension —
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Pi core extension — inline chips, thinking blocks, and framed code rendering",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.ts",
|
|
7
7
|
"scripts": {
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"pi",
|
|
23
23
|
"pi-package",
|
|
24
24
|
"pi-extension",
|
|
25
|
-
"
|
|
25
|
+
"inline-chips",
|
|
26
26
|
"thinking",
|
|
27
27
|
"code-rendering",
|
|
28
28
|
"syntax-highlighting",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"access": "public"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@xynogen/pix-pretty": "^1.
|
|
42
|
+
"@xynogen/pix-pretty": "^1.21.0"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
45
|
"@earendil-works/pi-coding-agent": "*",
|
package/src/index.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* pix-display — Pi core extension:
|
|
2
|
+
* pix-display — Pi core extension: inline chips, thinking, and code-block display.
|
|
3
3
|
*
|
|
4
|
-
* Entry point: activates
|
|
4
|
+
* Entry point: activates inline-chip, thinking, and code-block extensions.
|
|
5
5
|
* Terminal-only rendering behavior stays inactive outside TUI mode.
|
|
6
6
|
*
|
|
7
7
|
* Modules:
|
|
8
|
-
*
|
|
8
|
+
* inline-chips.ts Installs the shared InlineChipEditor
|
|
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
11
|
*/
|
|
@@ -13,11 +13,11 @@
|
|
|
13
13
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
14
14
|
|
|
15
15
|
import codeBlocksExtension from "./code-blocks.js";
|
|
16
|
-
import
|
|
16
|
+
import inlineChipsExtension from "./inline-chips.js";
|
|
17
17
|
import thinkingExtension from "./thinking.js";
|
|
18
18
|
|
|
19
19
|
export default function pixDisplayExtension(pi: ExtensionAPI): void {
|
|
20
|
-
|
|
20
|
+
inlineChipsExtension(pi);
|
|
21
21
|
thinkingExtension(pi);
|
|
22
22
|
codeBlocksExtension(pi);
|
|
23
23
|
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* inline-chips — render inline tokens in the prompt editor as compact chips.
|
|
3
|
+
*
|
|
4
|
+
* long pasted text → buffer: [paste #1 +42 lines] display: text 42 lines
|
|
5
|
+
* /tmp/shot.png → buffer: [paste #2 13 chars] display: image #2
|
|
6
|
+
* <path>src/a.ts</path> → buffer: [paste #3 8 chars] display: @a.ts
|
|
7
|
+
*
|
|
8
|
+
* `<path>…</path>` from pix-search and Pi's `<paste>…</paste>` payloads are
|
|
9
|
+
* promoted to atomic paste markers (one backspace deletes the whole chip) and
|
|
10
|
+
* expanded back verbatim for the model.
|
|
11
|
+
*/
|
|
12
|
+
import { basename } from "node:path";
|
|
13
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
14
|
+
import { CustomEditor } from "@earendil-works/pi-coding-agent";
|
|
15
|
+
import { CURSOR_MARKER, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
16
|
+
import { BOLD, FG_BLUE, FG_DIM, FG_GREEN, RST } from "@xynogen/pix-pretty/ansi";
|
|
17
|
+
import { icon } from "@xynogen/pix-pretty/icon-catalog";
|
|
18
|
+
import { dirIcon, fileIcon } from "@xynogen/pix-pretty/icons";
|
|
19
|
+
|
|
20
|
+
// ponytail: Pi only exposes atomic paste tokens today. Keep its private registry
|
|
21
|
+
// adapter here; replace this adapter when Pi provides a public inline-token API.
|
|
22
|
+
type Chip = { kind: "image" | "path"; path: string };
|
|
23
|
+
type Registry = Map<number, string | Chip>;
|
|
24
|
+
type PiEditor = {
|
|
25
|
+
pastes: Registry;
|
|
26
|
+
pasteCounter: number;
|
|
27
|
+
expandPasteMarkers(text: string): string;
|
|
28
|
+
handlePaste(text: string): void;
|
|
29
|
+
insertTextAtCursorInternal(text: string): void;
|
|
30
|
+
};
|
|
31
|
+
const MARKER = /\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g;
|
|
32
|
+
const SGR = "(?:\\x1b\\[[0-9;]*m|\\x1b_pi:c\\x07)*";
|
|
33
|
+
const PASTE_SPAN = new RegExp(`${SGR}\\[${SGR}paste #(?:[^\\]]|${SGR})*\\]`, "g");
|
|
34
|
+
const PATH_TAG = /<path>([^<]+)<\/path>/g;
|
|
35
|
+
const PASTE_TAG = /<paste>([\s\S]*?)<\/paste>/g;
|
|
36
|
+
const CODES = /\x1b\[[0-9;]*m|\x1b_pi:c\x07/g;
|
|
37
|
+
const IMAGE_PATH =
|
|
38
|
+
/(^|[^\w/@])((?:~|\/)[^\s,;'"(){}[\]]+\.(?:png|jpe?g|gif|webp|bmp|tiff?|heic|heif))(?=$|[\s,;'"(){}[\]])/gi;
|
|
39
|
+
|
|
40
|
+
/** Expand once: token-looking text inside a paste is literal user content. */
|
|
41
|
+
export function expandChips(text: string, registry: Registry): string {
|
|
42
|
+
return text.replace(MARKER, (marker, id: string) => {
|
|
43
|
+
const value = registry.get(Number(id));
|
|
44
|
+
if (value === undefined) return marker;
|
|
45
|
+
if (typeof value === "string") return `<paste>${value}</paste>`;
|
|
46
|
+
return value.kind === "path" ? `<path>${value.path}</path>` : `<paste>${value.path}</paste>`;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Re-emit the cursor (inverse video + TUI marker) that a chip swallowed. */
|
|
51
|
+
function keepCursor(span: string, label: string): string {
|
|
52
|
+
const marker = span.includes(CURSOR_MARKER) ? CURSOR_MARKER : "";
|
|
53
|
+
return span.includes("\x1b[7m")
|
|
54
|
+
? `${marker}\x1b[7m${label.replaceAll(RST, `${RST}\x1b[7m`)}\x1b[27m`
|
|
55
|
+
: marker + label;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Plain chip text: `head` is the identity, `meta` the dim size/id suffix. */
|
|
59
|
+
function chipLabel(
|
|
60
|
+
value: string | Chip,
|
|
61
|
+
id?: number,
|
|
62
|
+
): { head: string; meta: string; color: string } {
|
|
63
|
+
if (typeof value === "string") {
|
|
64
|
+
const lines = value.split("\n").length;
|
|
65
|
+
const count =
|
|
66
|
+
value.length < 1000 ? `${value.length}` : `${Number((value.length / 1000).toFixed(1))}k`;
|
|
67
|
+
return {
|
|
68
|
+
head: `${icon("paste.text")} text`,
|
|
69
|
+
meta: lines > 10 ? `${lines} lines` : `${count} chars`,
|
|
70
|
+
color: FG_GREEN,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
if (value.kind === "path") {
|
|
74
|
+
const dir = value.path.endsWith("/");
|
|
75
|
+
const name = basename(value.path) || value.path;
|
|
76
|
+
// Same file-type glyphs the picker shows (trailing space is part of the icon).
|
|
77
|
+
return {
|
|
78
|
+
head: `${dir ? dirIcon() : fileIcon(value.path)}@${name}${dir && name !== "/" ? "/" : ""}`,
|
|
79
|
+
meta: "",
|
|
80
|
+
color: FG_BLUE,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
return {
|
|
84
|
+
head: `${icon("paste.image")} image`,
|
|
85
|
+
meta: id === undefined ? "" : `#${id}`,
|
|
86
|
+
color: FG_BLUE,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function renderChips(line: string, registry: Registry): string {
|
|
91
|
+
return line.replace(PASTE_SPAN, (span) => {
|
|
92
|
+
const id = Number(/\[paste #(\d+)/.exec(span.replace(CODES, ""))?.[1]);
|
|
93
|
+
const value = registry.get(id);
|
|
94
|
+
if (value === undefined) return span;
|
|
95
|
+
const { head, meta, color } = chipLabel(value, id);
|
|
96
|
+
const label = `${color}${BOLD}${head}${RST}${meta ? `${FG_DIM} ${meta}${RST}` : ""}`;
|
|
97
|
+
// Tight, no padding: Pi locates the cursor by its marker, so a shorter chip
|
|
98
|
+
// just shifts following text left. render() clamps overflow.
|
|
99
|
+
return keepCursor(span, label);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const HISTORY_TAG = /<(paste|path)>([\s\S]*?)<\/\1>/g;
|
|
104
|
+
const IMAGE_FILE = /^(?:~|\/)\S+\.(?:png|jpe?g|gif|webp|bmp|tiff?|heic|heif)$/i;
|
|
105
|
+
const PREVIEW_CHARS = 40;
|
|
106
|
+
|
|
107
|
+
/** Head…tail glimpse of a paste (whitespace collapsed, backticks dropped for inline code). */
|
|
108
|
+
function snippet(text: string): string {
|
|
109
|
+
const flat = text.replace(/`/g, "").replace(/\s+/g, " ").trim();
|
|
110
|
+
if (flat.length <= PREVIEW_CHARS) return flat;
|
|
111
|
+
const tail = Math.floor(PREVIEW_CHARS / 3);
|
|
112
|
+
return `${flat.slice(0, PREVIEW_CHARS - tail).trimEnd()}…${flat.slice(-tail).trimStart()}`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Display-only: collapse `<paste>…</paste>` / `<path>…</path>` in a sent user
|
|
117
|
+
* message into the same chips the editor showed. Session and model context
|
|
118
|
+
* keep the full text; images take the paste chip since the file path is the
|
|
119
|
+
* whole payload.
|
|
120
|
+
*/
|
|
121
|
+
export function renderHistoryChips(markdown: string): string {
|
|
122
|
+
return markdown.replace(HISTORY_TAG, (_match, tag: string, body: string) => {
|
|
123
|
+
let value: string | Chip = body;
|
|
124
|
+
if (tag === "path") value = { kind: "path", path: body };
|
|
125
|
+
else if (IMAGE_FILE.test(body)) value = { kind: "image", path: body };
|
|
126
|
+
const { head, meta } = chipLabel(value);
|
|
127
|
+
// Text pastes keep a short glimpse so history stays scannable.
|
|
128
|
+
const preview = typeof value === "string" ? snippet(value) : "";
|
|
129
|
+
return `\`${head}${meta ? ` ${meta}` : ""}${preview ? ` · ${preview}` : ""}\``;
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Patch one editor instance; order-independent with other instance patchers (pix-search). */
|
|
134
|
+
export function installChips(editor: CustomEditor): void {
|
|
135
|
+
// SAFETY: Pi's TS-private members remain runtime properties on CustomEditor.
|
|
136
|
+
const pi = editor as unknown as PiEditor;
|
|
137
|
+
pi.expandPasteMarkers = (text) => expandChips(text, pi.pastes);
|
|
138
|
+
const handlePaste = pi.handlePaste.bind(editor);
|
|
139
|
+
pi.handlePaste = (text) => {
|
|
140
|
+
if (IMAGE_FILE.test(text)) {
|
|
141
|
+
editor.insertTextAtCursor(`<paste>${text}</paste>`);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const before = pi.pasteCounter;
|
|
145
|
+
handlePaste(text);
|
|
146
|
+
// Land the cursor after the chip, not glued to it.
|
|
147
|
+
if (pi.pasteCounter > before) pi.insertTextAtCursorInternal(" ");
|
|
148
|
+
};
|
|
149
|
+
const insertTextAtCursor = editor.insertTextAtCursor.bind(editor);
|
|
150
|
+
editor.insertTextAtCursor = (text: string) => {
|
|
151
|
+
if (!text) return;
|
|
152
|
+
// SAFETY: Pi snapshots and renumbers registry values without interpreting them.
|
|
153
|
+
const chip = (value: string | Chip, length: number) => {
|
|
154
|
+
const id = ++pi.pasteCounter;
|
|
155
|
+
pi.pastes.set(id, value);
|
|
156
|
+
return `[paste #${id} ${length} chars]`;
|
|
157
|
+
};
|
|
158
|
+
const replaced = text
|
|
159
|
+
.replace(PATH_TAG, (_match, path: string) => chip({ kind: "path", path }, path.length))
|
|
160
|
+
.replace(PASTE_TAG, (_match, body: string) =>
|
|
161
|
+
chip(IMAGE_FILE.test(body) ? { kind: "image", path: body } : body, body.length),
|
|
162
|
+
)
|
|
163
|
+
.replace(
|
|
164
|
+
IMAGE_PATH,
|
|
165
|
+
(_match, prefix: string, path: string) =>
|
|
166
|
+
prefix + chip({ kind: "image", path }, path.length),
|
|
167
|
+
);
|
|
168
|
+
insertTextAtCursor(/\[paste #\d+[^\]]*\]$/.test(replaced) ? `${replaced} ` : replaced);
|
|
169
|
+
};
|
|
170
|
+
const render = editor.render.bind(editor);
|
|
171
|
+
editor.render = (width: number) =>
|
|
172
|
+
render(width).map((line) => {
|
|
173
|
+
// SAFETY: Pi owns the current registry, including its replacement during undo.
|
|
174
|
+
const styled = renderChips(line, pi.pastes);
|
|
175
|
+
// Restyling may widen a line (e.g. "#1" → "text"); clamp only on overflow.
|
|
176
|
+
return visibleWidth(styled) > width ? truncateToWidth(styled, width, "") : styled;
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export default function (pi: ExtensionAPI): void {
|
|
181
|
+
// ponytail: local Pi 0.82 types predate the runtime Markdown transformer hook.
|
|
182
|
+
const markdownPi = pi as ExtensionAPI & {
|
|
183
|
+
registerMarkdownTransformer?: (
|
|
184
|
+
transformer: (markdown: string, context: { messageType: string }) => string,
|
|
185
|
+
) => void;
|
|
186
|
+
};
|
|
187
|
+
markdownPi.registerMarkdownTransformer?.((markdown, { messageType }) =>
|
|
188
|
+
messageType === "user" ? renderHistoryChips(markdown) : markdown,
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
pi.on("session_start", (_event, ctx) => {
|
|
192
|
+
if (ctx.mode !== "tui") return;
|
|
193
|
+
const previous = ctx.ui.getEditorComponent();
|
|
194
|
+
ctx.ui.setEditorComponent((tui, theme, kb) => {
|
|
195
|
+
const editor = previous?.(tui, theme, kb) ?? new CustomEditor(tui, theme, kb);
|
|
196
|
+
// ponytail: chips need CustomEditor internals; a foreign editor is kept unchipped.
|
|
197
|
+
if (editor instanceof CustomEditor) installChips(editor);
|
|
198
|
+
return editor;
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
203
|
+
if (ctx.mode === "tui") ctx.ui.setEditorComponent(undefined);
|
|
204
|
+
});
|
|
205
|
+
}
|
package/src/paste-chips.ts
DELETED
|
@@ -1,300 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* paste-chips — collapse pasted image paths into Pi paste markers, and
|
|
3
|
-
* re-render all paste markers with type-aware labels.
|
|
4
|
-
*
|
|
5
|
-
* /tmp/pi-clipboard-abc.png → buffer: [paste #1 58 chars]
|
|
6
|
-
* display: [paste image #1]
|
|
7
|
-
*
|
|
8
|
-
* long pasted text → buffer: [paste #2 +42 lines]
|
|
9
|
-
* display: [paste text +42]
|
|
10
|
-
*
|
|
11
|
-
* Atomic deletion + cursor handling come from Pi's marker grammar.
|
|
12
|
-
* On submit, getExpandedText() restores the real path/text for the model.
|
|
13
|
-
* The display rewrite is purely visual (render layer); buffer is untouched.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import type { ExtensionAPI, KeybindingsManager } from "@earendil-works/pi-coding-agent";
|
|
17
|
-
import { CustomEditor } from "@earendil-works/pi-coding-agent";
|
|
18
|
-
import type { EditorTheme, TUI } from "@earendil-works/pi-tui";
|
|
19
|
-
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
20
|
-
import { BOLD, FG_BLUE, FG_DIM, FG_GREEN, RST } from "@xynogen/pix-pretty/ansi";
|
|
21
|
-
import { icon } from "@xynogen/pix-pretty/icon-catalog";
|
|
22
|
-
|
|
23
|
-
// Upstream stopped re-exporting `EditorFactory` from the package entry point,
|
|
24
|
-
// so we reconstruct its signature locally from the still-exported primitives.
|
|
25
|
-
// This matches ctx.ui.setEditorComponent's expected factory shape.
|
|
26
|
-
type EditorFactory = (
|
|
27
|
-
tui: TUI,
|
|
28
|
-
theme: EditorTheme,
|
|
29
|
-
keybindings: KeybindingsManager,
|
|
30
|
-
) => CustomEditor;
|
|
31
|
-
|
|
32
|
-
// ─── Constants ────────────────────────────────────────────────────────────────
|
|
33
|
-
|
|
34
|
-
// Boundary wrapper injected around each expanded paste so the model sees an
|
|
35
|
-
// explicit start/end per blob instead of multiple pastes merged into one wall.
|
|
36
|
-
// Applies to text and image pastes alike.
|
|
37
|
-
const PASTE_OPEN = "<paste>";
|
|
38
|
-
const PASTE_CLOSE = "</paste>";
|
|
39
|
-
|
|
40
|
-
const IMAGE_EXTS = new Set([
|
|
41
|
-
".png",
|
|
42
|
-
".jpg",
|
|
43
|
-
".jpeg",
|
|
44
|
-
".gif",
|
|
45
|
-
".webp",
|
|
46
|
-
".bmp",
|
|
47
|
-
".tif",
|
|
48
|
-
".tiff",
|
|
49
|
-
".heic",
|
|
50
|
-
".heif",
|
|
51
|
-
]);
|
|
52
|
-
|
|
53
|
-
// Group 1 = prefix char (or empty at start), Group 2 = path
|
|
54
|
-
const PATH_RE = /(^|[^\w/])((?:~|\/)[^\s,;'"(){}[\]]+)/g;
|
|
55
|
-
|
|
56
|
-
// Pi's marker grammar — must match exactly for atomic segmentation.
|
|
57
|
-
// e.g. `[paste #1 58 chars]` or `[paste #2 +42 lines]`
|
|
58
|
-
const MARKER_RE = /\[paste #(\d+)( (\+(\d+) lines|(\d+) chars))?\]/g;
|
|
59
|
-
// Cursor inversion codes the TUI Editor embeds when the cursor intersects
|
|
60
|
-
// a marker. Strip them before matching — Pi re-wraps each render call, so
|
|
61
|
-
// width-preserving is not required.
|
|
62
|
-
const CURSOR_RE = /\x1b\[[0-9;]*m/g;
|
|
63
|
-
|
|
64
|
-
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
65
|
-
|
|
66
|
-
function extOf(p: string): string {
|
|
67
|
-
const dot = p.lastIndexOf(".");
|
|
68
|
-
return dot >= 0 ? p.slice(dot).toLowerCase() : "";
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function isImagePath(p: string): boolean {
|
|
72
|
-
return IMAGE_EXTS.has(extOf(p));
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function makeMarker(id: number, charCount: number): string {
|
|
76
|
-
return `[paste #${id} ${charCount} chars]`;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// ─── Editor internals (Pi's TS-private fields are runtime-public JS) ─────────
|
|
80
|
-
|
|
81
|
-
type EditorInternals = {
|
|
82
|
-
pastes: Map<number, string>;
|
|
83
|
-
pasteCounter: number;
|
|
84
|
-
};
|
|
85
|
-
|
|
86
|
-
// expandPasteMarkers is TS-private on the base Editor but runtime-public JS.
|
|
87
|
-
// We reimplement its loop (rather than call super) so we can wrap each
|
|
88
|
-
// replacement, and to avoid depending on a non-exported private method.
|
|
89
|
-
type ExpandInternals = {
|
|
90
|
-
pastes: Map<number, string>;
|
|
91
|
-
};
|
|
92
|
-
|
|
93
|
-
type ExpandPasteHandler = { expandPasteMarkers(text: string): string };
|
|
94
|
-
|
|
95
|
-
// Mirror of the base Editor's paste-marker grammar, per-id at expand time.
|
|
96
|
-
function markerReFor(pasteId: number): RegExp {
|
|
97
|
-
return new RegExp(`\\[paste #${pasteId}( (\\+\\d+ lines|\\d+ chars))?\\]`, "g");
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Expand every paste marker in `text` to its content wrapped in
|
|
102
|
-
* `<paste>…</paste>`. Mirrors the base Editor's expansion loop but adds a
|
|
103
|
-
* boundary per blob (text and image alike) so adjacent pastes can't merge
|
|
104
|
-
* into one indistinguishable wall in the model-facing text.
|
|
105
|
-
*/
|
|
106
|
-
export function expandPasteMarkers(text: string, pastes: Map<number, string>): string {
|
|
107
|
-
let result = text;
|
|
108
|
-
for (const [pasteId, pasteContent] of pastes) {
|
|
109
|
-
result = result.replace(
|
|
110
|
-
markerReFor(pasteId),
|
|
111
|
-
() => `${PASTE_OPEN}${pasteContent}${PASTE_CLOSE}`,
|
|
112
|
-
);
|
|
113
|
-
}
|
|
114
|
-
return result;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
// ─── Path → marker rewriter ──────────────────────────────────────────────────
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* Walk `text`, for each image path: allocate a new paste ID, register the
|
|
121
|
-
* real path in editor.pastes, remember the ID as an image, and emit a
|
|
122
|
-
* Pi-format marker so deletion is atomic.
|
|
123
|
-
*
|
|
124
|
-
* Exported for integration testing: composed with `expandPasteMarkers`, this
|
|
125
|
-
* reproduces the full clipboard-image round-trip (path insert → marker →
|
|
126
|
-
* boundary-wrapped expansion) without standing up a live TUI editor.
|
|
127
|
-
*/
|
|
128
|
-
export function replaceImagePaths(
|
|
129
|
-
text: string,
|
|
130
|
-
internals: EditorInternals,
|
|
131
|
-
imageIds: Set<number>,
|
|
132
|
-
): string {
|
|
133
|
-
return text.replace(PATH_RE, (_, prefix: string, rawPath: string) => {
|
|
134
|
-
if (!isImagePath(rawPath)) return prefix + rawPath;
|
|
135
|
-
internals.pasteCounter += 1;
|
|
136
|
-
const id = internals.pasteCounter;
|
|
137
|
-
internals.pastes.set(id, rawPath);
|
|
138
|
-
imageIds.add(id);
|
|
139
|
-
return prefix + makeMarker(id, rawPath.length);
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// ─── Display rewriter ────────────────────────────────────────────────────────
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Re-style every paste marker in a rendered line:
|
|
147
|
-
* image → ` image #N` with blue icon/label
|
|
148
|
-
* text → ` text Lines lines` or ` text Chars chars` with green icon/label
|
|
149
|
-
*
|
|
150
|
-
* Width-preserving is not required — Pi re-wraps each render call.
|
|
151
|
-
*/
|
|
152
|
-
// A `[...]` span that starts with `paste #` and may carry interleaved cursor
|
|
153
|
-
// SGR codes (e.g. `[paste #1 \x1b[7m5\x1b[0m8 chars]`). We strip ANSI from the
|
|
154
|
-
// matched span only, never the whole line, so the editor cursor's own
|
|
155
|
-
// inverse-video block outside any marker survives.
|
|
156
|
-
const MARKER_SPAN_RE =
|
|
157
|
-
/(?:\x1b\[[0-9;]*m)*\[(?:\x1b\[[0-9;]*m)*paste #(?:[^\]]|\x1b\[[0-9;]*m)*\]/g;
|
|
158
|
-
|
|
159
|
-
export function restyleMarkers(line: string, imageIds: Set<number>): string {
|
|
160
|
-
return line.replace(MARKER_SPAN_RE, (span) => {
|
|
161
|
-
const clean = span.includes("\x1b") ? span.replace(CURSOR_RE, "") : span;
|
|
162
|
-
MARKER_RE.lastIndex = 0;
|
|
163
|
-
const m = MARKER_RE.exec(clean);
|
|
164
|
-
if (!m?.[1]) return span;
|
|
165
|
-
const [, idStr, , , linesStr, charsStr] = m;
|
|
166
|
-
const id = Number.parseInt(idStr, 10);
|
|
167
|
-
if (imageIds.has(id)) {
|
|
168
|
-
return chip(FG_BLUE, icon("paste.image"), "image", `#${id}`);
|
|
169
|
-
}
|
|
170
|
-
if (linesStr) {
|
|
171
|
-
return chip(FG_GREEN, icon("paste.text"), "text", `${linesStr} lines`);
|
|
172
|
-
}
|
|
173
|
-
if (charsStr) {
|
|
174
|
-
return chip(FG_GREEN, icon("paste.text"), "text", `${compactNumber(charsStr)} chars`);
|
|
175
|
-
}
|
|
176
|
-
return chip(FG_GREEN, icon("paste.text"), "text", `#${id}`);
|
|
177
|
-
});
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
function chip(color: string, icon: string, label: string, meta: string): string {
|
|
181
|
-
return `${color}${BOLD}${icon} ${label}${RST}${FG_DIM} ${meta}${RST}`;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
/** True when `text` ends with a Pi paste marker (chip), e.g. `[paste #1 58 chars]`. */
|
|
185
|
-
export function endsWithMarker(text: string): boolean {
|
|
186
|
-
return /\[paste #\d+[^\]]*\]$/.test(text);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
function compactNumber(raw: string): string {
|
|
190
|
-
const n = Number.parseInt(raw, 10);
|
|
191
|
-
if (!Number.isFinite(n)) return raw;
|
|
192
|
-
if (n < 1_000) return `${n}`;
|
|
193
|
-
if (n < 1_000_000) return `${(n / 1_000).toFixed(1).replace(/\.0$/, "")}k`;
|
|
194
|
-
return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
// ─── Custom editor ────────────────────────────────────────────────────────────
|
|
198
|
-
|
|
199
|
-
// handlePaste is TS-private in CustomEditor but runtime-public JS. We patch it
|
|
200
|
-
// per-instance, capturing the base implementation, so large text pastes get the
|
|
201
|
-
// same trailing-space treatment as image chips.
|
|
202
|
-
type PasteHandler = { handlePaste(text: string): void };
|
|
203
|
-
type SubmitHandler = { submitValue(): void };
|
|
204
|
-
|
|
205
|
-
/**
|
|
206
|
-
* Drop image classifications when Pi resets its paste IDs after a submit.
|
|
207
|
-
*
|
|
208
|
-
* The base editor clears `pastes` and resets `pasteCounter` to zero, so IDs are
|
|
209
|
-
* reused in the next prompt. Keeping the old IDs would make a later text paste
|
|
210
|
-
* with the same ID render as an image chip.
|
|
211
|
-
*/
|
|
212
|
-
export function clearImageIdsAfterSubmit(imageIds: Set<number>): void {
|
|
213
|
-
imageIds.clear();
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
class ChipEditor extends CustomEditor {
|
|
217
|
-
private readonly imageIds = new Set<number>();
|
|
218
|
-
|
|
219
|
-
constructor(...args: ConstructorParameters<typeof CustomEditor>) {
|
|
220
|
-
super(...args);
|
|
221
|
-
this.patchHandlePaste();
|
|
222
|
-
this.patchExpandPasteMarkers();
|
|
223
|
-
this.patchSubmitValue();
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
override insertTextAtCursor(text: string): void {
|
|
227
|
-
const internals = this as unknown as EditorInternals;
|
|
228
|
-
const replaced = replaceImagePaths(text, internals, this.imageIds);
|
|
229
|
-
// Append a trailing space when the insertion ends with a paste marker so
|
|
230
|
-
// the cursor lands after the chip rather than inside it.
|
|
231
|
-
super.insertTextAtCursor(endsWithMarker(replaced) ? `${replaced} ` : replaced);
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/**
|
|
235
|
-
* Patch `expandPasteMarkers` (TS-private on the base Editor, runtime-public
|
|
236
|
-
* JS) so every paste expands to its content wrapped in `<paste>…</paste>`,
|
|
237
|
-
* giving the model an explicit boundary per blob — text and image alike.
|
|
238
|
-
* The base inlines content raw, letting adjacent pastes merge into one
|
|
239
|
-
* indistinguishable wall. Patched per-instance, mirroring patchHandlePaste.
|
|
240
|
-
*/
|
|
241
|
-
private patchExpandPasteMarkers(): void {
|
|
242
|
-
const internals = this as unknown as ExpandInternals;
|
|
243
|
-
const self = this as unknown as ExpandPasteHandler;
|
|
244
|
-
self.expandPasteMarkers = (text: string): string => expandPasteMarkers(text, internals.pastes);
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
private patchHandlePaste(): void {
|
|
248
|
-
const self = this as unknown as PasteHandler;
|
|
249
|
-
const base = self.handlePaste.bind(self);
|
|
250
|
-
self.handlePaste = (pastedText: string) => {
|
|
251
|
-
const before = this.getText();
|
|
252
|
-
base(pastedText);
|
|
253
|
-
const after = this.getText();
|
|
254
|
-
// Only nudge a space when the paste collapsed into a marker chip;
|
|
255
|
-
// inline small pastes (no marker) are left untouched.
|
|
256
|
-
if (endsWithMarker(after) && after !== before) {
|
|
257
|
-
super.insertTextAtCursor(" ");
|
|
258
|
-
}
|
|
259
|
-
};
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
private patchSubmitValue(): void {
|
|
263
|
-
const self = this as unknown as SubmitHandler;
|
|
264
|
-
const base = self.submitValue.bind(self);
|
|
265
|
-
self.submitValue = () => {
|
|
266
|
-
// Pi resets pasteCounter to zero in submitValue. Clear the parallel
|
|
267
|
-
// image-ID registry in the same operation before those IDs get reused.
|
|
268
|
-
clearImageIdsAfterSubmit(this.imageIds);
|
|
269
|
-
base();
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
override render(width: number): string[] {
|
|
274
|
-
const raw = super.render(width);
|
|
275
|
-
return raw.map((line) => {
|
|
276
|
-
const restyled = restyleMarkers(line, this.imageIds);
|
|
277
|
-
// Restyling may widen lines (e.g. "#1" → "text"), so clamp to width.
|
|
278
|
-
if (visibleWidth(restyled) > width) {
|
|
279
|
-
return truncateToWidth(restyled, width, "");
|
|
280
|
-
}
|
|
281
|
-
return restyled;
|
|
282
|
-
});
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
// ─── Extension ────────────────────────────────────────────────────────────────
|
|
287
|
-
|
|
288
|
-
export default function (pi: ExtensionAPI) {
|
|
289
|
-
pi.on("session_start", (_event, ctx) => {
|
|
290
|
-
if (!ctx.hasUI) return;
|
|
291
|
-
const factory: EditorFactory = (tui, theme, keybindings) =>
|
|
292
|
-
new ChipEditor(tui, theme, keybindings);
|
|
293
|
-
ctx.ui.setEditorComponent(factory);
|
|
294
|
-
});
|
|
295
|
-
|
|
296
|
-
pi.on("session_shutdown", (_event, ctx) => {
|
|
297
|
-
if (!ctx.hasUI) return;
|
|
298
|
-
ctx.ui.setEditorComponent(undefined);
|
|
299
|
-
});
|
|
300
|
-
}
|