repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/clipboard/clipboard.ts
Rawimport { execFile } from "node:child_process";
import { promisify } from "node:util";
import { convertToPng, copyToClipboard } from "@earendil-works/pi-coding-agent";
import { getNativeClipboard } from "@earendil-works/pi-tui";
const run = promisify(execFile);
const MAX_TEXT_BYTES = 32 * 1024;
const MAX_IMAGE_BYTES = 4 * 1024 * 1024;
// Pixel budget (2^25 px, 8K frames) bounds decode memory; PNG allows at most 2^31-1 per axis.
const MAX_IMAGE_PIXELS = 2 ** 25;
const MAX_IMAGE_SIDE = 16 * 1024;
const READ_TIMEOUT_MS = 3000;
const COPY_TIMEOUT_MS = 10000;
const PNG_HEADER = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
const PNG_IHDR = Buffer.from("IHDR", "latin1");
const PNG_IEND = Buffer.from([
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
]);
export type ClipboardParams =
| { action: "copy"; text: string }
| { action: "read"; format?: "text" | "image" | "files" };
export type ClipboardValue =
| { action: "copy"; bytes: number }
| { action: "read"; format: "text"; text: string | null; bytes: number }
| {
action: "read";
format: "image";
image: { type: "image"; mimeType: "image/png"; data: string } | null;
bytes: number;
}
| { action: "read"; format: "files"; files: string[] | null; bytes: number };
class ClipboardError extends Error {}
/**
* Bound a backend call that offers no cancellation of its own.
* Losing timeout and abort paths must not surface as unhandled rejections.
*/
function withDeadline<T>(
work: Promise<T>,
timeoutMs: number,
signal: AbortSignal | undefined,
message: string,
): Promise<T> {
work.catch(() => {});
return new Promise<T>((resolve, reject) => {
const cleanup = () => {
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
};
const onAbort = () => {
cleanup();
reject(new Error("aborted"));
};
const timer = setTimeout(() => {
cleanup();
reject(new ClipboardError(message));
}, timeoutMs);
signal?.addEventListener("abort", onAbort, { once: true });
work.then(
(value) => {
cleanup();
resolve(value);
},
(error) => {
cleanup();
reject(error);
},
);
});
}
/** IHDR dimensions of a PNG; null when the header is not a well-formed IHDR chunk. */
function pngInfo(bytes: Buffer): { width: number; height: number } | null {
if (bytes.length < 24) return null;
if (bytes.readUInt32BE(8) !== 13 || !bytes.subarray(12, 16).equals(PNG_IHDR))
return null;
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
}
/** Reject malformed PNGs and decode bombs before they reach passthrough or the context. */
function assertPngBudget(bytes: Buffer, stage: "input" | "converted"): void {
const info = pngInfo(bytes);
if (!info || !bytes.subarray(bytes.length - 12).equals(PNG_IEND))
throw new ClipboardError(
`Clipboard ${stage === "input" ? "image is a malformed" : "conversion produced a malformed"} PNG; nothing was returned.`,
);
if (
info.width === 0 ||
info.height === 0 ||
info.width > MAX_IMAGE_SIDE ||
info.height > MAX_IMAGE_SIDE ||
info.width * info.height > MAX_IMAGE_PIXELS
)
throw new ClipboardError(
`Clipboard image exceeds the pixel limit (${MAX_IMAGE_PIXELS} px, ${MAX_IMAGE_SIDE} per side); nothing was returned.`,
);
}
async function wayland(
args: string[],
maxBuffer: number,
signal?: AbortSignal,
): Promise<Buffer | null> {
try {
const { stdout } = await run("wl-paste", args, {
encoding: "buffer",
timeout: 3000,
maxBuffer,
signal,
windowsHide: true,
});
return stdout;
} catch (error) {
const failure = error as NodeJS.ErrnoException & { stderr?: Buffer };
// wl-paste distinguishes an absent selection through this specific diagnostic.
if (
String(failure.code) === "1" &&
failure.stderr?.toString("utf8").trim() === "Nothing is copied"
)
return null;
if (failure.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
throw new ClipboardError(
"Clipboard data exceeds the read limit; nothing was returned.",
);
throw new ClipboardError(
"Wayland clipboard read failed. Install wl-clipboard (wl-paste) and check display access; no X11 fallback was attempted.",
);
}
}
/** Match Pi's Wayland preference without importing its private clipboard helpers. */
async function readWayland(
format: "text" | "image",
signal?: AbortSignal,
): Promise<Buffer | null> {
const list = await wayland(["--list-types"], 16 * 1024, signal);
if (list === null) return null;
const types = list
.toString("utf8")
.split(/\r?\n/)
.map((raw) => ({
raw: raw.trim(),
type: raw.split(";")[0]?.trim().toLowerCase(),
}));
const selected =
format === "text"
? (types.find(({ raw }) =>
/^text\/plain\s*;\s*charset\s*=\s*"?utf-8"?$/i.test(raw),
)?.raw ??
types.find(({ raw }) => raw.toLowerCase() === "text/plain")?.raw)
: [
"image/png",
"image/jpeg",
"image/webp",
"image/gif",
"image/bmp",
"image/tiff",
]
.map((preferred) => types.find(({ type }) => type === preferred)?.raw)
.find(Boolean);
if (!selected) {
if (format === "text" && types.some(({ type }) => type === "text/plain"))
throw new ClipboardError(
"Clipboard text uses an unsupported encoding; UTF-8 or plain text is required.",
);
return null;
}
return wayland(
["--no-newline", "--type", selected],
format === "text" ? MAX_TEXT_BYTES : MAX_IMAGE_BYTES,
signal,
);
}
export async function accessClipboard(
params: ClipboardParams,
signal?: AbortSignal,
): Promise<ClipboardValue> {
try {
signal?.throwIfAborted();
if (params.action === "copy") {
const bytes = Buffer.byteLength(params.text);
if (bytes > 64 * 1024)
throw new ClipboardError(
"Copy text exceeds 64 KiB; clipboard unchanged.",
);
// A completed copy cannot be rolled back if cancellation or a deadline arrives.
await withDeadline(
copyToClipboard(params.text),
COPY_TIMEOUT_MS,
signal,
"Clipboard copy timed out; the clipboard may or may not have changed.",
);
return { action: "copy", bytes };
}
const format = params.format ?? "text";
const isWayland =
process.platform === "linux" &&
Boolean(
process.env["WAYLAND_DISPLAY"] ||
process.env["XDG_SESSION_TYPE"] === "wayland",
);
const native = isWayland ? undefined : getNativeClipboard();
if (format === "files") {
if (!native?.getFilePaths)
throw new ClipboardError(
"File-reference reading is unavailable in this Pi clipboard backend (currently supported on macOS). No files were opened.",
);
const files = await withDeadline(
Promise.resolve(native.getFilePaths()),
READ_TIMEOUT_MS,
signal,
"Clipboard file-reference reading timed out; the native backend did not respond in time.",
);
if (files === undefined)
throw new ClipboardError(
"Clipboard file-reference reading is unavailable.",
);
signal?.throwIfAborted();
if (
files &&
(files.length > 128 || files.some((path) => path.length > 4096))
)
throw new ClipboardError(
"Clipboard file references exceed the read limit; nothing was returned.",
);
const bytes = Buffer.byteLength(JSON.stringify(files));
if (bytes > MAX_TEXT_BYTES)
throw new ClipboardError(
"Clipboard file references exceed 32 KiB; nothing was returned.",
);
return { action: "read", format, files, bytes };
}
if (!isWayland && !native)
throw new ClipboardError(
"Clipboard reading is unavailable. Check local display access and Pi's native clipboard support; OSC 52 copy does not provide clipboard reading.",
);
if (format === "text") {
const raw = isWayland ? await readWayland(format, signal) : undefined;
const text = isWayland
? raw === null
? null
: new TextDecoder("utf-8", { fatal: true }).decode(raw)
: await withDeadline(
Promise.resolve(native?.getText()),
READ_TIMEOUT_MS,
signal,
"Clipboard text reading timed out; the native backend did not respond in time.",
);
if (text === undefined)
throw new ClipboardError("Clipboard text reading is unavailable.");
signal?.throwIfAborted();
const bytes = text === null ? 0 : Buffer.byteLength(text);
if (
bytes > MAX_TEXT_BYTES ||
Buffer.byteLength(JSON.stringify(text)) > 48 * 1024
)
throw new ClipboardError(
"Clipboard text exceeds the read limit (32 KiB text / 48 KiB JSON); nothing was returned.",
);
return { action: "read", format, text, bytes };
}
const bytes = isWayland
? await readWayland(format, signal)
: await withDeadline(
Promise.resolve(native?.getImage()),
READ_TIMEOUT_MS,
signal,
"Clipboard image reading timed out; the native backend did not respond in time.",
);
if (bytes === undefined)
throw new ClipboardError("Clipboard image reading is unavailable.");
signal?.throwIfAborted();
if (!bytes?.length)
return { action: "read", format, image: null, bytes: 0 };
if (bytes.byteLength > MAX_IMAGE_BYTES)
throw new ClipboardError(
"Clipboard image exceeds 4 MiB; nothing was returned.",
);
const buffer = Buffer.from(
bytes.buffer,
bytes.byteOffset,
bytes.byteLength,
);
const isPng = buffer.subarray(0, 8).equals(PNG_HEADER);
// Passthrough must not launder malformed payloads or declared-dimension bombs.
if (isPng) assertPngBudget(buffer, "input");
const png = await convertToPng(
buffer.toString("base64"),
isPng ? "image/png" : "application/octet-stream",
);
signal?.throwIfAborted();
if (!png)
throw new ClipboardError(
"Pi could not convert this clipboard image to PNG.",
);
const size = Buffer.byteLength(png.data, "base64");
if (size > MAX_IMAGE_BYTES)
throw new ClipboardError(
"Converted clipboard image exceeds 4 MiB; nothing was returned.",
);
// Converted output also needs the budget: small compressed inputs can decode huge.
assertPngBudget(Buffer.from(png.data, "base64"), "converted");
return {
action: "read",
format,
image: { type: "image", mimeType: "image/png", data: png.data },
bytes: size,
};
} catch (error) {
if (signal?.aborted)
throw new Error(
"Clipboard operation cancelled; a copy already dispatched to Pi may still complete.",
);
if (error instanceof ClipboardError) throw error;
throw new Error(
params.action === "copy"
? "Pi could not copy text. Check clipboard access, platform utilities, and terminal OSC 52 support."
: "Pi could not read the clipboard. Check clipboard ownership and local display access.",
);
}
}