pi-image-tools 1.0.0

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,469 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
7
+ import {
8
+ calculateImageRows,
9
+ Container,
10
+ getImageDimensions,
11
+ Image,
12
+ Spacer,
13
+ Text,
14
+ type Component,
15
+ } from "@mariozechner/pi-tui";
16
+
17
+ export const IMAGE_PREVIEW_CUSTOM_TYPE = "pi-image-tools-preview";
18
+ const DEFAULT_MAX_WIDTH_CELLS = 60;
19
+ const MAX_IMAGES_PER_MESSAGE = 3;
20
+ const POWER_SHELL_TIMEOUT_MS = 120_000;
21
+ const POWER_SHELL_MAX_BUFFER_BYTES = 128 * 1024 * 1024;
22
+ const SIXEL_IMAGE_LINE_MARKER = "\x1b_Gm=0;\x1b\\";
23
+
24
+ export type ImagePayload = {
25
+ type: "image";
26
+ data: string;
27
+ mimeType: string;
28
+ };
29
+
30
+ type SixelAvailability = {
31
+ checked: boolean;
32
+ available: boolean;
33
+ version?: string;
34
+ reason?: string;
35
+ };
36
+
37
+ export type ImagePreviewItem = {
38
+ protocol: "sixel" | "native";
39
+ mimeType: string;
40
+ rows: number;
41
+ maxWidthCells: number;
42
+ sixelSequence?: string;
43
+ data?: string;
44
+ warning?: string;
45
+ };
46
+
47
+ export type ImagePreviewDetails = {
48
+ items: ImagePreviewItem[];
49
+ };
50
+
51
+ interface ThemeLike {
52
+ fg(color: string, text: string): string;
53
+ }
54
+
55
+ class SixelImageComponent implements Component {
56
+ constructor(
57
+ private readonly sequence: string,
58
+ private readonly rows: number,
59
+ ) {}
60
+
61
+ invalidate(): void {}
62
+
63
+ render(_width: number): string[] {
64
+ const safeRows = Math.max(1, Math.min(this.rows, 80));
65
+ const lines = Array.from({ length: Math.max(0, safeRows - 1) }, () => "");
66
+ const moveUp = safeRows > 1 ? `\x1b[${safeRows - 1}A` : "";
67
+ return [...lines, `${SIXEL_IMAGE_LINE_MARKER}${moveUp}${this.sequence}`];
68
+ }
69
+ }
70
+
71
+ function normalizeText(value: unknown): string {
72
+ return typeof value === "string" ? value.trim() : "";
73
+ }
74
+
75
+ function getErrorMessage(error: unknown): string {
76
+ if (error instanceof Error && error.message.trim()) {
77
+ return error.message;
78
+ }
79
+
80
+ return "Unknown error";
81
+ }
82
+
83
+ function toRecord(value: unknown): Record<string, unknown> {
84
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
85
+ return {};
86
+ }
87
+
88
+ return value as Record<string, unknown>;
89
+ }
90
+
91
+ function shouldAttemptSixelRendering(): boolean {
92
+ return process.platform === "win32";
93
+ }
94
+
95
+ function runPowerShellCommand(
96
+ script: string,
97
+ args: string[] = [],
98
+ ): { ok: boolean; stdout: string; stderr: string; reason?: string } {
99
+ if (process.platform !== "win32") {
100
+ return {
101
+ ok: false,
102
+ stdout: "",
103
+ stderr: "",
104
+ reason: "PowerShell-based Sixel rendering is only available on Windows.",
105
+ };
106
+ }
107
+
108
+ const result = spawnSync(
109
+ "powershell.exe",
110
+ [
111
+ "-NoProfile",
112
+ "-NonInteractive",
113
+ "-ExecutionPolicy",
114
+ "Bypass",
115
+ "-Command",
116
+ script,
117
+ ...args,
118
+ ],
119
+ {
120
+ encoding: "utf8",
121
+ timeout: POWER_SHELL_TIMEOUT_MS,
122
+ maxBuffer: POWER_SHELL_MAX_BUFFER_BYTES,
123
+ windowsHide: true,
124
+ },
125
+ );
126
+
127
+ if (result.error) {
128
+ return {
129
+ ok: false,
130
+ stdout: result.stdout ?? "",
131
+ stderr: result.stderr ?? "",
132
+ reason: getErrorMessage(result.error),
133
+ };
134
+ }
135
+
136
+ if (result.status !== 0) {
137
+ return {
138
+ ok: false,
139
+ stdout: result.stdout ?? "",
140
+ stderr: result.stderr ?? "",
141
+ reason: `PowerShell exited with code ${result.status}`,
142
+ };
143
+ }
144
+
145
+ return {
146
+ ok: true,
147
+ stdout: result.stdout ?? "",
148
+ stderr: result.stderr ?? "",
149
+ };
150
+ }
151
+
152
+ const sixelAvailabilityState: SixelAvailability = {
153
+ checked: false,
154
+ available: false,
155
+ };
156
+
157
+ function ensureSixelModuleAvailable(forceRefresh = false): SixelAvailability {
158
+ if (sixelAvailabilityState.checked && !forceRefresh) {
159
+ return sixelAvailabilityState;
160
+ }
161
+
162
+ const script = `
163
+ $ErrorActionPreference = 'Stop'
164
+ $ProgressPreference = 'SilentlyContinue'
165
+
166
+ $module = Get-Module -ListAvailable -Name Sixel | Sort-Object Version -Descending | Select-Object -First 1
167
+ if ($null -eq $module) {
168
+ try {
169
+ if (Get-Command Install-Module -ErrorAction SilentlyContinue) {
170
+ Install-Module -Name Sixel -Scope CurrentUser -Force -AllowClobber -Repository PSGallery -ErrorAction Stop | Out-Null
171
+ } elseif (Get-Command Install-PSResource -ErrorAction SilentlyContinue) {
172
+ Install-PSResource -Name Sixel -Scope CurrentUser -TrustRepository -Reinstall -Force -ErrorAction Stop | Out-Null
173
+ }
174
+ } catch {
175
+ }
176
+
177
+ $module = Get-Module -ListAvailable -Name Sixel | Sort-Object Version -Descending | Select-Object -First 1
178
+ }
179
+
180
+ if ($null -eq $module) {
181
+ Write-Error 'Sixel PowerShell module is unavailable.'
182
+ }
183
+
184
+ Write-Output ('Sixel/' + $module.Version.ToString())
185
+ `;
186
+
187
+ const result = runPowerShellCommand(script);
188
+ sixelAvailabilityState.checked = true;
189
+
190
+ if (!result.ok) {
191
+ const stderr = normalizeText(result.stderr);
192
+ const stdout = normalizeText(result.stdout);
193
+ sixelAvailabilityState.available = false;
194
+ sixelAvailabilityState.version = undefined;
195
+ sixelAvailabilityState.reason =
196
+ stderr || stdout || result.reason || "Failed to detect/install the Sixel PowerShell module.";
197
+ return sixelAvailabilityState;
198
+ }
199
+
200
+ const marker = normalizeText(result.stdout)
201
+ .split(/\r?\n/)
202
+ .find((line) => line.startsWith("Sixel/"));
203
+ sixelAvailabilityState.available = true;
204
+ sixelAvailabilityState.version = marker ? marker.slice("Sixel/".length) : undefined;
205
+ sixelAvailabilityState.reason = undefined;
206
+ return sixelAvailabilityState;
207
+ }
208
+
209
+ function extensionForImageMimeType(mimeType: string): string {
210
+ const normalized = mimeType.split(";")[0]?.trim().toLowerCase() ?? mimeType.toLowerCase();
211
+ switch (normalized) {
212
+ case "image/png":
213
+ return "png";
214
+ case "image/jpeg":
215
+ return "jpg";
216
+ case "image/webp":
217
+ return "webp";
218
+ case "image/gif":
219
+ return "gif";
220
+ case "image/bmp":
221
+ return "bmp";
222
+ case "image/tiff":
223
+ return "tiff";
224
+ default:
225
+ return "png";
226
+ }
227
+ }
228
+
229
+ function normalizeSixelSequence(value: string): string {
230
+ return value.replace(/\r?\n/g, "").replace(/\s+$/g, "");
231
+ }
232
+
233
+ function escapePowerShellSingleQuoted(value: string): string {
234
+ return value.replace(/'/g, "''");
235
+ }
236
+
237
+ function convertImageToSixelSequence(
238
+ image: ImagePayload,
239
+ ): { sequence?: string; error?: string } {
240
+ const tempBaseDir = mkdtempSync(join(tmpdir(), "pi-image-tools-image-"));
241
+ const imagePath = join(tempBaseDir, `preview.${extensionForImageMimeType(image.mimeType)}`);
242
+
243
+ try {
244
+ const bytes = Buffer.from(image.data, "base64");
245
+ if (bytes.length === 0) {
246
+ return { error: "Image conversion failed: clipboard payload was empty." };
247
+ }
248
+
249
+ writeFileSync(imagePath, bytes);
250
+
251
+ const escapedPath = escapePowerShellSingleQuoted(imagePath);
252
+
253
+ const script = `
254
+ $ErrorActionPreference = 'Stop'
255
+ $ProgressPreference = 'SilentlyContinue'
256
+
257
+ $path = '${escapedPath}'
258
+
259
+ Import-Module Sixel -ErrorAction Stop
260
+ if (-not (Test-Path -LiteralPath $path)) {
261
+ throw "Image path does not exist: $path"
262
+ }
263
+
264
+ $rendered = ConvertTo-Sixel -Path $path -Protocol Sixel -Force
265
+ if ([string]::IsNullOrWhiteSpace($rendered)) {
266
+ throw 'ConvertTo-Sixel returned empty output.'
267
+ }
268
+
269
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
270
+ Write-Output $rendered
271
+ `;
272
+
273
+ const result = runPowerShellCommand(script);
274
+ if (!result.ok) {
275
+ const detail = normalizeText(result.stderr) || normalizeText(result.stdout) || result.reason;
276
+ return {
277
+ error: detail
278
+ ? `Sixel conversion failed: ${detail}`
279
+ : "Sixel conversion failed for an unknown reason.",
280
+ };
281
+ }
282
+
283
+ const normalized = normalizeSixelSequence(result.stdout);
284
+ if (!normalized) {
285
+ return { error: "Sixel conversion produced empty output." };
286
+ }
287
+
288
+ return { sequence: normalized };
289
+ } catch (error) {
290
+ return { error: `Sixel conversion failed: ${getErrorMessage(error)}` };
291
+ } finally {
292
+ try {
293
+ rmSync(tempBaseDir, { recursive: true, force: true });
294
+ } catch {
295
+ }
296
+ }
297
+ }
298
+
299
+ function estimateImageRows(image: ImagePayload, maxWidthCells: number): number {
300
+ const dimensions = getImageDimensions(image.data, image.mimeType);
301
+ if (!dimensions) {
302
+ return 12;
303
+ }
304
+
305
+ return Math.max(1, Math.min(calculateImageRows(dimensions, maxWidthCells), 80));
306
+ }
307
+
308
+ function parseImagePreviewDetails(value: unknown): ImagePreviewDetails | null {
309
+ const record = toRecord(value);
310
+ const itemsRaw = record.items;
311
+ if (!Array.isArray(itemsRaw)) {
312
+ return null;
313
+ }
314
+
315
+ const items: ImagePreviewItem[] = [];
316
+ for (const raw of itemsRaw) {
317
+ const itemRecord = toRecord(raw);
318
+ const protocol = itemRecord.protocol === "sixel" ? "sixel" : "native";
319
+ const mimeType = typeof itemRecord.mimeType === "string" ? itemRecord.mimeType : "image/png";
320
+ const rows =
321
+ typeof itemRecord.rows === "number" && Number.isFinite(itemRecord.rows)
322
+ ? Math.max(1, Math.min(Math.trunc(itemRecord.rows), 80))
323
+ : 12;
324
+ const maxWidthCells =
325
+ typeof itemRecord.maxWidthCells === "number" && Number.isFinite(itemRecord.maxWidthCells)
326
+ ? Math.max(4, Math.min(Math.trunc(itemRecord.maxWidthCells), 240))
327
+ : DEFAULT_MAX_WIDTH_CELLS;
328
+ const sixelSequence =
329
+ typeof itemRecord.sixelSequence === "string" ? itemRecord.sixelSequence : undefined;
330
+ const data = typeof itemRecord.data === "string" ? itemRecord.data : undefined;
331
+ const warning = typeof itemRecord.warning === "string" ? itemRecord.warning : undefined;
332
+
333
+ if (protocol === "sixel" && !sixelSequence) {
334
+ continue;
335
+ }
336
+
337
+ if (protocol === "native" && !data) {
338
+ continue;
339
+ }
340
+
341
+ items.push({
342
+ protocol,
343
+ mimeType,
344
+ rows,
345
+ maxWidthCells,
346
+ sixelSequence,
347
+ data,
348
+ warning,
349
+ });
350
+ }
351
+
352
+ if (items.length === 0) {
353
+ return null;
354
+ }
355
+
356
+ return { items };
357
+ }
358
+
359
+ export function buildPreviewItems(images: readonly ImagePayload[]): ImagePreviewItem[] {
360
+ const selectedImages = images.slice(0, MAX_IMAGES_PER_MESSAGE);
361
+ if (selectedImages.length === 0) {
362
+ return [];
363
+ }
364
+
365
+ const attemptSixel = shouldAttemptSixelRendering();
366
+ const sixelState = attemptSixel ? ensureSixelModuleAvailable() : undefined;
367
+
368
+ return selectedImages.map((image) => {
369
+ const rows = estimateImageRows(image, DEFAULT_MAX_WIDTH_CELLS);
370
+
371
+ if (attemptSixel && sixelState?.available) {
372
+ const conversion = convertImageToSixelSequence(image);
373
+ if (conversion.sequence) {
374
+ return {
375
+ protocol: "sixel",
376
+ mimeType: image.mimeType,
377
+ rows,
378
+ maxWidthCells: DEFAULT_MAX_WIDTH_CELLS,
379
+ sixelSequence: conversion.sequence,
380
+ };
381
+ }
382
+
383
+ return {
384
+ protocol: "native",
385
+ mimeType: image.mimeType,
386
+ rows,
387
+ maxWidthCells: DEFAULT_MAX_WIDTH_CELLS,
388
+ data: image.data,
389
+ warning: conversion.error,
390
+ };
391
+ }
392
+
393
+ return {
394
+ protocol: "native",
395
+ mimeType: image.mimeType,
396
+ rows,
397
+ maxWidthCells: DEFAULT_MAX_WIDTH_CELLS,
398
+ data: image.data,
399
+ warning:
400
+ attemptSixel && sixelState && !sixelState.available
401
+ ? `Sixel preview unavailable: ${sixelState.reason || "missing PowerShell Sixel module."}`
402
+ : undefined,
403
+ };
404
+ });
405
+ }
406
+
407
+ export function registerImagePreviewDisplay(pi: ExtensionAPI): void {
408
+ let warnedSixelSetup = false;
409
+
410
+ pi.registerMessageRenderer<ImagePreviewDetails>(
411
+ IMAGE_PREVIEW_CUSTOM_TYPE,
412
+ (message, _options, theme) => {
413
+ const details = parseImagePreviewDetails(message.details);
414
+ if (!details) {
415
+ return undefined;
416
+ }
417
+
418
+ const uiTheme = theme as unknown as ThemeLike;
419
+ const container = new Container();
420
+ const imageCount = details.items.length;
421
+ const imageLabel = imageCount === 1 ? "image" : "images";
422
+
423
+ container.addChild(new Spacer(1));
424
+ container.addChild(new Text(uiTheme.fg("muted", `↳ pasted ${imageLabel} preview`), 0, 0));
425
+
426
+ for (const item of details.items) {
427
+ container.addChild(new Spacer(1));
428
+
429
+ if (item.protocol === "sixel" && item.sixelSequence) {
430
+ container.addChild(new SixelImageComponent(item.sixelSequence, item.rows));
431
+ } else if (item.data) {
432
+ container.addChild(
433
+ new Image(
434
+ item.data,
435
+ item.mimeType,
436
+ {
437
+ fallbackColor: (text: string) => uiTheme.fg("toolOutput", text),
438
+ },
439
+ {
440
+ maxWidthCells: item.maxWidthCells,
441
+ },
442
+ ),
443
+ );
444
+ }
445
+
446
+ if (item.warning) {
447
+ container.addChild(new Text(uiTheme.fg("warning", item.warning), 0, 0));
448
+ }
449
+ }
450
+
451
+ return container;
452
+ },
453
+ );
454
+
455
+ pi.on("session_start", async (_event, ctx) => {
456
+ if (!shouldAttemptSixelRendering()) {
457
+ return;
458
+ }
459
+
460
+ const availability = ensureSixelModuleAvailable();
461
+ if (!availability.available && !warnedSixelSetup && ctx.hasUI) {
462
+ warnedSixelSetup = true;
463
+ ctx.ui.notify(
464
+ `Image preview fallback active: ${availability.reason || "Sixel module unavailable."}`,
465
+ "warning",
466
+ );
467
+ }
468
+ });
469
+ }