@each1024/pi-mini-mode 2.0.19 → 2.0.21
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/extensions/footer-status.ts +64 -8
- package/lib/agent-render.ts +4 -4
- package/lib/agent-state.ts +170 -34
- package/lib/agent-widgets.ts +6 -3
- package/lib/assistant-images.ts +1 -1
- package/lib/decision-dock.ts +243 -0
- package/lib/input-enhancements-types.ts +2 -0
- package/lib/input-enhancements.ts +3 -1
- package/lib/input-hover-preview.ts +6 -4
- package/lib/input-image-graphics.ts +3 -2
- package/lib/input-image-paths.ts +36 -8
- package/lib/input-inline-images.ts +12 -4
- package/lib/input-skill-completion.ts +2 -1
- package/lib/link-hover.ts +100 -7
- package/lib/minimal-markdown.ts +22 -4
- package/lib/minimal-output.ts +56 -10
- package/lib/minimal-theme.ts +2 -2
- package/lib/semantic-badges.ts +274 -0
- package/lib/settings.html +12 -0
- package/lib/settings.ts +12 -4
- package/lib/token-speed.ts +67 -20
- package/lib/transcript-adapter.ts +14 -0
- package/lib/transcript-cards.ts +7 -6
- package/lib/transcript-notice-render.ts +9 -6
- package/lib/transcript-notices.ts +72 -16
- package/lib/update-banner.ts +220 -54
- package/package.json +1 -1
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { matchesKey, truncateToWidth, type Component, type TuiMouseEvent } from "@earendil-works/pi-tui";
|
|
3
|
+
import { stripVTControlCharacters } from "node:util";
|
|
4
|
+
import { isDecisionBadgeText, parseSemanticBadge } from "./semantic-badges.ts";
|
|
5
|
+
import type { UiLanguage } from "./settings.ts";
|
|
6
|
+
|
|
7
|
+
export interface DecisionChoice {
|
|
8
|
+
number: number;
|
|
9
|
+
label: string;
|
|
10
|
+
recommended: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface DecisionPrompt {
|
|
14
|
+
key: string;
|
|
15
|
+
choices: DecisionChoice[];
|
|
16
|
+
defaultIndex: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const DOCK_COPY: Record<UiLanguage, { title: string; nav: string; confirm: string; cancel: string; typeHint: string }> = {
|
|
20
|
+
zh: {
|
|
21
|
+
title: "选择处置方案(上下键或点击切换,回车发送)",
|
|
22
|
+
nav: "切换",
|
|
23
|
+
confirm: "确认",
|
|
24
|
+
cancel: "关闭",
|
|
25
|
+
typeHint: "直接打字可自由补充",
|
|
26
|
+
},
|
|
27
|
+
en: {
|
|
28
|
+
title: "Choose an option (Up/Down or click, Enter to send)",
|
|
29
|
+
nav: "navigate",
|
|
30
|
+
confirm: "select",
|
|
31
|
+
cancel: "dismiss",
|
|
32
|
+
typeHint: "or type freely below",
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
function stripFences(markdown: string): string {
|
|
37
|
+
const lines = markdown.split("\n");
|
|
38
|
+
const kept: string[] = [];
|
|
39
|
+
let fenceChar = "";
|
|
40
|
+
let fenceLen = 0;
|
|
41
|
+
for (const line of lines) {
|
|
42
|
+
const match = /^ {0,3}(`{3,}|~{3,})/.exec(line);
|
|
43
|
+
if (match) {
|
|
44
|
+
const marker = match[1];
|
|
45
|
+
if (!fenceChar) {
|
|
46
|
+
fenceChar = marker[0];
|
|
47
|
+
fenceLen = marker.length;
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (marker[0] === fenceChar && marker.length >= fenceLen && /^ {0,3}[`~]+[ \t]*$/.test(line)) {
|
|
51
|
+
fenceChar = "";
|
|
52
|
+
fenceLen = 0;
|
|
53
|
+
}
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (!fenceChar) kept.push(line);
|
|
57
|
+
}
|
|
58
|
+
return kept.join("\n");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function cleanOptionLine(raw: string): { label: string; recommended: boolean } {
|
|
62
|
+
let recommended = false;
|
|
63
|
+
let cleaned = stripVTControlCharacters(raw)
|
|
64
|
+
.replace(/`?(\[[^\]\r\n`]{1,32}\])`?/g, (full, bracketed: string) => {
|
|
65
|
+
const badge = parseSemanticBadge(bracketed);
|
|
66
|
+
if (!badge) return full;
|
|
67
|
+
if (badge.tone === "success" && /推荐|recommended|★/i.test(badge.label)) recommended = true;
|
|
68
|
+
return `[${badge.label}]`;
|
|
69
|
+
})
|
|
70
|
+
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
|
|
71
|
+
.replace(/(\*\*|__|~~|\*|`)/g, "")
|
|
72
|
+
.replace(/\s+/g, " ")
|
|
73
|
+
.trim();
|
|
74
|
+
if (/★|推荐|recommended/i.test(cleaned)) recommended = true;
|
|
75
|
+
cleaned = cleaned.replace(/^[-::—–\s]+/, "");
|
|
76
|
+
return { label: cleaned, recommended };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Extract a 2..5 numbered option group when the assistant reply explicitly asks for a decision. */
|
|
80
|
+
export function extractDecisionPrompt(markdown: string | undefined, turnId: string | number = 0): DecisionPrompt | undefined {
|
|
81
|
+
if (!markdown) return undefined;
|
|
82
|
+
const prose = stripFences(markdown);
|
|
83
|
+
if (!isDecisionBadgeText(prose)) return undefined;
|
|
84
|
+
|
|
85
|
+
const groups: DecisionChoice[][] = [];
|
|
86
|
+
let current: DecisionChoice[] = [];
|
|
87
|
+
for (const rawLine of prose.split(/\r?\n/)) {
|
|
88
|
+
const trimmed = rawLine.trim();
|
|
89
|
+
if (!trimmed) continue;
|
|
90
|
+
const match = /^(\d{1,2})[.)、]\s+(.+)$/.exec(trimmed);
|
|
91
|
+
if (match) {
|
|
92
|
+
const num = Number(match[1]);
|
|
93
|
+
const { label, recommended } = cleanOptionLine(match[2]);
|
|
94
|
+
if (!label) continue;
|
|
95
|
+
if (current.length === 0 && num === 1) {
|
|
96
|
+
current = [{ number: 1, label, recommended }];
|
|
97
|
+
} else if (current.length > 0 && num === current.length + 1 && current.length < 5) {
|
|
98
|
+
current.push({ number: num, label, recommended });
|
|
99
|
+
} else if (num === 1) {
|
|
100
|
+
if (current.length >= 2) groups.push(current);
|
|
101
|
+
current = [{ number: 1, label, recommended }];
|
|
102
|
+
}
|
|
103
|
+
} else if (current.length > 0 && !rawLine.startsWith(" ") && !rawLine.startsWith("\t")) {
|
|
104
|
+
if (current.length >= 2) groups.push(current);
|
|
105
|
+
current = [];
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (current.length >= 2) groups.push(current);
|
|
109
|
+
const choices = groups.at(-1);
|
|
110
|
+
if (!choices || choices.length < 2) return undefined;
|
|
111
|
+
const recIdx = choices.findIndex((item) => item.recommended);
|
|
112
|
+
return {
|
|
113
|
+
key: `${turnId}:${choices.map((item) => item.label).join("|")}`,
|
|
114
|
+
choices,
|
|
115
|
+
defaultIndex: recIdx >= 0 ? recIdx : 0,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface DecisionDockOptions {
|
|
120
|
+
language: () => UiLanguage;
|
|
121
|
+
isEditorEmpty: () => boolean;
|
|
122
|
+
onSubmit: (replyText: string) => void;
|
|
123
|
+
requestRender: () => void;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function createDecisionDock(options: DecisionDockOptions) {
|
|
127
|
+
let activePrompt: DecisionPrompt | undefined;
|
|
128
|
+
let selectedIndex = 0;
|
|
129
|
+
const dismissedKeys = new Set<string>();
|
|
130
|
+
let optionStartRow = 2;
|
|
131
|
+
|
|
132
|
+
const sync = (prompt: DecisionPrompt | undefined): boolean => {
|
|
133
|
+
if (!prompt || dismissedKeys.has(prompt.key)) {
|
|
134
|
+
if (!activePrompt) return false;
|
|
135
|
+
activePrompt = undefined;
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
if (activePrompt?.key === prompt.key) return false;
|
|
139
|
+
activePrompt = prompt;
|
|
140
|
+
selectedIndex = prompt.defaultIndex;
|
|
141
|
+
return true;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const dismiss = (): boolean => {
|
|
145
|
+
if (!activePrompt) return false;
|
|
146
|
+
dismissedKeys.add(activePrompt.key);
|
|
147
|
+
activePrompt = undefined;
|
|
148
|
+
options.requestRender();
|
|
149
|
+
return true;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const clearAll = (): void => {
|
|
153
|
+
activePrompt = undefined;
|
|
154
|
+
dismissedKeys.clear();
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const choose = (index: number): void => {
|
|
158
|
+
if (!activePrompt) return;
|
|
159
|
+
const choice = activePrompt.choices[index];
|
|
160
|
+
if (!choice) return;
|
|
161
|
+
dismissedKeys.add(activePrompt.key);
|
|
162
|
+
activePrompt = undefined;
|
|
163
|
+
options.onSubmit(`${choice.number}. ${choice.label}`);
|
|
164
|
+
options.requestRender();
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
const handleTerminalInput = (data: string): { consume?: boolean } | undefined => {
|
|
168
|
+
if (!activePrompt) return undefined;
|
|
169
|
+
if (matchesKey(data, "escape")) {
|
|
170
|
+
dismiss();
|
|
171
|
+
return { consume: true };
|
|
172
|
+
}
|
|
173
|
+
if (!options.isEditorEmpty()) return undefined;
|
|
174
|
+
if (matchesKey(data, "up")) {
|
|
175
|
+
selectedIndex = selectedIndex <= 0 ? activePrompt.choices.length - 1 : selectedIndex - 1;
|
|
176
|
+
options.requestRender();
|
|
177
|
+
return { consume: true };
|
|
178
|
+
}
|
|
179
|
+
if (matchesKey(data, "down")) {
|
|
180
|
+
selectedIndex = selectedIndex >= activePrompt.choices.length - 1 ? 0 : selectedIndex + 1;
|
|
181
|
+
options.requestRender();
|
|
182
|
+
return { consume: true };
|
|
183
|
+
}
|
|
184
|
+
if (matchesKey(data, "enter") || matchesKey(data, "return")) {
|
|
185
|
+
choose(selectedIndex);
|
|
186
|
+
return { consume: true };
|
|
187
|
+
}
|
|
188
|
+
return undefined;
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
const component = (theme: ExtensionContext["ui"]["theme"]): Component => ({
|
|
192
|
+
invalidate() {},
|
|
193
|
+
handleMouse(event: TuiMouseEvent) {
|
|
194
|
+
if (!activePrompt) return undefined;
|
|
195
|
+
const idx = event.y - optionStartRow;
|
|
196
|
+
if (idx < 0 || idx >= activePrompt.choices.length) return undefined;
|
|
197
|
+
if (event.type === "move" || event.type === "press") {
|
|
198
|
+
if (selectedIndex !== idx) {
|
|
199
|
+
selectedIndex = idx;
|
|
200
|
+
return { handled: true, render: true };
|
|
201
|
+
}
|
|
202
|
+
return { handled: true };
|
|
203
|
+
}
|
|
204
|
+
if (event.type === "click" && event.button === "left") {
|
|
205
|
+
choose(idx);
|
|
206
|
+
return { handled: true, render: true };
|
|
207
|
+
}
|
|
208
|
+
return undefined;
|
|
209
|
+
},
|
|
210
|
+
render(width: number): string[] {
|
|
211
|
+
if (!activePrompt || width < 16 || !options.isEditorEmpty()) return [];
|
|
212
|
+
const copy = DOCK_COPY[options.language()] ?? DOCK_COPY.zh;
|
|
213
|
+
const rule = theme.fg("borderMuted" as "muted", "─".repeat(width));
|
|
214
|
+
const pad = width >= 40 ? " " : "";
|
|
215
|
+
const rows: string[] = [
|
|
216
|
+
rule,
|
|
217
|
+
truncateToWidth(pad + theme.fg("accent", theme.bold(copy.title)), width, "…"),
|
|
218
|
+
];
|
|
219
|
+
optionStartRow = rows.length;
|
|
220
|
+
for (const [index, item] of activePrompt.choices.entries()) {
|
|
221
|
+
const selected = index === selectedIndex;
|
|
222
|
+
const prefix = selected ? "→ " : " ";
|
|
223
|
+
const body = `${item.number}. ${item.label}`;
|
|
224
|
+
const fitted = truncateToWidth(pad + prefix + body, width, "…");
|
|
225
|
+
rows.push(selected ? theme.fg("accent", fitted) : theme.fg("text", fitted));
|
|
226
|
+
}
|
|
227
|
+
const hints = `${theme.bold("↑↓")} ${copy.nav} ${theme.bold("enter")} ${copy.confirm} ${theme.bold("esc")} ${copy.cancel} · ${copy.typeHint}`;
|
|
228
|
+
rows.push(truncateToWidth(pad + theme.fg("muted", hints), width, "…"));
|
|
229
|
+
return rows;
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
return {
|
|
234
|
+
get isActive() {
|
|
235
|
+
return Boolean(activePrompt);
|
|
236
|
+
},
|
|
237
|
+
sync,
|
|
238
|
+
dismiss,
|
|
239
|
+
clearAll,
|
|
240
|
+
handleTerminalInput,
|
|
241
|
+
component,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
@@ -2,6 +2,7 @@ import type { spawn } from "node:child_process";
|
|
|
2
2
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import type { EditorComponent, OverlayHandle, OverlayOptions, renderImage, TUI } from "@earendil-works/pi-tui";
|
|
4
4
|
import type { Preview } from "./input-image-paths.ts";
|
|
5
|
+
import type { UiLanguage } from "./settings.ts";
|
|
5
6
|
|
|
6
7
|
export interface PreviewState {
|
|
7
8
|
path?: string;
|
|
@@ -38,6 +39,7 @@ export interface Enhancements {
|
|
|
38
39
|
hoverLink?: { row: number; start: number; end: number; path: string };
|
|
39
40
|
previewOptions?: OverlayOptions;
|
|
40
41
|
previewMode: () => "hover" | "inline";
|
|
42
|
+
language?: () => UiLanguage;
|
|
41
43
|
inlineImages: Map<string, Preview | undefined>;
|
|
42
44
|
inlinePending: Map<string, Promise<Preview | undefined>>;
|
|
43
45
|
inlineGraphics: Map<string, { layout: string } & NonNullable<ReturnType<typeof renderImage>>>;
|
|
@@ -18,6 +18,7 @@ import { installEditor, liveUI } from "./input-editor.ts";
|
|
|
18
18
|
import { handleTerminalInput, requestPreview, setPointer } from "./input-hover-preview.ts";
|
|
19
19
|
import { clearInlineGraphics, syncInlineImages } from "./input-inline-images.ts";
|
|
20
20
|
import { createSkillAutocompleteProvider, handleInput, readSkillCommands } from "./input-skill-completion.ts";
|
|
21
|
+
import type { UiLanguage } from "./settings.ts";
|
|
21
22
|
|
|
22
23
|
export { MAX_PREVIEW_BYTES, imagePathsInLine, imagePathAtCursor, imageDirectoryUrl, readPreview } from "./input-image-paths.ts";
|
|
23
24
|
export type { ImagePathMatch, PreviewImage, PreviewNote, Preview } from "./input-image-paths.ts";
|
|
@@ -31,12 +32,13 @@ export const INPUT_ENHANCEMENTS_SETTING = "pi-mini-mode-input-enhancements";
|
|
|
31
32
|
|
|
32
33
|
let installed: Enhancements | undefined;
|
|
33
34
|
|
|
34
|
-
export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext, isEnabled: boolean | (() => boolean), previewMode: () => "hover" | "inline" = () => "hover"): InputEnhancementsCleanup {
|
|
35
|
+
export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext, isEnabled: boolean | (() => boolean), previewMode: () => "hover" | "inline" = () => "hover", language: () => UiLanguage = () => "zh"): InputEnhancementsCleanup {
|
|
35
36
|
const enabled = typeof isEnabled === "function" ? isEnabled : () => isEnabled;
|
|
36
37
|
if (installed && installed.pi !== pi) installed.cleanup();
|
|
37
38
|
const state = installed?.pi === pi ? installed : (installed = createEnhancements(pi));
|
|
38
39
|
state.enabled = enabled;
|
|
39
40
|
state.previewMode = previewMode;
|
|
41
|
+
state.language = language;
|
|
40
42
|
state.ctx = ctx;
|
|
41
43
|
state.cwd = ctx.cwd;
|
|
42
44
|
state.theme = ctx.hasUI ? ctx.ui.theme : undefined;
|
|
@@ -85,10 +85,11 @@ export async function requestPreview(state: Enhancements, path: string | undefin
|
|
|
85
85
|
return;
|
|
86
86
|
}
|
|
87
87
|
const cells = getCellDimensions();
|
|
88
|
+
const lang = state.language?.() ?? "zh";
|
|
88
89
|
const preview = await readPreview(path, state.cwd ?? process.cwd(), {
|
|
89
90
|
widthPx: Math.max(1, (state.tui?.terminal.columns ?? 80) - 2) * cells.widthPx,
|
|
90
91
|
heightPx: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2) * cells.heightPx,
|
|
91
|
-
});
|
|
92
|
+
}, lang);
|
|
92
93
|
if (token !== state.previewToken || !state.enabled()) return;
|
|
93
94
|
setPreview(state, preview);
|
|
94
95
|
}
|
|
@@ -107,9 +108,10 @@ function setPreview(state: Enhancements, preview: Preview | undefined): void {
|
|
|
107
108
|
maxHeightCells: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2),
|
|
108
109
|
imageId: allocateImageId(), moveCursor: false,
|
|
109
110
|
}) ?? undefined : undefined;
|
|
111
|
+
const lang = state.language?.() ?? "zh";
|
|
110
112
|
state.preview = {
|
|
111
113
|
path: preview?.path, graphic,
|
|
112
|
-
note: preview?.kind === "note" ? preview.note : graphic ? undefined : "终端未能生成图片预览",
|
|
114
|
+
note: preview?.kind === "note" ? preview.note : graphic ? undefined : (lang === "en" ? "Terminal cannot render image preview" : "终端未能生成图片预览"),
|
|
113
115
|
};
|
|
114
116
|
if (state.preview.path && !state.overlayReady) showOverlay(state);
|
|
115
117
|
positionPreview(state);
|
|
@@ -123,7 +125,7 @@ function showOverlay(state: Enhancements): void {
|
|
|
123
125
|
state.previewHandle = state.tui.showOverlay({
|
|
124
126
|
render: width => {
|
|
125
127
|
if (state.previewLayout !== imageLayoutKey()) setPreview(state, state.previewSource);
|
|
126
|
-
return previewLines(state.preview, state.theme!, width);
|
|
128
|
+
return previewLines(state.preview, state.theme!, width, state.language?.() ?? "zh");
|
|
127
129
|
},
|
|
128
130
|
invalidate: () => {},
|
|
129
131
|
}, state.previewOptions);
|
|
@@ -133,7 +135,7 @@ export function positionPreview(state: Enhancements): void {
|
|
|
133
135
|
if (!state.previewOptions || !state.tui || !state.theme) return;
|
|
134
136
|
const { rows, columns } = state.tui.terminal;
|
|
135
137
|
const width = Math.max(3, Math.min((state.preview.graphic?.columns ?? 26) + 2, columns || 80));
|
|
136
|
-
const height = Math.min(rows, previewLines(state.preview, state.theme, width).length);
|
|
138
|
+
const height = Math.min(rows, previewLines(state.preview, state.theme, width, state.language?.() ?? "zh").length);
|
|
137
139
|
const { x, y } = state.previewAnchor ?? { x: 0, y: rows - 2 };
|
|
138
140
|
const previewRow = y + 1 + height <= rows ? y + 1 : Math.max(0, y - height);
|
|
139
141
|
// Keep hover previews out of the draft attachment band. If there is no safe
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { getCapabilities, getCellDimensions, truncateToWidth } from "@earendil-works/pi-tui";
|
|
3
3
|
import type { PreviewState } from "./input-enhancements-types.ts";
|
|
4
|
+
import type { UiLanguage } from "./settings.ts";
|
|
4
5
|
|
|
5
6
|
export function positionedGraphic(sequence: string, up: number, right: number): string {
|
|
6
7
|
// Pi <=0.87's ANSI slicer needs an SGR terminator after relative motion.
|
|
@@ -19,7 +20,7 @@ export function imageLayoutKey(): string {
|
|
|
19
20
|
}
|
|
20
21
|
|
|
21
22
|
/** 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
|
+
export function previewLines(preview: PreviewState, theme: ExtensionContext["ui"]["theme"], width: number, lang: UiLanguage = "zh"): string[] {
|
|
23
24
|
if (!preview.path) return [];
|
|
24
25
|
const graphic = preview.graphic;
|
|
25
26
|
const innerWidth = Math.max(1, Math.min(width - 2, graphic?.columns ?? 26));
|
|
@@ -27,7 +28,7 @@ export function previewLines(preview: PreviewState, theme: ExtensionContext["ui"
|
|
|
27
28
|
const lines = [border(`╭${"─".repeat(innerWidth)}╮`)];
|
|
28
29
|
if (graphic) {
|
|
29
30
|
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
|
+
} else lines.push(border("│") + truncateToWidth(preview.note ?? (lang === "en" ? "Cannot preview image" : "无法预览图片"), innerWidth, "", true) + border("│"));
|
|
31
32
|
const draw = graphic ? positionedGraphic(graphic.sequence, graphic.rows, 1) : "";
|
|
32
33
|
lines.push(draw + border(`╰${"─".repeat(innerWidth)}╯`));
|
|
33
34
|
return lines;
|
package/lib/input-image-paths.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { resizeImage } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { getImageDimensions, stripTerminalSequences, visibleWidth } from "@earendil-works/pi-tui";
|
|
3
3
|
import { filePaths } from "./file-links.ts";
|
|
4
|
+
import type { UiLanguage } from "./settings.ts";
|
|
4
5
|
import { open } from "node:fs/promises";
|
|
5
6
|
import { existsSync } from "node:fs";
|
|
6
7
|
import { homedir } from "node:os";
|
|
@@ -48,7 +49,7 @@ export function imagePathsInLine(line: string): ImagePathMatch[] {
|
|
|
48
49
|
if (!IMAGE_MIME[extname(path).toLowerCase()]) continue;
|
|
49
50
|
matches.push({ path, start, end, startCol: visibleWidth(plain.slice(0, start)), endCol: visibleWidth(plain.slice(0, end)) });
|
|
50
51
|
}
|
|
51
|
-
return matches;
|
|
52
|
+
return matches.sort((a, b) => a.start - b.start);
|
|
52
53
|
}
|
|
53
54
|
|
|
54
55
|
/** Image path token the cursor sits in, if any. */
|
|
@@ -78,11 +79,38 @@ export interface PreviewNote {
|
|
|
78
79
|
}
|
|
79
80
|
export type Preview = PreviewImage | PreviewNote;
|
|
80
81
|
|
|
82
|
+
const PREVIEW_NOTES: Record<UiLanguage, {
|
|
83
|
+
overLimit: (mb: number) => string;
|
|
84
|
+
badDimensions: string;
|
|
85
|
+
resizeFailed: string;
|
|
86
|
+
convertFailed: string;
|
|
87
|
+
tooLarge: string;
|
|
88
|
+
readFailed: string;
|
|
89
|
+
}> = {
|
|
90
|
+
zh: {
|
|
91
|
+
overLimit: mb => `超过 ${mb}MB`,
|
|
92
|
+
badDimensions: "无法解析图片尺寸",
|
|
93
|
+
resizeFailed: "无法缩小图片预览",
|
|
94
|
+
convertFailed: "无法转换图片预览",
|
|
95
|
+
tooLarge: "图片预览过大",
|
|
96
|
+
readFailed: "读取失败",
|
|
97
|
+
},
|
|
98
|
+
en: {
|
|
99
|
+
overLimit: mb => `Over ${mb}MB`,
|
|
100
|
+
badDimensions: "Cannot read image dimensions",
|
|
101
|
+
resizeFailed: "Cannot resize image preview",
|
|
102
|
+
convertFailed: "Cannot convert image preview",
|
|
103
|
+
tooLarge: "Image preview too large",
|
|
104
|
+
readFailed: "Read failed",
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
|
|
81
108
|
/**
|
|
82
109
|
* Read a preview for an image path. Returns undefined when there is nothing to show
|
|
83
110
|
* (unknown extension, missing file, directory) so typing never raises a hint.
|
|
84
111
|
*/
|
|
85
|
-
export async function readPreview(path: string, cwd: string, bounds = { widthPx: MAX_PREVIEW_WIDTH_PX, heightPx: MAX_PREVIEW_HEIGHT_PX }): Promise<Preview | undefined> {
|
|
112
|
+
export async function readPreview(path: string, cwd: string, bounds = { widthPx: MAX_PREVIEW_WIDTH_PX, heightPx: MAX_PREVIEW_HEIGHT_PX }, lang: UiLanguage = "zh"): Promise<Preview | undefined> {
|
|
113
|
+
const copy = PREVIEW_NOTES[lang] ?? PREVIEW_NOTES.zh;
|
|
86
114
|
const absolute = absolutePath(path, cwd);
|
|
87
115
|
const mimeType = IMAGE_MIME[extname(absolute).toLowerCase()];
|
|
88
116
|
if (!mimeType) return undefined;
|
|
@@ -91,7 +119,7 @@ export async function readPreview(path: string, cwd: string, bounds = { widthPx:
|
|
|
91
119
|
try {
|
|
92
120
|
const info = await file.stat();
|
|
93
121
|
if (!info.isFile()) return undefined;
|
|
94
|
-
if (info.size > MAX_PREVIEW_BYTES) return { kind: "note", path, note:
|
|
122
|
+
if (info.size > MAX_PREVIEW_BYTES) return { kind: "note", path, note: copy.overLimit(MAX_PREVIEW_BYTES / 1024 / 1024) };
|
|
95
123
|
const bytes = Buffer.alloc(info.size);
|
|
96
124
|
let offset = 0;
|
|
97
125
|
while (offset < bytes.length) {
|
|
@@ -102,19 +130,19 @@ export async function readPreview(path: string, cwd: string, bounds = { widthPx:
|
|
|
102
130
|
const data = bytes.subarray(0, offset);
|
|
103
131
|
const base64 = data.toString("base64");
|
|
104
132
|
const dimensions = getImageDimensions(base64, mimeType);
|
|
105
|
-
if (!dimensions) return { kind: "note", path, note:
|
|
133
|
+
if (!dimensions) return { kind: "note", path, note: copy.badDimensions };
|
|
106
134
|
const maxWidth = Math.max(1, Math.min(MAX_PREVIEW_WIDTH_PX, Math.floor(bounds.widthPx)));
|
|
107
135
|
const maxHeight = Math.max(1, Math.min(MAX_PREVIEW_HEIGHT_PX, Math.floor(bounds.heightPx)));
|
|
108
136
|
// renderImage controls cell placement, not pixels; its Kitty f=100 payload must be PNG.
|
|
109
137
|
const resized = dimensions.widthPx <= maxWidth && dimensions.heightPx <= maxHeight && base64.length < MAX_PREVIEW_ENCODED_BYTES
|
|
110
138
|
? { data: base64, mimeType } : await resizeImage(data, mimeType, { maxWidth, maxHeight, maxBytes: MAX_PREVIEW_ENCODED_BYTES });
|
|
111
|
-
if (!resized) return { kind: "note", path, note:
|
|
139
|
+
if (!resized) return { kind: "note", path, note: copy.resizeFailed };
|
|
112
140
|
const png = resized.mimeType === "image/png" ? resized
|
|
113
141
|
: 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:
|
|
142
|
+
if (!png) return { kind: "note", path, note: copy.convertFailed };
|
|
143
|
+
if (png.data.length > MAX_PREVIEW_ENCODED_BYTES) return { kind: "note", path, note: copy.tooLarge };
|
|
116
144
|
return { kind: "image", path, mimeType: png.mimeType, base64: png.data, widthPx: dimensions.widthPx, heightPx: dimensions.heightPx };
|
|
117
145
|
} catch {
|
|
118
|
-
return { kind: "note", path, note:
|
|
146
|
+
return { kind: "note", path, note: copy.readFailed };
|
|
119
147
|
} finally { await file.close(); }
|
|
120
148
|
}
|
|
@@ -4,6 +4,12 @@ import type { Enhancements } from "./input-enhancements-types.ts";
|
|
|
4
4
|
import { editorImagePaths } from "./input-editor-paths.ts";
|
|
5
5
|
import { imageLayoutKey, positionedGraphic } from "./input-image-graphics.ts";
|
|
6
6
|
import { readPreview } from "./input-image-paths.ts";
|
|
7
|
+
import type { UiLanguage } from "./settings.ts";
|
|
8
|
+
|
|
9
|
+
const INLINE_COPY: Record<UiLanguage, { loading: string; cannotPreview: string }> = {
|
|
10
|
+
zh: { loading: "加载中", cannotPreview: "无法预览" },
|
|
11
|
+
en: { loading: "Loading", cannotPreview: "No preview" },
|
|
12
|
+
};
|
|
7
13
|
|
|
8
14
|
function draftImagePaths(editor: EditorComponent): string[] {
|
|
9
15
|
const source = (editor as EditorComponent & { state?: { lines: string[] } }).state?.lines ?? editor.getText().split("\n");
|
|
@@ -27,8 +33,9 @@ export function syncInlineImages(state: Enhancements): void {
|
|
|
27
33
|
for (const path of paths) {
|
|
28
34
|
if (state.inlineImages.has(path) || state.inlinePending.has(path)) continue;
|
|
29
35
|
const cwd = state.cwd ?? process.cwd();
|
|
36
|
+
const lang = state.language?.() ?? "zh";
|
|
30
37
|
// Cell placement scales the image; keep a bounded copy independent of startup cell metrics.
|
|
31
|
-
const pending = readPreview(path, cwd).catch(() => undefined);
|
|
38
|
+
const pending = readPreview(path, cwd, undefined, lang).catch(() => undefined);
|
|
32
39
|
state.inlinePending.set(path, pending);
|
|
33
40
|
void pending.then(preview => {
|
|
34
41
|
if (state.inlinePending.get(path) !== pending) return;
|
|
@@ -40,9 +47,10 @@ export function syncInlineImages(state: Enhancements): void {
|
|
|
40
47
|
}
|
|
41
48
|
}
|
|
42
49
|
|
|
43
|
-
export function inlinePreviewLines(state: Pick<Enhancements, "editor" | "enabled" | "previewMode" | "inlineImages" | "inlinePending" | "inlineGraphics" | "tui">, theme: ExtensionContext["ui"]["theme"], width: number): string[] {
|
|
50
|
+
export function inlinePreviewLines(state: Pick<Enhancements, "editor" | "enabled" | "previewMode" | "inlineImages" | "inlinePending" | "inlineGraphics" | "tui" | "language">, theme: ExtensionContext["ui"]["theme"], width: number): string[] {
|
|
44
51
|
const paths = state.editor && state.enabled() && state.previewMode() === "inline" && width >= 12 ? draftImagePaths(state.editor) : [];
|
|
45
52
|
if (!paths.length) { clearInlineGraphics(state); return []; }
|
|
53
|
+
const copy = INLINE_COPY[state.language?.() ?? "zh"] ?? INLINE_COPY.zh;
|
|
46
54
|
const cardWidth = Math.min(14, width);
|
|
47
55
|
// ponytail: cards are capped at one row; beyond viewport width show compact numbered tags, upgrade to a gallery when scrolling is supported.
|
|
48
56
|
const count = Math.max(1, Math.floor((width + 2) / (cardWidth + 2)));
|
|
@@ -77,14 +85,14 @@ export function inlinePreviewLines(state: Pick<Enhancements, "editor" | "enabled
|
|
|
77
85
|
return frame(`${top ? "╭" : "╰"}${"─".repeat(Math.floor(fill / 2))} ${caption} ${"─".repeat(Math.ceil(fill / 2))}${top ? "╮" : "╯"}`);
|
|
78
86
|
};
|
|
79
87
|
const top = rim(` #${index + 1}`, true);
|
|
80
|
-
const size = preview?.kind === "image" ? `${preview.widthPx}x${preview.heightPx}` : state.inlinePending.has(path) ?
|
|
88
|
+
const size = preview?.kind === "image" ? `${preview.widthPx}x${preview.heightPx}` : state.inlinePending.has(path) ? copy.loading : copy.cannotPreview;
|
|
81
89
|
return { graphic, preview, top, size, rim, frame };
|
|
82
90
|
});
|
|
83
91
|
// OMP's 12x4 inner grid; never grow a tall empty box for a wide image.
|
|
84
92
|
const bodyHeight = 4;
|
|
85
93
|
rows.push(cards.map(card => card.top).join(" "));
|
|
86
94
|
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 ===
|
|
95
|
+
const content = row === 0 && !card.graphic ? truncateToWidth(card.preview?.kind === "note" ? card.preview.note : card.size === copy.loading ? copy.loading : copy.cannotPreview, cardWidth - 4, "…") : "";
|
|
88
96
|
const left = card.graphic ? Math.floor((cardWidth - 2 - card.graphic.columns) / 2) : 0;
|
|
89
97
|
return card.frame("│") + " ".repeat(left) + " ".repeat(cardWidth - 2 - left - visibleWidth(content)) + content + card.frame("│");
|
|
90
98
|
}).join(" "));
|
|
@@ -122,11 +122,12 @@ export function createSkillAutocompleteProvider(current: AutocompleteProvider, l
|
|
|
122
122
|
export async function handleInput(state: Enhancements, event: InputEvent, ctx: ExtensionContext): Promise<InputEventResult | undefined> {
|
|
123
123
|
if (!state.enabled() || event.source !== "interactive" || !event.text.includes("/skill:")) return undefined;
|
|
124
124
|
const skills = readSkillCommands(state.pi);
|
|
125
|
+
const lang = state.language?.() ?? "zh";
|
|
125
126
|
const text = await expandSkillTokens(
|
|
126
127
|
event.text,
|
|
127
128
|
skills,
|
|
128
129
|
(path) => readFile(path, "utf8"),
|
|
129
|
-
(skill) => ctx.ui.notify(`无法读取技能文件:${skill.path}`, "warning"),
|
|
130
|
+
(skill) => ctx.ui.notify(lang === "en" ? `Cannot read skill file: ${skill.path}` : `无法读取技能文件:${skill.path}`, "warning"),
|
|
130
131
|
);
|
|
131
132
|
return text === undefined ? undefined : { action: "transform", text };
|
|
132
133
|
}
|
package/lib/link-hover.ts
CHANGED
|
@@ -1,9 +1,105 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { sliceByColumn, visibleWidth, type TuiMouseEvent } from "@earendil-works/pi-tui";
|
|
2
2
|
|
|
3
3
|
/** OSC 8 identifies targets; standard mouse events and SGR supply hover feedback.
|
|
4
4
|
* Cmd is not a modifier in SGR mouse reports. The terminal owns Cmd underlining;
|
|
5
5
|
* Ctrl reports can provide the same feedback inside a mouse-capturing TUI.
|
|
6
6
|
*/
|
|
7
|
+
const LINK_CACHE_MAX = 2000;
|
|
8
|
+
const LINK_CACHE_MAX_SOURCE = 16384;
|
|
9
|
+
const NO_LINKS: readonly LinkSpan[] = [];
|
|
10
|
+
const linkSpans = new Map<string, LinkSpan[]>();
|
|
11
|
+
|
|
12
|
+
interface LinkSpan {
|
|
13
|
+
start: number;
|
|
14
|
+
end: number;
|
|
15
|
+
url: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function readAnsi(line: string, pos: number): number {
|
|
19
|
+
if (line.charCodeAt(pos) !== 0x1b) return 0;
|
|
20
|
+
const next = line[pos + 1];
|
|
21
|
+
if (next === "[") {
|
|
22
|
+
let end = pos + 2;
|
|
23
|
+
while (end < line.length && !/[mGKHJ]/.test(line[end])) end++;
|
|
24
|
+
return end < line.length ? end + 1 - pos : 0;
|
|
25
|
+
}
|
|
26
|
+
if (next === "]" || next === "_") {
|
|
27
|
+
let end = pos + 2;
|
|
28
|
+
while (end < line.length) {
|
|
29
|
+
if (line[end] === "\x07") return end + 1 - pos;
|
|
30
|
+
if (line[end] === "\x1b" && line[end + 1] === "\\") return end + 2 - pos;
|
|
31
|
+
end++;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** One left-to-right pass. Columns follow the same ANSI skipping rules as Pi's hit test. */
|
|
38
|
+
function parseLinkSpans(line: string): LinkSpan[] {
|
|
39
|
+
const spans: LinkSpan[] = [];
|
|
40
|
+
let column = 0;
|
|
41
|
+
let index = 0;
|
|
42
|
+
let active: string | undefined;
|
|
43
|
+
let start = 0;
|
|
44
|
+
const close = (next: string | undefined) => {
|
|
45
|
+
if (active !== undefined && column > start) {
|
|
46
|
+
const previous = spans.at(-1);
|
|
47
|
+
if (previous && previous.url === active && previous.end === start) previous.end = column;
|
|
48
|
+
else spans.push({ start, end: column, url: active });
|
|
49
|
+
}
|
|
50
|
+
active = next;
|
|
51
|
+
start = column;
|
|
52
|
+
};
|
|
53
|
+
while (index < line.length) {
|
|
54
|
+
let textEnd = index;
|
|
55
|
+
while (textEnd < line.length && !(line.charCodeAt(textEnd) === 0x1b && readAnsi(line, textEnd) > 0)) textEnd++;
|
|
56
|
+
if (textEnd > index) {
|
|
57
|
+
column += visibleWidth(line.slice(index, textEnd));
|
|
58
|
+
index = textEnd;
|
|
59
|
+
}
|
|
60
|
+
if (index >= line.length) break;
|
|
61
|
+
const length = readAnsi(line, index);
|
|
62
|
+
if (line.startsWith("\x1b]8;", index)) {
|
|
63
|
+
const match = /^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(line.slice(index, index + length));
|
|
64
|
+
if (match) close(match[1] || undefined);
|
|
65
|
+
}
|
|
66
|
+
index += length;
|
|
67
|
+
}
|
|
68
|
+
close(undefined);
|
|
69
|
+
return spans;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function linksFor(line: string): readonly LinkSpan[] {
|
|
73
|
+
if (!line.includes("\x1b]8;")) return NO_LINKS;
|
|
74
|
+
if (line.length > LINK_CACHE_MAX_SOURCE) return parseLinkSpans(line);
|
|
75
|
+
const cached = linkSpans.get(line);
|
|
76
|
+
if (cached) {
|
|
77
|
+
linkSpans.delete(line);
|
|
78
|
+
linkSpans.set(line, cached);
|
|
79
|
+
return cached;
|
|
80
|
+
}
|
|
81
|
+
const parsed = parseLinkSpans(line);
|
|
82
|
+
if (linkSpans.size >= LINK_CACHE_MAX) {
|
|
83
|
+
const first = linkSpans.keys().next().value;
|
|
84
|
+
if (first !== undefined) linkSpans.delete(first);
|
|
85
|
+
}
|
|
86
|
+
linkSpans.set(line, parsed);
|
|
87
|
+
return parsed;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function spanAt(spans: readonly LinkSpan[], column: number): LinkSpan | undefined {
|
|
91
|
+
let lo = 0;
|
|
92
|
+
let hi = spans.length - 1;
|
|
93
|
+
while (lo <= hi) {
|
|
94
|
+
const mid = (lo + hi) >> 1;
|
|
95
|
+
const span = spans[mid];
|
|
96
|
+
if (column < span.start) hi = mid - 1;
|
|
97
|
+
else if (column >= span.end) lo = mid + 1;
|
|
98
|
+
else return span;
|
|
99
|
+
}
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
7
103
|
export function createLinkHover(highlight: (text: string) => string) {
|
|
8
104
|
let rows: string[] = [];
|
|
9
105
|
let width = 0;
|
|
@@ -22,12 +118,9 @@ export function createLinkHover(highlight: (text: string) => string) {
|
|
|
22
118
|
hovered.underline = underline;
|
|
23
119
|
return changed;
|
|
24
120
|
}
|
|
25
|
-
const
|
|
26
|
-
if (!
|
|
27
|
-
|
|
28
|
-
while (start > 0 && getOsc8LinkAtColumn(source, start - 1) === url) start--;
|
|
29
|
-
while (end < visibleWidth(source) && getOsc8LinkAtColumn(source, end) === url) end++;
|
|
30
|
-
hovered = { row: event.y, start, end, source, underline };
|
|
121
|
+
const span = spanAt(linksFor(source), event.x);
|
|
122
|
+
if (!span) return clear();
|
|
123
|
+
hovered = { row: event.y, start: span.start, end: span.end, source, underline };
|
|
31
124
|
return true;
|
|
32
125
|
},
|
|
33
126
|
render(lines: string[], columns: number): string[] {
|