refactor(media): share base64 mime sniff helper

This commit is contained in:
Peter Steinberger
2026-02-15 04:17:38 +00:00
parent 482055832d
commit cb29346a1b
3 changed files with 23 additions and 41 deletions

View File

@@ -3,6 +3,7 @@ import { createEditTool, createReadTool, createWriteTool } from "@mariozechner/p
import type { AnyAgentTool } from "./pi-tools.types.js";
import type { SandboxFsBridge } from "./sandbox/fs-bridge.js";
import { detectMime } from "../media/mime.js";
import { sniffMimeFromBase64 } from "../media/sniff-mime-from-base64.js";
import { assertSandboxPath } from "./sandbox-paths.js";
import { sanitizeToolResultImages } from "./tool-images.js";
@@ -12,26 +13,6 @@ type ToolContentBlock = AgentToolResult<unknown>["content"][number];
type ImageContentBlock = Extract<ToolContentBlock, { type: "image" }>;
type TextContentBlock = Extract<ToolContentBlock, { type: "text" }>;
async function sniffMimeFromBase64(base64: string): Promise<string | undefined> {
const trimmed = base64.trim();
if (!trimmed) {
return undefined;
}
const take = Math.min(256, trimmed.length);
const sliceLen = take - (take % 4);
if (sliceLen < 8) {
return undefined;
}
try {
const head = Buffer.from(trimmed.slice(0, sliceLen), "base64");
return await detectMime({ buffer: head });
} catch {
return undefined;
}
}
function rewriteReadImageHeader(text: string, mimeType: string): string {
// pi-coding-agent uses: "Read image file [image/png]"
if (text.startsWith("Read image file [") && text.endsWith("]")) {

View File

@@ -1,5 +1,5 @@
import { estimateBase64DecodedBytes } from "../media/base64.js";
import { detectMime } from "../media/mime.js";
import { sniffMimeFromBase64 } from "../media/sniff-mime-from-base64.js";
export type ChatAttachment = {
type?: string;
@@ -31,26 +31,6 @@ function normalizeMime(mime?: string): string | undefined {
return cleaned || undefined;
}
async function sniffMimeFromBase64(base64: string): Promise<string | undefined> {
const trimmed = base64.trim();
if (!trimmed) {
return undefined;
}
const take = Math.min(256, trimmed.length);
const sliceLen = take - (take % 4);
if (sliceLen < 8) {
return undefined;
}
try {
const head = Buffer.from(trimmed.slice(0, sliceLen), "base64");
return await detectMime({ buffer: head });
} catch {
return undefined;
}
}
function isImageMime(mime?: string): boolean {
return typeof mime === "string" && mime.startsWith("image/");
}

View File

@@ -0,0 +1,21 @@
import { detectMime } from "./mime.js";
export async function sniffMimeFromBase64(base64: string): Promise<string | undefined> {
const trimmed = base64.trim();
if (!trimmed) {
return undefined;
}
const take = Math.min(256, trimmed.length);
const sliceLen = take - (take % 4);
if (sliceLen < 8) {
return undefined;
}
try {
const head = Buffer.from(trimmed.slice(0, sliceLen), "base64");
return await detectMime({ buffer: head });
} catch {
return undefined;
}
}