import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { randomUUID } from "node:crypto"; import { DEFAULT_LIMITS, type DocxLimits } from "./core/limits.ts"; function compact(payload: unknown): Record { if (!payload || typeof payload !== "object" || Array.isArray(payload)) return { type: typeof payload }; const source = payload as Record, result: Record = {}; for (const key of ["sourcePath", "sourceSha256", "revisionId", "stagedPath", "stagedSha256", "beforePath", "afterPath", "beforeSha256", "afterSha256", "destinationPath", "outputSha256", "ok", "equal", "dryRun", "engine"]) if (source[key] !== undefined) result[key] = source[key]; for (const [key, value] of Object.entries(source)) if (Array.isArray(value)) result[`${key}Count`] = value.length; return result; } export async function boundedJsonResult(payload: unknown, label: string, maxChars = DEFAULT_LIMITS.maxVisibleOutputChars): Promise<{ content: Array<{ type: "text"; text: string }>; details: Record }> { const json = JSON.stringify(payload, null, 2), lineCount = (json.match(/\n/g)?.length ?? 0) + 1; if (json.length <= maxChars && lineCount <= 2000) return { content: [{ type: "text", text: json }], details: payload as Record }; const dir = path.join(os.tmpdir(), "pi-docx-results", randomUUID()); await fs.mkdir(dir, { recursive: true, mode: 0o700 }); const artifactPath = path.join(dir, `${label.replace(/[^A-Za-z0-9._-]/g, "-")}.json`); await fs.writeFile(artifactPath, `${json}\n`, { encoding: "utf8", mode: 0o600 }); const summary = { ...compact(payload), truncated: true, artifactPath, fullOutputBytes: Buffer.byteLength(json), fullOutputLines: lineCount }; return { content: [{ type: "text", text: JSON.stringify(summary, null, 2) }], details: summary }; } export function renderImageResult(payload: Record & { pages: Array<{ pageNum: number; width: number; height: number; outputPath: string; bytes: number; png: Buffer }> }): { content: Array<{ type: "text"; text: string } | { type: "image"; mimeType: "image/png"; data: string }>; details: Record } { const detailsPages = payload.pages.map(({ png: _png, outputPath: _outputPath, ...page }) => page), { pages: _pages, pdfPath: _pdfPath, workspace: _workspace, ...publicDetails } = payload; return { content: [{ type: "text", text: [`Rendered DOCX: ${String(payload.sourcePath)}`, `Pages: ${detailsPages.map((page) => page.pageNum).join(", ")} of ${String(payload.pageCount ?? "unknown")}`, ...((payload.warnings as Array<{ message?: string }> | undefined) ?? []).map((warning) => `Warning: ${warning.message}`)].join("\n") }, ...payload.pages.map((page) => ({ type: "image" as const, mimeType: "image/png" as const, data: page.png.toString("base64") }))], details: { ...publicDetails, pages: detailsPages } }; } export function visibleLimitFrom(input: { limits?: Partial }): number { return input.limits?.maxVisibleOutputChars ?? DEFAULT_LIMITS.maxVisibleOutputChars; }