@each1024/pi-mini-mode 1.3.6 → 1.3.8

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.
@@ -0,0 +1,622 @@
1
+ /**
2
+ * Pi Mini Mode input enhancements.
3
+ *
4
+ * Adds, on top of Pi's native input handling (never replacing it):
5
+ * - skill completion for `/` at the line start or after whitespace, including `/skill:name`
6
+ * - inline `/skill:name` expansion (single leading skill commands stay native)
7
+ * - image-path preview in a non-capturing overlay (editing cursor and editor hover)
8
+ * - compact image labels with OSC 8 links to the original file
9
+ *
10
+ * Wiring: call `installInputEnhancements(pi, ctx, () => enabled)` from `session_start`
11
+ * and call cleanup.refresh() when the setting changes; call cleanup from
12
+ * `session_shutdown`.
13
+ */
14
+ import { CustomEditor, stripFrontmatter, type ExtensionAPI, type ExtensionContext, type InputEvent, type InputEventResult } from "@earendil-works/pi-coding-agent";
15
+ import {
16
+ allocateImageId, getImageDimensions, renderImage, getCapabilities, setCapabilities, getOsc8LinkAtColumn, matchesKey, stripTerminalSequences, truncateToWidth, visibleWidth,
17
+ type AutocompleteItem, type AutocompleteProvider, type Component, type EditorComponent, type TuiMouseEvent, type TUI, type OverlayHandle, type OverlayOptions,
18
+ } from "@earendil-works/pi-tui";
19
+ import { filePaths, inputCapabilities, linkRenderedPath, localPath } from "./file-links.ts";
20
+ import { open, readFile } from "node:fs/promises";
21
+ import { homedir } from "node:os";
22
+ import { dirname, extname, isAbsolute, join, resolve } from "node:path";
23
+ import { fileURLToPath, pathToFileURL } from "node:url";
24
+
25
+ export const INPUT_ENHANCEMENTS_SETTING = "pi-mini-mode-input-enhancements";
26
+ export const MAX_PREVIEW_BYTES = 20 * 1024 * 1024;
27
+
28
+ const IMAGE_MIME: Record<string, string> = {
29
+ ".png": "image/png",
30
+ ".jpg": "image/jpeg",
31
+ ".jpeg": "image/jpeg",
32
+ ".gif": "image/gif",
33
+ ".webp": "image/webp",
34
+ };
35
+ const SKILL_TOKEN = /(?:^|\s)(\/skill:[^\s/]+)/g;
36
+ const SKILL_PREFIX = /(?:^|[ \t])(\/(?:skill:)?[^/\s]*)$/;
37
+
38
+ export interface ImagePathMatch {
39
+ path: string;
40
+ /** Source indices in the line (after terminal sequences are stripped). */
41
+ start: number;
42
+ end: number;
43
+ /** Visible columns, for rendered lines. */
44
+ startCol: number;
45
+ endCol: number;
46
+ }
47
+
48
+ function absolutePath(path: string, cwd: string): string {
49
+ if (path === "~") return homedir();
50
+ if (path.startsWith("~/")) return join(homedir(), path.slice(2));
51
+ return isAbsolute(path) ? path : resolve(cwd, path);
52
+ }
53
+
54
+ /** Image paths in one line, with source indices and visible columns. */
55
+ export function imagePathsInLine(line: string): ImagePathMatch[] {
56
+ const plain = stripTerminalSequences(line);
57
+ const matches: ImagePathMatch[] = [];
58
+ for (const { path, start } of filePaths(plain)) {
59
+ if (!IMAGE_MIME[extname(path).toLowerCase()]) continue;
60
+ matches.push({ path, start, end: start + path.length, startCol: visibleWidth(plain.slice(0, start)), endCol: visibleWidth(plain.slice(0, start + path.length)) });
61
+ }
62
+ return matches;
63
+ }
64
+
65
+ /** Image path token the cursor sits in, if any. */
66
+ export function imagePathAtCursor(text: string, line: number, col: number): string | undefined {
67
+ const current = text.split("\n")[line];
68
+ if (current === undefined) return undefined;
69
+ return imagePathsInLine(current).find((match) => col >= match.start && col <= match.end)?.path;
70
+ }
71
+
72
+ /** OSC 8 target for an image path: the `file://` URL of its directory. */
73
+ export function imageDirectoryUrl(path: string, cwd: string): string {
74
+ return pathToFileURL(dirname(absolutePath(path, cwd))).href;
75
+ }
76
+
77
+ export interface PreviewImage {
78
+ kind: "image";
79
+ path: string;
80
+ mimeType: string;
81
+ base64: string;
82
+ }
83
+ export interface PreviewNote {
84
+ kind: "note";
85
+ path: string;
86
+ note: string;
87
+ }
88
+ export type Preview = PreviewImage | PreviewNote;
89
+
90
+ /**
91
+ * Read a preview for an image path. Returns undefined when there is nothing to show
92
+ * (unknown extension, missing file, directory) so typing never raises a hint.
93
+ */
94
+ export async function readPreview(path: string, cwd: string): Promise<Preview | undefined> {
95
+ const absolute = absolutePath(path, cwd);
96
+ const mimeType = IMAGE_MIME[extname(absolute).toLowerCase()];
97
+ if (!mimeType) return undefined;
98
+ const file = await open(absolute, "r").catch(() => undefined);
99
+ if (!file) return undefined;
100
+ try {
101
+ const info = await file.stat();
102
+ if (!info.isFile()) return undefined;
103
+ if (info.size > MAX_PREVIEW_BYTES) return { kind: "note", path, note: `超过 ${MAX_PREVIEW_BYTES / 1024 / 1024}MB` };
104
+ const bytes = Buffer.alloc(info.size);
105
+ let offset = 0;
106
+ while (offset < bytes.length) {
107
+ const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
108
+ if (!bytesRead) break;
109
+ offset += bytesRead;
110
+ }
111
+ return { kind: "image", path, mimeType, base64: bytes.subarray(0, offset).toString("base64") };
112
+ } catch {
113
+ return { kind: "note", path, note: "读取失败" };
114
+ } finally { await file.close(); }
115
+ }
116
+
117
+ export interface SkillEntry {
118
+ /** Registry command name, e.g. `skill:release`. */
119
+ command: string;
120
+ name: string;
121
+ path: string;
122
+ baseDir: string;
123
+ }
124
+
125
+ /** Skills registered for this session, keyed by command name (`skill:<name>`). */
126
+ export function readSkillCommands(pi: Pick<ExtensionAPI, "getCommands">): Map<string, SkillEntry> {
127
+ const skills = new Map<string, SkillEntry>();
128
+ for (const command of pi.getCommands()) {
129
+ const path = command.sourceInfo?.path;
130
+ if (command.source !== "skill" || !path) continue;
131
+ skills.set(command.name, { command: command.name, name: command.name.replace(/^skill:/, ""), path, baseDir: command.sourceInfo.baseDir ?? dirname(path) });
132
+ }
133
+ return skills;
134
+ }
135
+
136
+ /** Same wrapper the core `_expandSkillCommand` uses. */
137
+ export function skillBlock(skill: SkillEntry, body: string): string {
138
+ return `<skill name="${skill.name}" location="${skill.path}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
139
+ }
140
+
141
+ export interface SkillToken {
142
+ token: string;
143
+ start: number;
144
+ end: number;
145
+ }
146
+
147
+ /** `/skill:name` tokens at whitespace boundaries. */
148
+ export function skillTokensIn(text: string): SkillToken[] {
149
+ const tokens: SkillToken[] = [];
150
+ for (const match of text.matchAll(SKILL_TOKEN)) {
151
+ const token = match[1];
152
+ const start = match.index + match[0].length - token.length;
153
+ tokens.push({ token, start, end: start + token.length });
154
+ }
155
+ return tokens;
156
+ }
157
+
158
+ /**
159
+ * Expand registered `/skill:name` tokens that the core would not expand itself.
160
+ * Leave single leading skills to the core; expand multiple skills in place.
161
+ */
162
+ export async function expandSkillTokens(
163
+ text: string,
164
+ skills: Map<string, SkillEntry>,
165
+ readSkill: (path: string) => Promise<string>,
166
+ onError: (skill: SkillEntry, error: unknown) => void,
167
+ ): Promise<string | undefined> {
168
+ const tokens = skillTokensIn(text).filter((token) => skills.has(token.token.slice(1)));
169
+ if (tokens.length === 0 || (tokens.length === 1 && tokens[0].start === 0)) return undefined;
170
+ const parts: string[] = [];
171
+ let cursor = 0;
172
+ for (const token of tokens) {
173
+ const skill = skills.get(token.token.slice(1));
174
+ if (!skill) continue;
175
+ let body: string;
176
+ try {
177
+ body = stripFrontmatter(await readSkill(skill.path)).trim();
178
+ } catch (error) {
179
+ onError(skill, error);
180
+ continue; // Keep the token verbatim and let the rest of the text survive.
181
+ }
182
+ parts.push(text.slice(cursor, token.start), skillBlock(skill, body));
183
+ cursor = token.end;
184
+ }
185
+ if (parts.length === 0) return undefined;
186
+ parts.push(text.slice(cursor));
187
+ return parts.join("");
188
+ }
189
+
190
+ /** Skill completion layered on the built-in provider. */
191
+ export function createSkillAutocompleteProvider(current: AutocompleteProvider, listSkills: () => Map<string, SkillEntry>, enabled: () => boolean = () => true): AutocompleteProvider {
192
+ return {
193
+ triggerCharacters: ["/"],
194
+ async getSuggestions(lines, cursorLine, cursorCol, options) {
195
+ if (!enabled()) return current.getSuggestions(lines, cursorLine, cursorCol, options);
196
+ const before = (lines[cursorLine] ?? "").slice(0, cursorCol);
197
+ const match = SKILL_PREFIX.exec(before);
198
+ if (!match) return current.getSuggestions(lines, cursorLine, cursorCol, options);
199
+ const prefix = match[1];
200
+ const typed = prefix.slice(1).replace(/^skill:/, "");
201
+ const ours: AutocompleteItem[] = [];
202
+ for (const skill of listSkills().values()) {
203
+ if (skill.command.startsWith(`skill:${typed}`) || skill.name.startsWith(typed)) ours.push({ value: `/${skill.command}`, label: skill.command });
204
+ }
205
+ // Mid-line only skills: the built-in provider would offer file paths there.
206
+ if (cursorLine !== 0 || prefix.length !== before.length) return ours.length > 0 ? { items: ours, prefix } : current.getSuggestions(lines, cursorLine, cursorCol, options);
207
+ const builtin = await current.getSuggestions(lines, cursorLine, cursorCol, options);
208
+ const items = (builtin?.items ?? []).filter((item) => !ours.some((skill) => skill.value.slice(1) === item.value.replace(/^\//, "")));
209
+ if (items.length === 0 && ours.length === 0) return null;
210
+ return { items: [...items, ...ours], prefix };
211
+ },
212
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
213
+ if (!item.value.startsWith("/skill:")) return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
214
+ // The built-in provider special-cases line-start slash commands; replace our own fragment.
215
+ const line = lines[cursorLine] ?? "";
216
+ const start = Math.max(0, cursorCol - prefix.length);
217
+ const rest = line.slice(cursorCol);
218
+ const text = `${item.value}${/^[ \t]/.test(rest) ? "" : " "}`;
219
+ const next = [...lines];
220
+ next[cursorLine] = `${line.slice(0, start)}${text}${rest}`;
221
+ return { lines: next, cursorLine, cursorCol: start + text.length };
222
+ },
223
+ shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
224
+ return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
225
+ },
226
+ };
227
+ }
228
+
229
+ export interface PreviewState {
230
+ path?: string;
231
+ note?: string;
232
+ graphic?: NonNullable<ReturnType<typeof renderImage>>;
233
+ }
234
+
235
+ /** A tightly sized image frame. Draw after clearing its interior, never a path-only tooltip. */
236
+ export function previewLines(preview: PreviewState, theme: ExtensionContext["ui"]["theme"], width: number, origin = { row: 0, col: 0 }): string[] {
237
+ if (!preview.path) return [];
238
+ const graphic = preview.graphic;
239
+ const innerWidth = Math.max(1, Math.min(width - 2, graphic?.columns ?? 26));
240
+ const border = (text: string) => theme.fg("border", text);
241
+ const lines = [border(`╭${"─".repeat(innerWidth)}╮`)];
242
+ if (graphic) {
243
+ for (let row = 0; row < graphic.rows; row++) lines.push(border("│") + " ".repeat(innerWidth) + border("│"));
244
+ } else lines.push(border("│") + truncateToWidth(preview.note ?? "无法预览图片", innerWidth, "", true) + border("│"));
245
+ // Absolute H survives Pi 0.85's ANSI slicer; restore to the border before any padding is painted.
246
+ const draw = graphic ? `\x1b[${origin.row + 2};${origin.col + 2}H${graphic.sequence}\x1b[${origin.row + graphic.rows + 2};${origin.col + 1}H` : "";
247
+ lines.push(draw + border(`╰${"─".repeat(innerWidth)}╯`));
248
+ return lines;
249
+ }
250
+
251
+ type EditorFactoryFunction = NonNullable<Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0]>;
252
+ type CursorEditor = EditorComponent & { getCursor?(): { line: number; col: number } };
253
+
254
+ export interface InputEnhancementsCleanup {
255
+ (): void;
256
+ refresh(): void;
257
+ }
258
+
259
+ interface Enhancements {
260
+ pi: ExtensionAPI;
261
+ enabled: () => boolean;
262
+ ctx?: ExtensionContext;
263
+ cwd?: string;
264
+ theme?: ExtensionContext["ui"]["theme"];
265
+ generation?: unknown;
266
+ preview: PreviewState;
267
+ previewToken: number;
268
+ overlayReady: boolean;
269
+ previewTui?: { requestRender(): void };
270
+ previewHandle?: OverlayHandle;
271
+ tui?: TUI;
272
+ requestedPath?: string;
273
+ pointer?: boolean;
274
+ previewAnchor?: { x: number; y: number };
275
+ previewOptions?: OverlayOptions;
276
+ baseFactory?: EditorFactoryFunction;
277
+ editor?: EditorComponent;
278
+ editorFactory?: EditorFactoryFunction;
279
+ unsubscribeInput?: () => void;
280
+ restoreViewportInput?: () => void;
281
+ cleanup: InputEnhancementsCleanup;
282
+ }
283
+
284
+ let installed: Enhancements | undefined;
285
+ let viewportHook: { restore(): void } | undefined;
286
+
287
+ /** TUI survives /new; detach any previous instance's mouse hook before wrapping again. */
288
+ function unhookViewportInput(): void {
289
+ viewportHook?.restore();
290
+ viewportHook = undefined;
291
+ }
292
+
293
+ function hookViewportInput(tui: TUI, onInput: (data: string) => void): () => void {
294
+ unhookViewportInput();
295
+ const viewport = tui as TUI & { handleViewportInput?(data: string): { consume?: boolean } | undefined };
296
+ const original = viewport.handleViewportInput;
297
+ if (!original) return () => {};
298
+ const observe = (data: string) => {
299
+ onInput(data);
300
+ return original.call(tui, data);
301
+ };
302
+ viewport.handleViewportInput = observe;
303
+ const hook = {
304
+ restore() {
305
+ if (viewport.handleViewportInput === observe) viewport.handleViewportInput = original;
306
+ },
307
+ };
308
+ viewportHook = hook;
309
+ return () => {
310
+ if (viewportHook !== hook) return;
311
+ unhookViewportInput();
312
+ };
313
+ }
314
+
315
+ function liveUI(ctx?: ExtensionContext): ExtensionContext["ui"] | undefined {
316
+ if (!ctx) return undefined;
317
+ try {
318
+ return ctx.ui;
319
+ } catch {
320
+ return undefined;
321
+ }
322
+ }
323
+
324
+ /** Compact image attachments without losing their paths on submit, reload, or external editing. */
325
+ function wrapEditor(inner: EditorComponent, cwd: string, isEnabled: () => boolean, onCursor: () => void, onHoverEditor: (editor: EditorComponent, event: TuiMouseEvent) => void): EditorComponent {
326
+ const attachments = new Map<string, string>();
327
+ const expand = (text: string) => text.replace(/\[image\d+\]/g, label => attachments.get(label) ?? label);
328
+ const compact = (text: string) => {
329
+ if (!isEnabled()) return text;
330
+ const replacements = imagePathsInLine(text).map(match => {
331
+ let label = [...attachments].find(([, path]) => path === match.path)?.[0];
332
+ if (!label) { label = `[image${attachments.size + 1}]`; attachments.set(label, match.path); }
333
+ return { ...match, label };
334
+ });
335
+ for (const match of replacements.reverse()) text = text.slice(0, match.start) + match.label + text.slice(match.end);
336
+ return text;
337
+ };
338
+ // ponytail: reuse Pi 0.85's editor segmentation/submit hooks; replace with a public attachment API when available.
339
+ const core = inner as EditorComponent & { expandPasteMarkers?(text: string): string; segment?(text: string, mode?: string): Array<{ segment: string; index: number; input: string }>; imageAttachments?: Map<string, string> };
340
+ core.imageAttachments = attachments;
341
+ if (core.expandPasteMarkers) { const original = core.expandPasteMarkers.bind(core); core.expandPasteMarkers = text => expand(original(text)); }
342
+ const pasteEditor = inner as EditorComponent & { handlePaste?(text: string): void };
343
+ if (pasteEditor.handlePaste) { const paste = pasteEditor.handlePaste.bind(inner); pasteEditor.handlePaste = text => paste(compact(text)); }
344
+ if (core.segment) {
345
+ const original = core.segment.bind(core);
346
+ core.segment = (text, mode) => {
347
+ const spans = [...text.matchAll(/\[image\d+\]/g)].filter(match => attachments.has(match[0]));
348
+ return [...original(text, mode)].flatMap(segment => {
349
+ const span = spans.find(match => segment.index >= match.index && segment.index < match.index + match[0].length);
350
+ return !span ? [segment] : segment.index === span.index ? [{ segment: span[0], index: span.index, input: text }] : [];
351
+ });
352
+ };
353
+ }
354
+ let onChange: ((text: string) => void) | undefined;
355
+ return new Proxy(inner, {
356
+ get(target, property, receiver) {
357
+ if (property === "getText") return () => expand(target.getText());
358
+ if (property === "setText" || property === "insertTextAtCursor") return (text: string) => target[property]?.(compact(text));
359
+ if (property === "render") {
360
+ return (width: number) => {
361
+ const lines = target.render(width);
362
+ return isEnabled() ? linkImagePaths(lines, target, cwd, width) : lines;
363
+ };
364
+ }
365
+ if (property === "handleMouse") {
366
+ return (event: TuiMouseEvent) => {
367
+ const result = target.handleMouse?.(event);
368
+ if (event.type === "move") onHoverEditor(target, event);
369
+ else if (event.type === "click") onCursor();
370
+ return result;
371
+ };
372
+ }
373
+ if (property === "handleInput") {
374
+ return (data: string) => {
375
+ if (isEnabled() && matchesKey(data, "super+v")) { (target as CustomEditor).onPasteImage?.(); return; }
376
+ target.handleInput(data);
377
+ // Pi explicitly excludes '/' from provider triggerCharacters; request inline completions ourselves.
378
+ const native = target as CursorEditor & { tryTriggerAutocomplete?(): void };
379
+ const cursor = native.getCursor?.();
380
+ if (isEnabled() && cursor && data.length === 1 && /[\w/:-]/.test(data)
381
+ && SKILL_PREFIX.test((target.getText().split("\n")[cursor.line] ?? "").slice(0, cursor.col))) native.tryTriggerAutocomplete?.();
382
+ onCursor();
383
+ };
384
+ }
385
+ return Reflect.get(target, property, receiver);
386
+ },
387
+ set(target, property, value) {
388
+ if (property === "onChange") {
389
+ onChange = value as ((text: string) => void) | undefined;
390
+ return Reflect.set(target, property, (text: string) => {
391
+ onChange?.(expand(text));
392
+ onCursor();
393
+ });
394
+ }
395
+ return Reflect.set(target, property, value);
396
+ },
397
+ }) as EditorComponent;
398
+ }
399
+
400
+ // ponytail: Pi 0.85 editor layout mapping; unknown editors use visible-line matching.
401
+ function editorImagePaths(editor: EditorComponent, text: string): ImagePathMatch[] {
402
+ const attachments = (editor as EditorComponent & { imageAttachments?: Map<string, string> }).imageAttachments;
403
+ const paths = imagePathsInLine(text);
404
+ for (const match of text.matchAll(/\[image\d+\]/g)) {
405
+ const path = attachments?.get(match[0]);
406
+ if (path) paths.push({ path, start: match.index, end: match.index + match[0].length, startCol: visibleWidth(text.slice(0, match.index)), endCol: visibleWidth(text.slice(0, match.index + match[0].length)) });
407
+ }
408
+ return paths.sort((a, b) => a.start - b.start);
409
+ }
410
+
411
+ function editorPaths(editor: EditorComponent, row: number, width: number) {
412
+ const core = editor as EditorComponent & { lastWidth?: number; scrollOffset?: number; renderedVisibleLineCount?: number; getPaddingX?(): number; buildVisualLineMap?(width: number): Array<{ logicalLine: number; startCol: number; length: number }> };
413
+ if (!core.buildVisualLineMap || !core.lastWidth) return imagePathsInLine(editor.render(width)[row] ?? "");
414
+ if (row < 1 || row > (core.renderedVisibleLineCount ?? 0)) return [];
415
+ const chunk = core.buildVisualLineMap(core.lastWidth)[(core.scrollOffset ?? 0) + row - 1];
416
+ if (!chunk) return [];
417
+ const source = editor.getText().split("\n")[chunk.logicalLine] ?? "";
418
+ const padding = Math.min(core.getPaddingX?.() ?? 0, Math.max(0, Math.floor((width - 1) / 2)));
419
+ return editorImagePaths(editor, source).filter(match => match.end > chunk.startCol && match.start < chunk.startCol + chunk.length).map(match => ({
420
+ ...match,
421
+ startCol: padding + visibleWidth(source.slice(chunk.startCol, Math.max(chunk.startCol, match.start))),
422
+ endCol: padding + visibleWidth(source.slice(chunk.startCol, Math.min(chunk.startCol + chunk.length, match.end))),
423
+ }));
424
+ }
425
+
426
+ function linkImagePaths(lines: string[], editor: EditorComponent, cwd: string, width: number): string[] {
427
+ if (!inputCapabilities().hyperlinks) return lines;
428
+ return lines.map((line, row) => {
429
+ for (const match of editorPaths(editor, row, width).reverse()) line = linkRenderedPath(line, match.startCol, match.endCol, localPath(match.path, cwd));
430
+ // Isolate editor rows from inherited terminal link/color state.
431
+ const reset = "\x1b]8;;\x07\x1b[0m";
432
+ return reset + line + reset;
433
+ });
434
+ }
435
+
436
+ export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext, isEnabled: boolean | (() => boolean)): InputEnhancementsCleanup {
437
+ if (process.env.TERM_PROGRAM?.toLowerCase() === "otty") setCapabilities(inputCapabilities());
438
+ const enabled = typeof isEnabled === "function" ? isEnabled : () => isEnabled;
439
+ if (installed && installed.pi !== pi) installed.cleanup();
440
+ const state = installed?.pi === pi ? installed : (installed = createEnhancements(pi));
441
+ state.enabled = enabled;
442
+ state.ctx = ctx;
443
+ state.cwd = ctx.cwd;
444
+ state.theme = ctx.hasUI ? ctx.ui.theme : undefined;
445
+ if (ctx.mode === "tui" && ctx.hasUI) {
446
+ const generation = ctx.sessionManager;
447
+ if (state.generation !== generation) {
448
+ state.generation = generation;
449
+ state.unsubscribeInput?.();
450
+ state.unsubscribeInput = ctx.ui.onTerminalInput?.((data) => handleTerminalInput(state, data)) ?? undefined;
451
+ ctx.ui.addAutocompleteProvider((current) => createSkillAutocompleteProvider(current, () => readSkillCommands(pi), () => state.enabled()));
452
+ }
453
+ const active = ctx.ui.getEditorComponent();
454
+ if (active !== state.editorFactory || !state.editor) installEditor(ctx, state, active);
455
+ }
456
+ return state.cleanup;
457
+ }
458
+
459
+ function createEnhancements(pi: ExtensionAPI): Enhancements {
460
+ const state: Enhancements = {
461
+ pi,
462
+ enabled: () => true,
463
+ preview: {},
464
+ previewToken: 0,
465
+ overlayReady: false,
466
+ cleanup: (() => {}) as InputEnhancementsCleanup,
467
+ };
468
+ state.cleanup = Object.assign(
469
+ () => {
470
+ state.unsubscribeInput?.();
471
+ state.unsubscribeInput = undefined;
472
+ state.restoreViewportInput?.();
473
+ state.restoreViewportInput = undefined;
474
+ state.requestedPath = undefined;
475
+ state.previewToken++;
476
+ state.preview = {};
477
+ setPointer(state, false);
478
+ state.previewHandle?.hide();
479
+ state.previewHandle = undefined;
480
+ state.overlayReady = false;
481
+ state.generation = undefined;
482
+ const ui = liveUI(state.ctx);
483
+ if (ui && state.editorFactory && ui.getEditorComponent() === state.editorFactory) ui.setEditorComponent(state.baseFactory);
484
+ state.ctx = undefined;
485
+ state.cwd = undefined;
486
+ state.theme = undefined;
487
+ state.editor = undefined;
488
+ state.editorFactory = undefined;
489
+ },
490
+ {
491
+ refresh: () => {
492
+ if (!state.enabled()) {
493
+ void requestPreview(state, undefined);
494
+ setPointer(state, false);
495
+ if (state.editor) state.editor.setText(state.editor.getText());
496
+ }
497
+ state.tui?.invalidate(); state.tui?.requestRender();
498
+ },
499
+ },
500
+ );
501
+ pi.on("input", (event: InputEvent, eventCtx: ExtensionContext): Promise<InputEventResult | undefined> => handleInput(state, event, eventCtx));
502
+
503
+ return state;
504
+ }
505
+
506
+ async function handleInput(state: Enhancements, event: InputEvent, ctx: ExtensionContext): Promise<InputEventResult | undefined> {
507
+ if (!state.enabled() || event.source !== "interactive" || !event.text.includes("/skill:")) return undefined;
508
+ const skills = readSkillCommands(state.pi);
509
+ const text = await expandSkillTokens(
510
+ event.text,
511
+ skills,
512
+ (path) => readFile(path, "utf8"),
513
+ (skill) => ctx.ui.notify(`无法读取技能文件:${skill.path}`, "warning"),
514
+ );
515
+ return text === undefined ? undefined : { action: "transform", text };
516
+ }
517
+
518
+ /** Wrap the current editor factory (or the default editor) so enhancements ride on top of it. */
519
+ function installEditor(ctx: ExtensionContext, state: Enhancements, base?: EditorFactoryFunction): void {
520
+ const create: EditorFactoryFunction = base ?? ((tui, theme, keybindings) => new CustomEditor(tui, theme, keybindings, { embedWorkingStatus: true }));
521
+ const factory: EditorFactoryFunction = (tui, theme, keybindings) => {
522
+ state.tui = tui;
523
+ state.previewTui = tui;
524
+ // Otty is detected after fullscreen startup; synchronize its cached protocol for placement cleanup.
525
+ const renderer = tui as TUI & { imageProtocol?: string | null };
526
+ if (renderer.imageProtocol === null && getCapabilities().images === "kitty") renderer.imageProtocol = "kitty";
527
+ // ponytail: fullscreen's first input listener consumes mouse events before extension listeners.
528
+ // Observe its entry point until Pi exposes a pre-dispatch mouse subscription.
529
+ state.restoreViewportInput = hookViewportInput(tui, (data) => handleTerminalInput(state, data));
530
+ const inner: CursorEditor = create(tui, theme, keybindings);
531
+ const editor = wrapEditor(inner, state.cwd ?? process.cwd(), () => state.enabled(), () => {
532
+ const cursor = inner.getCursor?.();
533
+ const path = cursor ? editorImagePaths(inner, inner.getText().split("\n")[cursor.line] ?? "").find(match => cursor.col >= match.start && cursor.col <= match.end)?.path : undefined;
534
+ void requestPreview(state, state.enabled() ? path : undefined);
535
+ }, (target, event) => {
536
+ const match = state.enabled() ? editorPaths(target, event.y, event.width).find(path => event.x >= path.startCol && event.x < path.endCol) : undefined;
537
+ if (match) state.previewAnchor = { x: event.screenX, y: event.screenY };
538
+ setPointer(state, !!match);
539
+ void requestPreview(state, match?.path);
540
+ });
541
+ state.editor = editor;
542
+ return editor;
543
+ };
544
+ state.baseFactory = base;
545
+ state.editorFactory = factory;
546
+ ctx.ui.setEditorComponent(factory);
547
+ }
548
+
549
+ function setPointer(state: Enhancements, pointer: boolean): void {
550
+ if (state.pointer === pointer) return;
551
+ if (pointer || state.pointer) state.tui?.terminal.write(`\x1b]22;${pointer ? "pointer" : "default"}\x07`);
552
+ state.pointer = pointer;
553
+ }
554
+
555
+ function handleTerminalInput(state: Enhancements, data: string): { consume?: boolean } | undefined {
556
+ const mouse = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);
557
+ if (mouse) {
558
+ const x = Number(mouse[2]) - 1, y = Number(mouse[3]) - 1;
559
+ // ponytail: Pi 0.85 has no public screen hit-test API; inspect its last rendered OSC 8 cells.
560
+ const screen = (state.tui as TUI & { previousScreen?: string[] } | undefined)?.previousScreen;
561
+ const url = state.enabled() && (Number(mouse[1]) & 32) ? getOsc8LinkAtColumn(screen?.[y] ?? "", x) : undefined;
562
+ let path: string | undefined;
563
+ if (url?.startsWith("file:")) {
564
+ try { const file = fileURLToPath(url); if (IMAGE_MIME[extname(file).toLowerCase()]) path = file; } catch { /* Reject malformed or remote file URLs. */ }
565
+ }
566
+ if (path) state.previewAnchor = { x, y };
567
+ setPointer(state, !!path);
568
+ void requestPreview(state, path);
569
+ }
570
+ if (!state.preview.path || !matchesKey(data, "escape")) return undefined;
571
+ void requestPreview(state, undefined);
572
+ return { consume: true };
573
+ }
574
+
575
+ async function requestPreview(state: Enhancements, path: string | undefined): Promise<void> {
576
+ if (path && state.enabled() && path === state.requestedPath) { positionPreview(state); state.previewTui?.requestRender(); return; }
577
+ state.requestedPath = state.enabled() ? path : undefined;
578
+ const token = ++state.previewToken;
579
+ if (!path || !state.enabled()) {
580
+ setPreview(state, undefined);
581
+ return;
582
+ }
583
+ const preview = await readPreview(path, state.cwd ?? process.cwd());
584
+ if (token !== state.previewToken || !state.enabled()) return;
585
+ setPreview(state, preview);
586
+ }
587
+
588
+ function setPreview(state: Enhancements, preview: Preview | undefined): void {
589
+ const dimensions = preview?.kind === "image" ? getImageDimensions(preview.base64, preview.mimeType) : undefined;
590
+ const graphic = preview?.kind === "image" && dimensions ? renderImage(preview.base64, dimensions, {
591
+ maxWidthCells: Math.max(1, Math.min(58, (state.tui?.terminal.columns ?? 80) - 2)),
592
+ maxHeightCells: Math.max(1, Math.floor((state.tui?.terminal.rows ?? 24) / 2) - 2),
593
+ imageId: allocateImageId(), moveCursor: false,
594
+ }) ?? undefined : undefined;
595
+ state.preview = {
596
+ path: preview?.path, graphic,
597
+ note: preview?.kind === "note" ? preview.note : graphic ? undefined : "终端未能生成图片预览",
598
+ };
599
+ if (state.preview.path && !state.overlayReady) showOverlay(state);
600
+ positionPreview(state);
601
+ state.previewTui?.requestRender();
602
+ }
603
+
604
+ function showOverlay(state: Enhancements): void {
605
+ if (!state.tui || !state.theme) return;
606
+ state.overlayReady = true;
607
+ state.previewOptions = { width: 60, maxHeight: "50%", nonCapturing: true, visible: () => state.enabled() && state.preview.path !== undefined };
608
+ state.previewHandle = state.tui.showOverlay({
609
+ render: width => previewLines(state.preview, state.theme!, width, { row: Number(state.previewOptions?.row ?? 0), col: Number(state.previewOptions?.col ?? 0) }),
610
+ invalidate: () => {},
611
+ }, state.previewOptions);
612
+ }
613
+
614
+ function positionPreview(state: Enhancements): void {
615
+ if (!state.previewOptions || !state.tui || !state.theme) return;
616
+ const { rows, columns } = state.tui.terminal;
617
+ const width = Math.max(3, Math.min((state.preview.graphic?.columns ?? 26) + 2, columns || 80));
618
+ const height = Math.min(Math.floor(rows / 2), previewLines(state.preview, state.theme, width, { row: 0, col: 0 }).length);
619
+ const { x, y } = state.previewAnchor ?? { x: 0, y: rows - 2 };
620
+ Object.assign(state.previewOptions, { width, col: Math.max(0, Math.min(x, (columns || 80) - width)),
621
+ row: y + 1 + height <= rows ? y + 1 : Math.max(0, y - height) });
622
+ }