@each1024/pi-mini-mode 2.0.9 → 2.0.10
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 +9 -6
- package/README.zh-CN.md +6 -8
- package/extensions/footer-status.ts +46 -1189
- package/lib/agent-render.ts +203 -0
- package/lib/agent-state.ts +199 -0
- package/lib/agent-view.ts +5 -519
- package/lib/agent-widgets.ts +129 -0
- package/lib/footer-line.ts +206 -0
- package/lib/input-editor-paths.ts +79 -0
- package/lib/input-editor.ts +184 -0
- package/lib/input-enhancements-types.ts +49 -0
- package/lib/input-enhancements.ts +15 -797
- package/lib/input-hover-preview.ts +122 -0
- package/lib/input-image-graphics.ts +34 -0
- package/lib/input-image-paths.ts +120 -0
- package/lib/input-inline-images.ts +114 -0
- package/lib/input-skill-completion.ts +132 -0
- package/lib/minimal-output.ts +379 -0
- package/lib/minimal-turns.ts +203 -0
- package/lib/settings-web.ts +9 -2
- package/lib/settings.html +5 -4
- package/lib/settings.ts +153 -0
- package/lib/thinking-preview.ts +30 -19
- package/lib/thinking-stream.ts +89 -0
- package/lib/transcript-adapter.ts +15 -501
- package/lib/transcript-cards.ts +67 -0
- package/lib/transcript-notice-render.ts +211 -0
- package/lib/transcript-notices.ts +238 -0
- package/lib/usage.ts +137 -0
- package/package.json +4 -2
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { allocateImageId, deleteKittyImage, getCellDimensions, getImageDimensions, getOsc8LinkAtColumn, matchesKey, renderImage, visibleWidth, type TUI } from "@earendil-works/pi-tui";
|
|
2
|
+
import { extname } from "node:path";
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
|
+
import type { Enhancements } from "./input-enhancements-types.ts";
|
|
5
|
+
import { imageLayoutKey, previewLines } from "./input-image-graphics.ts";
|
|
6
|
+
import { IMAGE_MIME, readPreview, type Preview } from "./input-image-paths.ts";
|
|
7
|
+
import { inlinePreviewLines } from "./input-inline-images.ts";
|
|
8
|
+
|
|
9
|
+
export function setPointer(state: Enhancements, pointer: boolean): void {
|
|
10
|
+
if (state.pointer === pointer) return;
|
|
11
|
+
if (pointer || state.pointer) state.tui?.terminal.write(`\x1b]22;${pointer ? "pointer" : "default"}\x07`);
|
|
12
|
+
state.pointer = pointer;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function handleTerminalInput(state: Enhancements, data: string): { consume?: boolean } | undefined {
|
|
16
|
+
if (data === "\x1b[O") { setPointer(state, false); void requestPreview(state, undefined); }
|
|
17
|
+
const mouse = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);
|
|
18
|
+
if (mouse) {
|
|
19
|
+
const x = Number(mouse[2]) - 1, y = Number(mouse[3]) - 1;
|
|
20
|
+
// ponytail: Pi 0.85 has no public screen hit-test API; inspect its last rendered OSC 8 cells.
|
|
21
|
+
const screen = (state.tui as TUI & { previousScreen?: string[] } | undefined)?.previousScreen;
|
|
22
|
+
const moving = !!(Number(mouse[1]) & 32) && mouse[4] === "M";
|
|
23
|
+
if (!moving) { setPointer(state, false); void requestPreview(state, undefined); return undefined; }
|
|
24
|
+
const cached = state.hoverLink;
|
|
25
|
+
const sameTarget = cached?.row === y && x >= cached.start && x < cached.end;
|
|
26
|
+
const url = state.enabled()
|
|
27
|
+
? sameTarget ? pathToFileURL(cached.path).href : getOsc8LinkAtColumn(screen?.[y] ?? "", x)
|
|
28
|
+
: undefined;
|
|
29
|
+
let path: string | undefined;
|
|
30
|
+
if (url?.startsWith("file:")) {
|
|
31
|
+
try { const file = fileURLToPath(url); if (IMAGE_MIME[extname(file).toLowerCase()]) path = file; } catch { /* Reject malformed or remote file URLs. */ }
|
|
32
|
+
}
|
|
33
|
+
if (path && (path !== state.requestedPath || !sameTarget)) {
|
|
34
|
+
state.previewAnchor = { x, y };
|
|
35
|
+
if (path === state.requestedPath && state.preview.path) { positionPreview(state); state.previewTui?.requestRender(); }
|
|
36
|
+
let start = x, end = x + 1;
|
|
37
|
+
const line = screen?.[y] ?? "";
|
|
38
|
+
while (start > 0 && getOsc8LinkAtColumn(line, start - 1) === url) start--;
|
|
39
|
+
while (end < visibleWidth(line) && getOsc8LinkAtColumn(line, end) === url) end++;
|
|
40
|
+
state.hoverLink = { row: y, start, end, path };
|
|
41
|
+
} else if (!path) state.hoverLink = undefined;
|
|
42
|
+
setPointer(state, !!path);
|
|
43
|
+
void requestPreview(state, path);
|
|
44
|
+
}
|
|
45
|
+
if (!state.preview.path || !matchesKey(data, "escape")) return undefined;
|
|
46
|
+
void requestPreview(state, undefined);
|
|
47
|
+
return { consume: true };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function requestPreview(state: Enhancements, path: string | undefined): Promise<void> {
|
|
51
|
+
if (path && state.enabled() && path === state.requestedPath) return;
|
|
52
|
+
if (!path || !state.enabled()) state.hoverLink = undefined;
|
|
53
|
+
if (!path && !state.requestedPath && !state.preview.path) return;
|
|
54
|
+
state.requestedPath = state.enabled() ? path : undefined;
|
|
55
|
+
const token = ++state.previewToken;
|
|
56
|
+
if (!path || !state.enabled()) {
|
|
57
|
+
setPreview(state, undefined);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const cells = getCellDimensions();
|
|
61
|
+
const preview = await readPreview(path, state.cwd ?? process.cwd(), {
|
|
62
|
+
widthPx: Math.max(1, (state.tui?.terminal.columns ?? 80) - 2) * cells.widthPx,
|
|
63
|
+
heightPx: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2) * cells.heightPx,
|
|
64
|
+
});
|
|
65
|
+
if (token !== state.previewToken || !state.enabled()) return;
|
|
66
|
+
setPreview(state, preview);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function setPreview(state: Enhancements, preview: Preview | undefined): void {
|
|
70
|
+
// Overlay visibility only erases text; explicitly free the image owned by this preview.
|
|
71
|
+
if (state.preview.graphic?.imageId) state.tui?.terminal.write(deleteKittyImage(state.preview.graphic.imageId));
|
|
72
|
+
state.previewSource = preview;
|
|
73
|
+
state.previewLayout = imageLayoutKey();
|
|
74
|
+
const dimensions = preview?.kind === "image" ? getImageDimensions(preview.base64, preview.mimeType) : undefined;
|
|
75
|
+
const bandWidth = state.previewMode() === "inline" && state.editor && state.theme
|
|
76
|
+
? visibleWidth(inlinePreviewLines(state, state.theme, state.tui?.terminal.columns ?? 80)[0] ?? "") : 0;
|
|
77
|
+
const available = (state.tui?.terminal.columns ?? 80) - (bandWidth ? bandWidth + 4 : 2);
|
|
78
|
+
const graphic = preview?.kind === "image" && dimensions ? renderImage(preview.base64, dimensions, {
|
|
79
|
+
maxWidthCells: Math.max(1, Math.min(Math.floor(dimensions.widthPx / getCellDimensions().widthPx), available)),
|
|
80
|
+
maxHeightCells: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2),
|
|
81
|
+
imageId: allocateImageId(), moveCursor: false,
|
|
82
|
+
}) ?? undefined : undefined;
|
|
83
|
+
state.preview = {
|
|
84
|
+
path: preview?.path, graphic,
|
|
85
|
+
note: preview?.kind === "note" ? preview.note : graphic ? undefined : "终端未能生成图片预览",
|
|
86
|
+
};
|
|
87
|
+
if (state.preview.path && !state.overlayReady) showOverlay(state);
|
|
88
|
+
positionPreview(state);
|
|
89
|
+
state.previewTui?.requestRender();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function showOverlay(state: Enhancements): void {
|
|
93
|
+
if (!state.tui || !state.theme) return;
|
|
94
|
+
state.overlayReady = true;
|
|
95
|
+
state.previewOptions = { width: 60, maxHeight: "100%", nonCapturing: true, visible: () => state.enabled() && state.preview.path !== undefined };
|
|
96
|
+
state.previewHandle = state.tui.showOverlay({
|
|
97
|
+
render: width => {
|
|
98
|
+
if (state.previewLayout !== imageLayoutKey()) setPreview(state, state.previewSource);
|
|
99
|
+
return previewLines(state.preview, state.theme!, width);
|
|
100
|
+
},
|
|
101
|
+
invalidate: () => {},
|
|
102
|
+
}, state.previewOptions);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function positionPreview(state: Enhancements): void {
|
|
106
|
+
if (!state.previewOptions || !state.tui || !state.theme) return;
|
|
107
|
+
const { rows, columns } = state.tui.terminal;
|
|
108
|
+
const width = Math.max(3, Math.min((state.preview.graphic?.columns ?? 26) + 2, columns || 80));
|
|
109
|
+
const height = Math.min(rows, previewLines(state.preview, state.theme, width).length);
|
|
110
|
+
const { x, y } = state.previewAnchor ?? { x: 0, y: rows - 2 };
|
|
111
|
+
const previewRow = y + 1 + height <= rows ? y + 1 : Math.max(0, y - height);
|
|
112
|
+
// Keep hover previews out of the draft attachment band. If there is no safe
|
|
113
|
+
// vertical gap, move to the side rather than painting over the thumbnail.
|
|
114
|
+
const band = state.previewMode() === "inline" && state.editor && state.theme
|
|
115
|
+
? inlinePreviewLines(state, state.theme, columns).length : 0;
|
|
116
|
+
const overlapsBand = band > 0 && previewRow < y && previewRow + height > y - band - 1;
|
|
117
|
+
const bandWidth = band && state.theme && state.editor ? visibleWidth(inlinePreviewLines(state, state.theme, columns)[0] ?? "") : 0;
|
|
118
|
+
const side = Math.min(columns - width, bandWidth + 2);
|
|
119
|
+
const beside = overlapsBand && side >= bandWidth + 2;
|
|
120
|
+
Object.assign(state.previewOptions, { width, col: beside ? side : Math.max(0, Math.min(x, columns - width)),
|
|
121
|
+
row: beside ? Math.max(0, Math.min(y + 1, rows - height)) : previewRow });
|
|
122
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { getCapabilities, getCellDimensions, truncateToWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
import type { PreviewState } from "./input-enhancements-types.ts";
|
|
4
|
+
|
|
5
|
+
export function positionedGraphic(sequence: string, up: number, right: number): string {
|
|
6
|
+
// Pi <=0.87's ANSI slicer needs an SGR terminator after relative motion.
|
|
7
|
+
// Otty places Kitty graphics against the last committed cursor while DEC 2026
|
|
8
|
+
// buffers text/cursor updates. Commit the target before the APC, then resume
|
|
9
|
+
// Pi's synchronized frame. Other terminals retain their atomic rendering.
|
|
10
|
+
const flush = process.env.TERM_PROGRAM?.toLowerCase() === "otty"
|
|
11
|
+
&& !process.env.TMUX && !process.env.STY && !/^(tmux|screen)/i.test(process.env.TERM ?? "")
|
|
12
|
+
&& sequence.startsWith("\x1b_G");
|
|
13
|
+
return `\x1b[s\x1b[${up}A\x1b[${right}C\x1b[0m${flush ? "\x1b[?2026l\x1b[0m" : ""}${sequence}\x1b[u${flush ? "\x1b[?2026h" : ""}\x1b[0m`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function imageLayoutKey(): string {
|
|
17
|
+
const cells = getCellDimensions();
|
|
18
|
+
return `${getCapabilities().images}:${cells.widthPx}:${cells.heightPx}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A tightly sized image frame. Draw after clearing its interior, never a path-only tooltip. */
|
|
22
|
+
export function previewLines(preview: PreviewState, theme: ExtensionContext["ui"]["theme"], width: number): string[] {
|
|
23
|
+
if (!preview.path) return [];
|
|
24
|
+
const graphic = preview.graphic;
|
|
25
|
+
const innerWidth = Math.max(1, Math.min(width - 2, graphic?.columns ?? 26));
|
|
26
|
+
const border = (text: string) => theme.fg("border", text);
|
|
27
|
+
const lines = [border(`╭${"─".repeat(innerWidth)}╮`)];
|
|
28
|
+
if (graphic) {
|
|
29
|
+
for (let row = 0; row < graphic.rows; row++) lines.push(border("│") + " ".repeat(innerWidth) + border("│"));
|
|
30
|
+
} else lines.push(border("│") + truncateToWidth(preview.note ?? "无法预览图片", innerWidth, "", true) + border("│"));
|
|
31
|
+
const draw = graphic ? positionedGraphic(graphic.sequence, graphic.rows, 1) : "";
|
|
32
|
+
lines.push(draw + border(`╰${"─".repeat(innerWidth)}╯`));
|
|
33
|
+
return lines;
|
|
34
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { resizeImage } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { getImageDimensions, stripTerminalSequences, visibleWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
import { filePaths } from "./file-links.ts";
|
|
4
|
+
import { open } from "node:fs/promises";
|
|
5
|
+
import { existsSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { dirname, extname, isAbsolute, join, resolve } from "node:path";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
|
|
10
|
+
export const MAX_PREVIEW_BYTES = 20 * 1024 * 1024;
|
|
11
|
+
const MAX_PREVIEW_ENCODED_BYTES = 1024 * 1024;
|
|
12
|
+
const MAX_PREVIEW_WIDTH_PX = 1200;
|
|
13
|
+
const MAX_PREVIEW_HEIGHT_PX = 800;
|
|
14
|
+
|
|
15
|
+
export const IMAGE_MIME: Record<string, string> = {
|
|
16
|
+
".png": "image/png",
|
|
17
|
+
".jpg": "image/jpeg",
|
|
18
|
+
".jpeg": "image/jpeg",
|
|
19
|
+
".gif": "image/gif",
|
|
20
|
+
".webp": "image/webp",
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export interface ImagePathMatch {
|
|
24
|
+
path: string;
|
|
25
|
+
/** Source indices in the line (after terminal sequences are stripped). */
|
|
26
|
+
start: number;
|
|
27
|
+
end: number;
|
|
28
|
+
/** Visible columns, for rendered lines. */
|
|
29
|
+
startCol: number;
|
|
30
|
+
endCol: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function absolutePath(path: string, cwd: string): string {
|
|
34
|
+
if (path === "~") return homedir();
|
|
35
|
+
if (path.startsWith("~/")) return join(homedir(), path.slice(2));
|
|
36
|
+
return isAbsolute(path) ? path : resolve(cwd, path);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Image paths in one line, with source indices and visible columns. */
|
|
40
|
+
export function imagePathsInLine(line: string): ImagePathMatch[] {
|
|
41
|
+
const plain = stripTerminalSequences(line);
|
|
42
|
+
const matches: ImagePathMatch[] = [];
|
|
43
|
+
// ponytail: accept existing absolute clipboard paths with spaces; extend to cwd-aware relative paths if needed.
|
|
44
|
+
const spaced = [...plain.matchAll(/(?:^|[\s"'`])((?:\/|~\/|\.\.?\/)[^\n"'`<>()[\]{},。;!?]+?\.(?:png|jpe?g|gif|webp))(?=$|[\s"'`<>()[\]{},。;!?])/gi)]
|
|
45
|
+
.map(match => ({ path: match[1], start: match.index + match[0].length - match[1].length, end: match.index + match[0].length }))
|
|
46
|
+
.filter(match => isAbsolute(match.path) && match.path.includes(" ") && existsSync(match.path));
|
|
47
|
+
for (const { path, start, end } of [...spaced, ...filePaths(plain).filter(match => !spaced.some(full => match.start >= full.start && match.start < full.end))]) {
|
|
48
|
+
if (!IMAGE_MIME[extname(path).toLowerCase()]) continue;
|
|
49
|
+
matches.push({ path, start, end, startCol: visibleWidth(plain.slice(0, start)), endCol: visibleWidth(plain.slice(0, end)) });
|
|
50
|
+
}
|
|
51
|
+
return matches;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Image path token the cursor sits in, if any. */
|
|
55
|
+
export function imagePathAtCursor(text: string, line: number, col: number): string | undefined {
|
|
56
|
+
const current = text.split("\n")[line];
|
|
57
|
+
if (current === undefined) return undefined;
|
|
58
|
+
return imagePathsInLine(current).find((match) => col >= match.start && col <= match.end)?.path;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** OSC 8 target for an image path: the `file://` URL of its directory. */
|
|
62
|
+
export function imageDirectoryUrl(path: string, cwd: string): string {
|
|
63
|
+
return pathToFileURL(dirname(absolutePath(path, cwd))).href;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface PreviewImage {
|
|
67
|
+
kind: "image";
|
|
68
|
+
path: string;
|
|
69
|
+
mimeType: string;
|
|
70
|
+
base64: string;
|
|
71
|
+
widthPx: number;
|
|
72
|
+
heightPx: number;
|
|
73
|
+
}
|
|
74
|
+
export interface PreviewNote {
|
|
75
|
+
kind: "note";
|
|
76
|
+
path: string;
|
|
77
|
+
note: string;
|
|
78
|
+
}
|
|
79
|
+
export type Preview = PreviewImage | PreviewNote;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Read a preview for an image path. Returns undefined when there is nothing to show
|
|
83
|
+
* (unknown extension, missing file, directory) so typing never raises a hint.
|
|
84
|
+
*/
|
|
85
|
+
export async function readPreview(path: string, cwd: string, bounds = { widthPx: MAX_PREVIEW_WIDTH_PX, heightPx: MAX_PREVIEW_HEIGHT_PX }): Promise<Preview | undefined> {
|
|
86
|
+
const absolute = absolutePath(path, cwd);
|
|
87
|
+
const mimeType = IMAGE_MIME[extname(absolute).toLowerCase()];
|
|
88
|
+
if (!mimeType) return undefined;
|
|
89
|
+
const file = await open(absolute, "r").catch(() => undefined);
|
|
90
|
+
if (!file) return undefined;
|
|
91
|
+
try {
|
|
92
|
+
const info = await file.stat();
|
|
93
|
+
if (!info.isFile()) return undefined;
|
|
94
|
+
if (info.size > MAX_PREVIEW_BYTES) return { kind: "note", path, note: `超过 ${MAX_PREVIEW_BYTES / 1024 / 1024}MB` };
|
|
95
|
+
const bytes = Buffer.alloc(info.size);
|
|
96
|
+
let offset = 0;
|
|
97
|
+
while (offset < bytes.length) {
|
|
98
|
+
const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
|
|
99
|
+
if (!bytesRead) break;
|
|
100
|
+
offset += bytesRead;
|
|
101
|
+
}
|
|
102
|
+
const data = bytes.subarray(0, offset);
|
|
103
|
+
const base64 = data.toString("base64");
|
|
104
|
+
const dimensions = getImageDimensions(base64, mimeType);
|
|
105
|
+
if (!dimensions) return { kind: "note", path, note: "无法解析图片尺寸" };
|
|
106
|
+
const maxWidth = Math.max(1, Math.min(MAX_PREVIEW_WIDTH_PX, Math.floor(bounds.widthPx)));
|
|
107
|
+
const maxHeight = Math.max(1, Math.min(MAX_PREVIEW_HEIGHT_PX, Math.floor(bounds.heightPx)));
|
|
108
|
+
// renderImage controls cell placement, not pixels; its Kitty f=100 payload must be PNG.
|
|
109
|
+
const resized = dimensions.widthPx <= maxWidth && dimensions.heightPx <= maxHeight && base64.length < MAX_PREVIEW_ENCODED_BYTES
|
|
110
|
+
? { data: base64, mimeType } : await resizeImage(data, mimeType, { maxWidth, maxHeight, maxBytes: MAX_PREVIEW_ENCODED_BYTES });
|
|
111
|
+
if (!resized) return { kind: "note", path, note: "无法缩小图片预览" };
|
|
112
|
+
const png = resized.mimeType === "image/png" ? resized
|
|
113
|
+
: await (await import("@earendil-works/pi-coding-agent")).convertToPng(resized.data, resized.mimeType);
|
|
114
|
+
if (!png) return { kind: "note", path, note: "无法转换图片预览" };
|
|
115
|
+
if (png.data.length > MAX_PREVIEW_ENCODED_BYTES) return { kind: "note", path, note: "图片预览过大" };
|
|
116
|
+
return { kind: "image", path, mimeType: png.mimeType, base64: png.data, widthPx: dimensions.widthPx, heightPx: dimensions.heightPx };
|
|
117
|
+
} catch {
|
|
118
|
+
return { kind: "note", path, note: "读取失败" };
|
|
119
|
+
} finally { await file.close(); }
|
|
120
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { allocateImageId, deleteKittyImage, encodeKitty, getCapabilities, getCellDimensions, getImageDimensions, renderImage, truncateToWidth, visibleWidth, type EditorComponent } from "@earendil-works/pi-tui";
|
|
3
|
+
import type { Enhancements } from "./input-enhancements-types.ts";
|
|
4
|
+
import { editorImagePaths } from "./input-editor-paths.ts";
|
|
5
|
+
import { imageLayoutKey, positionedGraphic } from "./input-image-graphics.ts";
|
|
6
|
+
import { readPreview } from "./input-image-paths.ts";
|
|
7
|
+
|
|
8
|
+
function draftImagePaths(editor: EditorComponent): string[] {
|
|
9
|
+
const source = (editor as EditorComponent & { state?: { lines: string[] } }).state?.lines ?? editor.getText().split("\n");
|
|
10
|
+
return source.flatMap(line => editorImagePaths(editor, line).map(match => match.path));
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function clearInlineGraphics(state: Pick<Enhancements, "inlineGraphics" | "tui">): void {
|
|
14
|
+
for (const graphic of state.inlineGraphics.values()) {
|
|
15
|
+
if (graphic.imageId) state.tui?.terminal.write(deleteKittyImage(graphic.imageId));
|
|
16
|
+
}
|
|
17
|
+
state.inlineGraphics.clear();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Only the editing draft is shown here; history hover remains the separate mode. */
|
|
21
|
+
export function syncInlineImages(state: Enhancements): void {
|
|
22
|
+
const paths = state.editor && state.enabled() && state.previewMode() === "inline"
|
|
23
|
+
? [...new Set(draftImagePaths(state.editor))].slice(0, 15) : [];
|
|
24
|
+
if (!paths.length) clearInlineGraphics(state);
|
|
25
|
+
for (const path of state.inlineImages.keys()) if (!paths.includes(path)) { state.inlineImages.delete(path); clearInlineGraphics(state); }
|
|
26
|
+
for (const path of state.inlinePending.keys()) if (!paths.includes(path)) state.inlinePending.delete(path);
|
|
27
|
+
for (const path of paths) {
|
|
28
|
+
if (state.inlineImages.has(path) || state.inlinePending.has(path)) continue;
|
|
29
|
+
const cwd = state.cwd ?? process.cwd();
|
|
30
|
+
// Cell placement scales the image; keep a bounded copy independent of startup cell metrics.
|
|
31
|
+
const pending = readPreview(path, cwd).catch(() => undefined);
|
|
32
|
+
state.inlinePending.set(path, pending);
|
|
33
|
+
void pending.then(preview => {
|
|
34
|
+
if (state.inlinePending.get(path) !== pending) return;
|
|
35
|
+
state.inlinePending.delete(path);
|
|
36
|
+
if (!state.editor || !state.enabled() || state.previewMode() !== "inline" || !draftImagePaths(state.editor).includes(path)) return;
|
|
37
|
+
state.inlineImages.set(path, preview);
|
|
38
|
+
state.tui?.requestRender();
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function inlinePreviewLines(state: Pick<Enhancements, "editor" | "enabled" | "previewMode" | "inlineImages" | "inlinePending" | "inlineGraphics" | "tui">, theme: ExtensionContext["ui"]["theme"], width: number): string[] {
|
|
44
|
+
const paths = state.editor && state.enabled() && state.previewMode() === "inline" && width >= 12 ? draftImagePaths(state.editor) : [];
|
|
45
|
+
if (!paths.length) { clearInlineGraphics(state); return []; }
|
|
46
|
+
const cardWidth = Math.min(14, width);
|
|
47
|
+
// ponytail: cards are capped at one row; beyond viewport width show compact numbered tags, upgrade to a gallery when scrolling is supported.
|
|
48
|
+
const count = Math.max(1, Math.floor((width + 2) / (cardWidth + 2)));
|
|
49
|
+
const protocol = getCapabilities().images;
|
|
50
|
+
const layout = `${cardWidth}:${imageLayoutKey()}`;
|
|
51
|
+
const keys = paths.slice(0, count).map((path, index) => `${index}:${path}`);
|
|
52
|
+
if ([...state.inlineGraphics].some(([key, graphic]) => graphic.layout !== layout || !keys.includes(key))) clearInlineGraphics(state);
|
|
53
|
+
const rows: string[] = [];
|
|
54
|
+
const color = (index: number, text: string) => theme.fg((["warning", "accent", "success", "error"] as const)[index % 4], text);
|
|
55
|
+
{
|
|
56
|
+
const cards = paths.slice(0, count).map((path, index) => {
|
|
57
|
+
const key = `${index}:${path}`;
|
|
58
|
+
const preview = state.inlineImages.get(path);
|
|
59
|
+
const dimensions = preview?.kind === "image" ? getImageDimensions(preview.base64, preview.mimeType) : undefined;
|
|
60
|
+
let graphic = state.inlineGraphics.get(key);
|
|
61
|
+
if (preview?.kind === "image" && dimensions && protocol && !graphic) {
|
|
62
|
+
const cells = getCellDimensions();
|
|
63
|
+
const scale = Math.min((cardWidth - 2) * cells.widthPx / dimensions.widthPx, 4 * cells.heightPx / dimensions.heightPx);
|
|
64
|
+
const columns = Math.min(cardWidth - 2, Math.ceil(dimensions.widthPx * scale / cells.widthPx));
|
|
65
|
+
const rows = Math.min(4, Math.ceil(dimensions.heightPx * scale / cells.heightPx));
|
|
66
|
+
const imageId = protocol === "kitty" ? allocateImageId() : undefined;
|
|
67
|
+
// ponytail: bottom-row placement must not register top-row crop metadata; use Pi's encoder until its layout API supports positioned graphics.
|
|
68
|
+
const rendered = protocol === "kitty"
|
|
69
|
+
? { sequence: encodeKitty(preview.base64, { imageId, columns, rows, moveCursor: false }), imageId, rows, columns }
|
|
70
|
+
: renderImage(preview.base64, dimensions, { maxWidthCells: cardWidth - 2, maxHeightCells: 4, moveCursor: false });
|
|
71
|
+
if (rendered) { graphic = { layout, ...rendered }; state.inlineGraphics.set(key, graphic); }
|
|
72
|
+
}
|
|
73
|
+
const frame = (text: string) => color(index, text);
|
|
74
|
+
const rim = (text: string, top: boolean) => {
|
|
75
|
+
const caption = truncateToWidth(text, cardWidth - 4, "…");
|
|
76
|
+
const fill = cardWidth - 4 - visibleWidth(caption);
|
|
77
|
+
return frame(`${top ? "╭" : "╰"}${"─".repeat(Math.floor(fill / 2))} ${caption} ${"─".repeat(Math.ceil(fill / 2))}${top ? "╮" : "╯"}`);
|
|
78
|
+
};
|
|
79
|
+
const top = rim(` #${index + 1}`, true);
|
|
80
|
+
const size = preview?.kind === "image" ? `${preview.widthPx}x${preview.heightPx}` : state.inlinePending.has(path) ? "加载中" : "无法预览";
|
|
81
|
+
return { graphic, preview, top, size, rim, frame };
|
|
82
|
+
});
|
|
83
|
+
// OMP's 12x4 inner grid; never grow a tall empty box for a wide image.
|
|
84
|
+
const bodyHeight = 4;
|
|
85
|
+
rows.push(cards.map(card => card.top).join(" "));
|
|
86
|
+
for (let row = 0; row < bodyHeight; row++) rows.push(cards.map(card => {
|
|
87
|
+
const content = row === 0 && !card.graphic ? truncateToWidth(card.preview?.kind === "note" ? card.preview.note : card.size === "加载中" ? "加载中" : "无法预览", cardWidth - 4, "…") : "";
|
|
88
|
+
const left = card.graphic ? Math.floor((cardWidth - 2 - card.graphic.columns) / 2) : 0;
|
|
89
|
+
return card.frame("│") + " ".repeat(left) + " ".repeat(cardWidth - 2 - left - visibleWidth(content)) + content + card.frame("│");
|
|
90
|
+
}).join(" "));
|
|
91
|
+
const bottom = cards.map(card => card.rim(card.size, false)).join(" ");
|
|
92
|
+
// Draw the cleared card first, then place images over its interior from the final row.
|
|
93
|
+
const drawings = cards.map((card, index) => {
|
|
94
|
+
if (!card.graphic) return "";
|
|
95
|
+
const topPad = Math.floor((bodyHeight - card.graphic.rows) / 2);
|
|
96
|
+
const leftPad = Math.floor((cardWidth - 2 - card.graphic.columns) / 2);
|
|
97
|
+
const up = bodyHeight - topPad;
|
|
98
|
+
const right = index * (cardWidth + 2) + leftPad + 1;
|
|
99
|
+
return positionedGraphic(card.graphic.sequence, up, right);
|
|
100
|
+
}).join("");
|
|
101
|
+
rows.push(drawings + bottom);
|
|
102
|
+
}
|
|
103
|
+
if (paths.length > count) {
|
|
104
|
+
rows.push("");
|
|
105
|
+
let line = "";
|
|
106
|
+
for (let index = count; index < paths.length; index++) {
|
|
107
|
+
const tag = color(index, ` #${index + 1}`);
|
|
108
|
+
if (visibleWidth(line) + visibleWidth(tag) + 2 > width) { rows.push(line); line = ""; }
|
|
109
|
+
line += (line ? " " : "") + tag;
|
|
110
|
+
}
|
|
111
|
+
if (line) rows.push(line);
|
|
112
|
+
}
|
|
113
|
+
return rows;
|
|
114
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { stripFrontmatter, type ExtensionAPI, type ExtensionContext, type InputEvent, type InputEventResult } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { AutocompleteItem, AutocompleteProvider } from "@earendil-works/pi-tui";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { dirname } from "node:path";
|
|
5
|
+
import type { Enhancements } from "./input-enhancements-types.ts";
|
|
6
|
+
|
|
7
|
+
const SKILL_TOKEN = /(?:^|\s)(\/skill:[^\s/]+)/g;
|
|
8
|
+
export const SKILL_PREFIX = /(?:^|[ \t])(\/(?:skill:)?[^/\s]*)$/;
|
|
9
|
+
|
|
10
|
+
export interface SkillEntry {
|
|
11
|
+
/** Registry command name, e.g. `skill:release`. */
|
|
12
|
+
command: string;
|
|
13
|
+
name: string;
|
|
14
|
+
path: string;
|
|
15
|
+
baseDir: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Skills registered for this session, keyed by command name (`skill:<name>`). */
|
|
19
|
+
export function readSkillCommands(pi: Pick<ExtensionAPI, "getCommands">): Map<string, SkillEntry> {
|
|
20
|
+
const skills = new Map<string, SkillEntry>();
|
|
21
|
+
for (const command of pi.getCommands()) {
|
|
22
|
+
const path = command.sourceInfo?.path;
|
|
23
|
+
if (command.source !== "skill" || !path) continue;
|
|
24
|
+
skills.set(command.name, { command: command.name, name: command.name.replace(/^skill:/, ""), path, baseDir: command.sourceInfo.baseDir ?? dirname(path) });
|
|
25
|
+
}
|
|
26
|
+
return skills;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Same wrapper the core `_expandSkillCommand` uses. */
|
|
30
|
+
export function skillBlock(skill: SkillEntry, body: string): string {
|
|
31
|
+
return `<skill name="${skill.name}" location="${skill.path}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SkillToken {
|
|
35
|
+
token: string;
|
|
36
|
+
start: number;
|
|
37
|
+
end: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** `/skill:name` tokens at whitespace boundaries. */
|
|
41
|
+
export function skillTokensIn(text: string): SkillToken[] {
|
|
42
|
+
const tokens: SkillToken[] = [];
|
|
43
|
+
for (const match of text.matchAll(SKILL_TOKEN)) {
|
|
44
|
+
const token = match[1];
|
|
45
|
+
const start = match.index + match[0].length - token.length;
|
|
46
|
+
tokens.push({ token, start, end: start + token.length });
|
|
47
|
+
}
|
|
48
|
+
return tokens;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Expand registered `/skill:name` tokens that the core would not expand itself.
|
|
53
|
+
* Leave single leading skills to the core; expand multiple skills in place.
|
|
54
|
+
*/
|
|
55
|
+
export async function expandSkillTokens(
|
|
56
|
+
text: string,
|
|
57
|
+
skills: Map<string, SkillEntry>,
|
|
58
|
+
readSkill: (path: string) => Promise<string>,
|
|
59
|
+
onError: (skill: SkillEntry, error: unknown) => void,
|
|
60
|
+
): Promise<string | undefined> {
|
|
61
|
+
const tokens = skillTokensIn(text).filter((token) => skills.has(token.token.slice(1)));
|
|
62
|
+
if (tokens.length === 0 || (tokens.length === 1 && tokens[0].start === 0)) return undefined;
|
|
63
|
+
const parts: string[] = [];
|
|
64
|
+
let cursor = 0;
|
|
65
|
+
for (const token of tokens) {
|
|
66
|
+
const skill = skills.get(token.token.slice(1));
|
|
67
|
+
if (!skill) continue;
|
|
68
|
+
let body: string;
|
|
69
|
+
try {
|
|
70
|
+
body = stripFrontmatter(await readSkill(skill.path)).trim();
|
|
71
|
+
} catch (error) {
|
|
72
|
+
onError(skill, error);
|
|
73
|
+
continue; // Keep the token verbatim and let the rest of the text survive.
|
|
74
|
+
}
|
|
75
|
+
parts.push(text.slice(cursor, token.start), skillBlock(skill, body));
|
|
76
|
+
cursor = token.end;
|
|
77
|
+
}
|
|
78
|
+
if (parts.length === 0) return undefined;
|
|
79
|
+
parts.push(text.slice(cursor));
|
|
80
|
+
return parts.join("");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Skill completion layered on the built-in provider. */
|
|
84
|
+
export function createSkillAutocompleteProvider(current: AutocompleteProvider, listSkills: () => Map<string, SkillEntry>, enabled: () => boolean = () => true): AutocompleteProvider {
|
|
85
|
+
return {
|
|
86
|
+
triggerCharacters: ["/"],
|
|
87
|
+
async getSuggestions(lines, cursorLine, cursorCol, options) {
|
|
88
|
+
if (!enabled()) return current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
89
|
+
const before = (lines[cursorLine] ?? "").slice(0, cursorCol);
|
|
90
|
+
const match = SKILL_PREFIX.exec(before);
|
|
91
|
+
if (!match) return current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
92
|
+
const prefix = match[1];
|
|
93
|
+
const typed = prefix.slice(1).replace(/^skill:/, "");
|
|
94
|
+
const ours: AutocompleteItem[] = [];
|
|
95
|
+
for (const skill of listSkills().values()) {
|
|
96
|
+
if (skill.command.startsWith(`skill:${typed}`) || skill.name.startsWith(typed)) ours.push({ value: `/${skill.command}`, label: skill.command });
|
|
97
|
+
}
|
|
98
|
+
// Mid-line only skills: the built-in provider would offer file paths there.
|
|
99
|
+
if (cursorLine !== 0 || prefix.length !== before.length) return ours.length > 0 ? { items: ours, prefix } : current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
100
|
+
const builtin = await current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
101
|
+
const items = (builtin?.items ?? []).filter((item) => !ours.some((skill) => skill.value.slice(1) === item.value.replace(/^\//, "")));
|
|
102
|
+
if (items.length === 0 && ours.length === 0) return null;
|
|
103
|
+
return { items: [...items, ...ours], prefix };
|
|
104
|
+
},
|
|
105
|
+
applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
|
|
106
|
+
if (!item.value.startsWith("/skill:")) return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
|
|
107
|
+
// The built-in provider special-cases line-start slash commands; replace our own fragment.
|
|
108
|
+
const line = lines[cursorLine] ?? "";
|
|
109
|
+
const start = Math.max(0, cursorCol - prefix.length);
|
|
110
|
+
const rest = line.slice(cursorCol);
|
|
111
|
+
const text = `${item.value}${/^[ \t]/.test(rest) ? "" : " "}`;
|
|
112
|
+
const next = [...lines];
|
|
113
|
+
next[cursorLine] = `${line.slice(0, start)}${text}${rest}`;
|
|
114
|
+
return { lines: next, cursorLine, cursorCol: start + text.length };
|
|
115
|
+
},
|
|
116
|
+
shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
|
|
117
|
+
return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function handleInput(state: Enhancements, event: InputEvent, ctx: ExtensionContext): Promise<InputEventResult | undefined> {
|
|
123
|
+
if (!state.enabled() || event.source !== "interactive" || !event.text.includes("/skill:")) return undefined;
|
|
124
|
+
const skills = readSkillCommands(state.pi);
|
|
125
|
+
const text = await expandSkillTokens(
|
|
126
|
+
event.text,
|
|
127
|
+
skills,
|
|
128
|
+
(path) => readFile(path, "utf8"),
|
|
129
|
+
(skill) => ctx.ui.notify(`无法读取技能文件:${skill.path}`, "warning"),
|
|
130
|
+
);
|
|
131
|
+
return text === undefined ? undefined : { action: "transform", text };
|
|
132
|
+
}
|