@ikijs/mcp 0.8.0 → 0.8.1
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.
- package/dist/{chunk-JPWDKP43.mjs → chunk-LIWK4PQV.mjs} +14 -4
- package/dist/chunk-LIWK4PQV.mjs.map +1 -0
- package/dist/cli.js +13 -3
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +10 -5
- package/dist/index.d.ts +10 -5
- package/dist/index.js +13 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-JPWDKP43.mjs.map +0 -1
|
@@ -847,7 +847,7 @@ async function autoRigFromLayers(input) {
|
|
|
847
847
|
}
|
|
848
848
|
}
|
|
849
849
|
rowSpansByRole.push({ role, rowLeft, rowRight });
|
|
850
|
-
|
|
850
|
+
const layer = {
|
|
851
851
|
role,
|
|
852
852
|
fileName,
|
|
853
853
|
canvasW,
|
|
@@ -855,7 +855,17 @@ async function autoRigFromLayers(input) {
|
|
|
855
855
|
bbox,
|
|
856
856
|
cropW: bbox.w,
|
|
857
857
|
cropH: bbox.h
|
|
858
|
-
}
|
|
858
|
+
};
|
|
859
|
+
if (role === "face") {
|
|
860
|
+
const rowHalfWidths = [];
|
|
861
|
+
for (let y = bbox.y; y < bbox.y + bbox.h; y++) {
|
|
862
|
+
rowHalfWidths.push(
|
|
863
|
+
rowRight[y] >= rowLeft[y] ? headHalfOf({ left: rowLeft[y], right: rowRight[y] }) : 0
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
layer.rowHalfWidths = rowHalfWidths;
|
|
867
|
+
}
|
|
868
|
+
layerInputs.push(layer);
|
|
859
869
|
crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
|
|
860
870
|
}
|
|
861
871
|
const eyeRow = eyeRowOf(layerInputs);
|
|
@@ -1491,7 +1501,7 @@ async function composeLayersFromParts(input) {
|
|
|
1491
1501
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
1492
1502
|
import { z } from "zod";
|
|
1493
1503
|
function createIkiMcpServer() {
|
|
1494
|
-
const server = new McpServer({ name: "iki", version: "0.8.
|
|
1504
|
+
const server = new McpServer({ name: "iki", version: "0.8.1" });
|
|
1495
1505
|
server.registerTool(
|
|
1496
1506
|
"validate_iki",
|
|
1497
1507
|
{
|
|
@@ -1720,4 +1730,4 @@ export {
|
|
|
1720
1730
|
composeLayersFromParts,
|
|
1721
1731
|
createIkiMcpServer
|
|
1722
1732
|
};
|
|
1723
|
-
//# sourceMappingURL=chunk-
|
|
1733
|
+
//# sourceMappingURL=chunk-LIWK4PQV.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/measure-turn.ts","../src/node-images.ts","../src/limits.ts","../src/tools.ts","../src/measure.ts","../src/compose.ts","../src/server.ts"],"sourcesContent":["/**\n * Measure the head-turn cues in a PAIR of images of the same character — one\n * facing front, one turned — and report them as three ratios. It is how a\n * rigged turn gets compared to a reference turn without either image being\n * registered to the other: every number below is a front→turned CHANGE,\n * divided by something measured in the same image. That cancels crop and\n * position, not SCALE: the head span is sampled over a FIXED ±HEAD_BAND row\n * band, so a pair at different resolutions — or a character redrawn larger or\n * smaller between the two shots — would read as a turn that never happened.\n * The pair MUST already share framing and head size; this only checks it, it\n * does not correct for it. The check is a yaw does not change iris HEIGHT, so\n * a front/turned pair whose mean iris height differs is refused rather than\n * measured (see `measureTurnReference`).\n *\n * farEyeRatio how much the far eye narrows, over what it already was at\n * rest (a resting asymmetry in the art is divided out)\n * eyeShift how far the eye pair slides across the head, in units of\n * the FRONT head half-width (hh); negative = toward the\n * image's left\n * silhouetteRatio how much the head narrows, turned over front\n *\n * Read-only over two files; it edits nothing. Ported from the measurement\n * script this repo's turn work ran by hand, so the numbers a rig is tuned\n * against come out of the server every agent already has.\n *\n * `sharp` must stay confined to @ikijs/mcp; the decode and the debug-overlay\n * encode both go through ./node-images, this package's single image boundary.\n */\n\nimport path from \"node:path\";\nimport { decodePng, encodeOverlayPng } from \"./node-images\";\nimport {\n AutoRigInputError,\n resolveInputPath,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n/**\n * Hue/saturation window that selects the iris. Anime irises are a saturated\n * colour on a face that is not, which is what makes them findable at all; the\n * default window is violet-to-blue because that is what the characters this was\n * tuned on have. A character with, say, amber eyes passes its own window.\n */\nexport interface IrisColor {\n /** Inclusive hue bounds in degrees (0..360). */\n hueMin: number;\n hueMax: number;\n /** Minimum HSV saturation (0..1) — separates the iris from the skin. */\n satMin: number;\n}\n\nconst DEFAULT_IRIS: IrisColor = { hueMin: 230, hueMax: 300, satMin: 0.22 };\n\n// Value window, NOT a parameter: it excludes the specular highlight (near\n// white) and the pupil/lash ink (near black) whatever the iris hue is, so the\n// blob that survives is the coloured ring itself.\nconst IRIS_V_MIN = 0.18;\nconst IRIS_V_MAX = 0.95;\n// A blob whose surviving pixels average darker than this is lash ink or a\n// shadow that crept through the hue window, not an iris.\nconst IRIS_MEAN_V_MIN = 0.32;\n// The pupil and the specular highlight split the coloured ring into pieces; a\n// morphological CLOSE (dilate, then erode by the same radius) welds them back\n// into one component WITHOUT moving the blob's edges. A bare dilate would do\n// the welding too, but it adds its radius to every width, and that bias does\n// not cancel in far/near — it pushes the ratio toward 1 by an amount that\n// depends on how many pixels wide the iris happens to be.\nconst CLOSE_RADIUS = 3;\n// ...at the size it was tuned on; a smaller image gets a proportionally smaller\n// radius (at least 1 px), the way the area floor below is scaled.\nconst CLOSE_RADIUS_REFERENCE_PX = 1254;\n// An iris is small. Anything wider or taller than this fraction of the image is\n// hair, a collar, or the face itself leaking through the hue window.\nconst BLOB_MAX_FRAC = 0.12;\n// A KEYED head span this wide is not a head: the hue/sat/value backdrop rule\n// found no background at all, so the whole frame reads as foreground — a\n// backdrop that is not the lavender-grey it keys on (a plain screenshot, a\n// different key colour), not a character that fills the canvas edge to edge.\nconst KEYED_SPAN_MAX_FRAC = 0.95;\n// Area floor, scaled from the 300 px it was tuned at on a 1254² reference so\n// the same physical blob survives on a smaller render.\nconst MIN_AREA_REFERENCE_PIXELS = 1254 * 1254;\nconst MIN_AREA = 300;\n// Two irises sit apart but level. Below the dx floor is one iris found twice\n// (highlight vs ring), above the ceiling is an iris paired with a hair clip.\nconst PAIR_DX_MIN_FRAC = 0.08;\nconst PAIR_DX_MAX_FRAC = 0.35;\nconst PAIR_DY_MAX_FRAC = 0.05;\n/** Blobs kept as pair candidates, largest first — the pair search is O(n²). */\nconst MAX_CANDIDATES = 12;\n/** Half-height of the row band the head span is taken over, in px. Fixed at\n * ±10 rows rather than scaled to the image, and that is the convention: any\n * other measurement of head width meant to be compared with these — one taken\n * off layer alpha, a hand script — has to span the same band. Exported so the\n * auto-rig's own head measurement spans it too. */\nexport const HEAD_BAND = 10;\n\n// --- Foreground (silhouette) rule -----------------------------------------\n// Two modes, chosen per image, because the two kinds of image this compares\n// carry their background differently and neither rule works on both.\n//\n// \"alpha\" an ENGINE RENDER: transparent backdrop. Foreground is alpha alone\n// — and nothing else. Its character pixels include near-black hair\n// ink and pale lavender highlights, both of which the keyed rule\n// below would eat, and the head would come back narrower than it is.\n// It is also the rule to follow when measuring the same silhouette\n// from the layer PNGs' own alpha, so the two are comparable.\n// \"keyed\" a fully opaque REFERENCE: no alpha to read, so the flat\n// lavender-grey backdrop is keyed out by colour instead, along with\n// a near-black frame/letterbox border.\n/** Exported for the layer-alpha silhouette the auto-rig measures its head on,\n * which has to follow the \"alpha\" rule above to be comparable with a render. */\nexport const ALPHA_OPAQUE = 128;\nconst BG_HUE_MIN = 220;\nconst BG_HUE_MAX = 260;\nconst BG_SAT_MAX = 0.2;\nconst BG_V_MIN = 0.55;\nconst BG_V_BLACK = 0.03;\n\n/** Connected blob of iris-coloured pixels, in image px. */\nexport interface IrisBlob {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n w: number;\n h: number;\n area: number;\n cx: number;\n cy: number;\n}\n\n/** One image's measurement. `irisL`/`irisR` are ordered by x in the IMAGE. */\nexport interface TurnImageMeasure {\n file: string;\n width: number;\n height: number;\n maskMode: \"alpha\" | \"keyed\";\n irisL: IrisBlob;\n irisR: IrisBlob;\n /** Mean row of the two iris centres. */\n eyeRow: number;\n /** Head silhouette span at the eye row. */\n head: { left: number; right: number; cx: number; half: number };\n /** Mean column of the two iris centres. */\n pairCx: number;\n eyeGap: number;\n}\n\nexport interface TurnMeasurement {\n front: TurnImageMeasure;\n turned: TurnImageMeasure;\n /** Turned far/near iris width over the same ratio at rest. */\n farEyeRatio: number;\n /** Front→turned slide of the eye pair across the head, in FRONT hh units. */\n eyeShift: number;\n /** Head half-width, turned over front. */\n silhouetteRatio: number;\n /** -1 = the head turned toward the image's left, +1 = toward its right. */\n turnSign: -1 | 1;\n /** Debug overlays written, when `debugDir` was given. */\n debug?: string[];\n}\n\nexport type MeasureTurnResult =\n | ({ ok: true } & TurnMeasurement)\n | { ok: false; error: string };\n\nexport interface MeasureTurnInput {\n /** Front-facing image (relative paths resolve against cwd). */\n front: string;\n /** The same character turned. */\n turned: string;\n /** Iris colour window override, merged over the violet default. */\n iris?: Partial<IrisColor>;\n /** Existing directory to write `<name>.debug.png` overlays into. */\n debugDir?: string;\n}\n\n/** HSV of an 8-bit RGB triple: hue in degrees, saturation and value in 0..1. */\nfunction rgbToHsv(r: number, g: number, b: number): [number, number, number] {\n r /= 255;\n g /= 255;\n b /= 255;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const d = max - min;\n let h = 0;\n if (d > 0) {\n if (max === r) h = ((g - b) / d) % 6;\n else if (max === g) h = (b - r) / d + 2;\n else h = (r - g) / d + 4;\n h *= 60;\n if (h < 0) h += 360;\n }\n return [h, max === 0 ? 0 : d / max, max];\n}\n\n/** Grow `mask` by `r` px in every direction (square kernel). */\nfunction dilate(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n const out = new Uint8Array(width * height);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n if (!mask[y * width + x]) continue;\n for (let dy = -r; dy <= r; dy++) {\n for (let dx = -r; dx <= r; dx++) {\n const yy = y + dy;\n const xx = x + dx;\n if (yy >= 0 && yy < height && xx >= 0 && xx < width)\n out[yy * width + xx] = 1;\n }\n }\n }\n }\n return out;\n}\n\n/** Shrink `mask` by `r` px in every direction; outside the image counts as\n * background. Erosion only ever clears pixels, so set ones are all it visits. */\nfunction erode(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n const out = new Uint8Array(width * height);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n if (!mask[y * width + x]) continue;\n let keep = true;\n for (let dy = -r; dy <= r && keep; dy++) {\n for (let dx = -r; dx <= r; dx++) {\n const yy = y + dy;\n const xx = x + dx;\n if (\n yy < 0 ||\n yy >= height ||\n xx < 0 ||\n xx >= width ||\n !mask[yy * width + xx]\n ) {\n keep = false;\n break;\n }\n }\n }\n if (keep) out[y * width + x] = 1;\n }\n }\n return out;\n}\n\n/** Morphological close: weld pieces up to 2r apart, leaving the outer edges\n * where they were (a closed set never spills past the original's bbox). */\nfunction closeMask(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n return erode(dilate(mask, width, height, r), width, height, r);\n}\n\n/** 4-connected components of `mask` with at least `minArea` px, largest first. */\nfunction components(\n mask: Uint8Array,\n width: number,\n height: number,\n minArea: number,\n): IrisBlob[] {\n const seen = new Uint8Array(width * height);\n const out: IrisBlob[] = [];\n for (let i = 0; i < width * height; i++) {\n if (!mask[i] || seen[i]) continue;\n const stack = [i];\n seen[i] = 1;\n let x0 = width;\n let x1 = 0;\n let y0 = height;\n let y1 = 0;\n let n = 0;\n let sx = 0;\n let sy = 0;\n while (stack.length) {\n const p = stack.pop() as number;\n const x = p % width;\n const y = (p / width) | 0;\n n++;\n sx += x;\n sy += y;\n if (x < x0) x0 = x;\n if (x > x1) x1 = x;\n if (y < y0) y0 = y;\n if (y > y1) y1 = y;\n const neighbours: number[] = [];\n if (x > 0) neighbours.push(p - 1);\n if (x < width - 1) neighbours.push(p + 1);\n if (y > 0) neighbours.push(p - width);\n if (y < height - 1) neighbours.push(p + width);\n for (const q of neighbours) {\n if (seen[q] || !mask[q]) continue;\n seen[q] = 1;\n stack.push(q);\n }\n }\n if (n >= minArea) {\n out.push({\n x0,\n x1,\n y0,\n y1,\n w: x1 - x0 + 1,\n h: y1 - y0 + 1,\n area: n,\n cx: sx / n,\n cy: sy / n,\n });\n }\n }\n return out.sort((a, b) => b.area - a.area);\n}\n\n/**\n * Outermost set pixels of `mask` across the row band `rowLo..rowHi` (clamped\n * to the image) — the silhouette span at that height. An empty band returns\n * `left > right`; every caller here treats that as an error.\n *\n * Exported for the head measured off the layer PNGs' alpha union, which has to\n * span the head the same way this does or the two cannot be compared.\n */\nexport function foregroundSpan(\n mask: Uint8Array,\n width: number,\n height: number,\n rowLo: number,\n rowHi: number,\n): { left: number; right: number } {\n let left = width;\n let right = -1;\n for (let y = Math.max(0, rowLo); y <= Math.min(height - 1, rowHi); y++) {\n for (let x = 0; x < width; x++) {\n if (!mask[y * width + x]) continue;\n if (x < left) left = x;\n if (x > right) right = x;\n }\n }\n return { left, right };\n}\n\n/**\n * Half of a silhouette span, in px. The span is INCLUSIVE — `left` and `right`\n * are both foreground columns — so the head is `right - left + 1` px wide.\n * Shared with the auto-rig's own layer measurement: the two head half-widths\n * are compared against each other, so they cannot be halved differently.\n */\nexport function headHalfOf(span: { left: number; right: number }): number {\n return (span.right - span.left + 1) / 2;\n}\n\n/** Merge a caller's partial iris window over the default, rejecting nonsense. */\nfunction resolveIris(override: Partial<IrisColor> | undefined): IrisColor {\n const iris = { ...DEFAULT_IRIS, ...override };\n if (iris.hueMin < 0 || iris.hueMax > 360 || iris.hueMin >= iris.hueMax) {\n throw new AutoRigInputError(\n `iris hue window must be 0 <= hueMin < hueMax <= 360, got ${iris.hueMin}..${iris.hueMax}`,\n );\n }\n if (iris.satMin < 0 || iris.satMin > 1) {\n throw new AutoRigInputError(\n `iris satMin must be within 0..1, got ${iris.satMin}`,\n );\n }\n return iris;\n}\n\n/**\n * Find the iris pair and the head silhouette in one image.\n *\n * Throws a path-qualified AutoRigInputError when no pair survives the filters\n * (the candidate count says whether the hue window found nothing at all or\n * found too much) or when the eye-row band holds no foreground.\n */\nasync function measureTurnImage(\n filePath: string,\n iris: IrisColor,\n): Promise<TurnImageMeasure> {\n const { width, height, rgba, hasAlpha } = await decodePng(filePath);\n const n = width * height;\n\n // An RGBA file whose alpha is entirely opaque is a reference that merely\n // carries a channel, not a render with a cut-out backdrop — key it by colour.\n let transparent = false;\n if (hasAlpha) {\n for (let i = 0; i < n; i++) {\n if (rgba[i * 4 + 3] < ALPHA_OPAQUE) {\n transparent = true;\n break;\n }\n }\n }\n const maskMode: \"alpha\" | \"keyed\" =\n hasAlpha && transparent ? \"alpha\" : \"keyed\";\n\n const irisMask = new Uint8Array(n);\n const fg = new Uint8Array(n);\n const value = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n if (rgba[i * 4 + 3] < ALPHA_OPAQUE) continue; // transparent = background\n const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);\n if (maskMode === \"alpha\") {\n fg[i] = 1;\n } else {\n const isBg =\n (hue >= BG_HUE_MIN &&\n hue <= BG_HUE_MAX &&\n s < BG_SAT_MAX &&\n v > BG_V_MIN) ||\n v < BG_V_BLACK;\n if (!isBg) fg[i] = 1;\n }\n if (\n hue >= iris.hueMin &&\n hue <= iris.hueMax &&\n s > iris.satMin &&\n v > IRIS_V_MIN &&\n v < IRIS_V_MAX\n ) {\n irisMask[i] = 1;\n value[i] = v;\n }\n }\n\n const minArea = Math.max(\n 1,\n Math.round((MIN_AREA * n) / MIN_AREA_REFERENCE_PIXELS),\n );\n const closeRadius = Math.max(\n 1,\n Math.round(\n (CLOSE_RADIUS * Math.max(width, height)) / CLOSE_RADIUS_REFERENCE_PX,\n ),\n );\n const meanValue = (b: IrisBlob): number => {\n let count = 0;\n let total = 0;\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const i = y * width + x;\n if (!irisMask[i]) continue;\n count++;\n total += value[i];\n }\n }\n return count ? total / count : 0;\n };\n const candidates = components(\n closeMask(irisMask, width, height, closeRadius),\n width,\n height,\n minArea,\n )\n .filter((b) => b.w < width * BLOB_MAX_FRAC && b.h < height * BLOB_MAX_FRAC)\n .filter((b) => meanValue(b) > IRIS_MEAN_V_MIN)\n .slice(0, MAX_CANDIDATES);\n\n let best: { score: number; pair: [IrisBlob, IrisBlob] } | null = null;\n for (let i = 0; i < candidates.length; i++) {\n for (let j = i + 1; j < candidates.length; j++) {\n const a = candidates[i];\n const b = candidates[j];\n const dx = Math.abs(a.cx - b.cx);\n const dy = Math.abs(a.cy - b.cy);\n if (dx < width * PAIR_DX_MIN_FRAC || dx > width * PAIR_DX_MAX_FRAC)\n continue;\n if (dy > height * PAIR_DY_MAX_FRAC) continue;\n const score = a.area + b.area;\n if (best === null || score > best.score) {\n const pair: [IrisBlob, IrisBlob] = a.cx <= b.cx ? [a, b] : [b, a];\n best = { score, pair };\n }\n }\n }\n if (best === null) {\n throw new AutoRigInputError(\n `no iris pair found in ${filePath} among ${candidates.length} candidate blobs ` +\n `(iris hue ${iris.hueMin}..${iris.hueMax}, sat > ${iris.satMin})`,\n );\n }\n\n const [irisL, irisR] = best.pair;\n const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);\n const { left, right } = foregroundSpan(\n fg,\n width,\n height,\n eyeRow - HEAD_BAND,\n eyeRow + HEAD_BAND,\n );\n // Every ratio divides by this half-width, so a band that keyed down to\n // nothing (or to a single column) must fail rather than report Infinity.\n if (right <= left) {\n throw new AutoRigInputError(\n `no head span at the eye row (y=${eyeRow}) in ${filePath}: the ${maskMode} foreground mask is empty there`,\n );\n }\n if (maskMode === \"keyed\" && right - left + 1 > width * KEYED_SPAN_MAX_FRAC) {\n throw new AutoRigInputError(\n `head span at the eye row (y=${eyeRow}) in ${filePath} covers ${right - left + 1}/${width} px: background not keyed / not an engine render`,\n );\n }\n\n return {\n file: filePath,\n width,\n height,\n maskMode,\n irisL,\n irisR,\n eyeRow,\n head: {\n left,\n right,\n cx: (left + right) / 2,\n half: headHalfOf({ left, right }),\n },\n pairCx: (irisL.cx + irisR.cx) / 2,\n eyeGap: irisR.cx - irisL.cx,\n };\n}\n\n/**\n * Iris widths split into far and near. FAR = the eye on the side the pair moved\n * TOWARD, which is the one rotating away from the viewer; `turnSign` says which\n * side that is. The measurement and the report must split them the same way, so\n * they share this.\n */\nfunction farNearWidths(\n m: TurnImageMeasure,\n turnSign: -1 | 1,\n): { far: number; near: number } {\n return turnSign < 0\n ? { far: m.irisL.w, near: m.irisR.w }\n : { far: m.irisR.w, near: m.irisL.w };\n}\n\n/** The overlay: iris boxes, head edges, head centre, pair centre. */\nfunction overlaySvg(m: TurnImageMeasure): string {\n const box = (b: IrisBlob, stroke: string) =>\n `<rect x=\"${b.x0}\" y=\"${b.y0}\" width=\"${b.w}\" height=\"${b.h}\" fill=\"none\" stroke=\"${stroke}\" stroke-width=\"3\"/>`;\n const tick = (x: number, half: number, stroke: string) =>\n `<line x1=\"${x}\" y1=\"${m.eyeRow - half}\" x2=\"${x}\" y2=\"${m.eyeRow + half}\" stroke=\"${stroke}\" stroke-width=\"3\"/>`;\n return (\n `<svg width=\"${m.width}\" height=\"${m.height}\">` +\n box(m.irisL, \"#ff0000\") +\n box(m.irisR, \"#00c000\") +\n tick(m.head.left, 40, \"#0000ff\") +\n tick(m.head.right, 40, \"#0000ff\") +\n tick(m.head.cx, 60, \"#ff8800\") +\n tick(m.pairCx, 60, \"#ff00ff\") +\n \"</svg>\"\n );\n}\n\n/** `label` prefixes the file name: the two inputs often share a basename\n * (`renders/head.png` + `ref/head.png`), and one would overwrite the other. */\nasync function writeOverlay(\n debugDir: string,\n label: \"front\" | \"turned\",\n m: TurnImageMeasure,\n): Promise<string> {\n const outPath = path.join(\n debugDir,\n `${label}-${path.basename(m.file, \".png\")}.debug.png`,\n );\n writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));\n return outPath;\n}\n\n/** How far the front/turned mean iris heights may differ before the pair is\n * refused as not being at the same scale. A yaw foreshortens iris WIDTH, never\n * its height, so any difference here is framing/scale, not turn — 10% is\n * comfortably above the paint/detection noise a same-scale pair shows (the\n * fixtures in measure-turn.test.ts read within a percent) and comfortably\n * below a deliberate rescale. */\nconst IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;\n\n/**\n * Measure a front/turned image pair and report the three turn ratios plus both\n * raw per-image measurements.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching measureLayers; any other throw propagates.\n */\nexport async function measureTurnReference(\n input: MeasureTurnInput,\n): Promise<MeasureTurnResult> {\n try {\n const iris = resolveIris(input.iris);\n const frontPath = resolveInputPath(input.front);\n const turnedPath = resolveInputPath(input.turned);\n // Resolve the debug dir before measuring (fail-fast): a missing or escaping\n // target should not cost two full decodes first.\n const debugDir =\n input.debugDir === undefined ? null : resolveOutputDir(input.debugDir);\n\n const front = await measureTurnImage(frontPath, iris);\n const turned = await measureTurnImage(turnedPath, iris);\n\n // A yaw does not change iris HEIGHT — only width, via foreshortening — so\n // a front/turned pair whose mean iris height differs is not at the same\n // scale/framing, and every ratio below would be measuring that instead of\n // the turn. Refuse it rather than silently reporting a scale change as one.\n const frontIrisH = (front.irisL.h + front.irisR.h) / 2;\n const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;\n if (\n Math.abs(turnedIrisH - frontIrisH) / frontIrisH >\n IRIS_HEIGHT_SCALE_TOLERANCE\n ) {\n throw new AutoRigInputError(\n `front and turned images are not at the same scale: mean iris height ${frontIrisH.toFixed(1)}px front vs ${turnedIrisH.toFixed(1)}px turned, more than ${(IRIS_HEIGHT_SCALE_TOLERANCE * 100).toFixed(0)}% apart — a yaw does not change iris height, so the pair must share the same framing and head size`,\n );\n }\n\n // Where the eye pair sits on the head, per image; the CHANGE is the turn.\n const frontShift = front.pairCx - front.head.cx;\n const turnedShift = turned.pairCx - turned.head.cx;\n const shift = turnedShift - frontShift;\n // A pair that did not move has no far side, so there is no third value the\n // far/near rule below could use: treat a zero shift as a right turn, where\n // the ratio reads ~1 from either assignment anyway.\n const turnSign: -1 | 1 = shift < 0 ? -1 : 1;\n // Dividing the turned far/near by the same ratio at rest cancels a resting\n // asymmetry in the art, so what is left is the turn alone.\n const f = farNearWidths(front, turnSign);\n const t = farNearWidths(turned, turnSign);\n\n const debug =\n debugDir === null\n ? undefined\n : [\n await writeOverlay(debugDir, \"front\", front),\n await writeOverlay(debugDir, \"turned\", turned),\n ];\n\n return {\n ok: true,\n front,\n turned,\n farEyeRatio: t.far / t.near / (f.far / f.near),\n eyeShift: shift / front.head.half,\n silhouetteRatio: turned.head.half / front.head.half,\n turnSign,\n ...(debug === undefined ? {} : { debug }),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n\nconst n1 = (v: number) => v.toFixed(1);\nconst n3 = (v: number) => v.toFixed(3);\n\n/** One image's raw block: what the ratios above were computed from. */\nfunction imageBlock(label: string, m: TurnImageMeasure): string[] {\n return [\n `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,\n `iris widths ${m.irisL.w} / ${m.irisR.w} px centres ${n1(m.irisL.cx)} / ${n1(m.irisR.cx)} ` +\n `eye row ${m.eyeRow} gap ${n1(m.eyeGap)}`,\n `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} ` +\n `pair centre ${n1(m.pairCx)}`,\n ];\n}\n\n/** Render a measurement as plain text: the three ratios with the raw numbers\n * behind each, then one block per image. */\nexport function formatTurnReport(result: TurnMeasurement): string {\n const { front, turned } = result;\n const f = farNearWidths(front, result.turnSign);\n const t = farNearWidths(turned, result.turnSign);\n const lines = [\n `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned ` +\n `over ${f.far}/${f.near} front`,\n `eyeShift ${n3(result.eyeShift)} pair-vs-head centre ${n1(turned.pairCx - turned.head.cx)} px turned, ` +\n `${n1(front.pairCx - front.head.cx)} px front, over front head half ${n1(front.head.half)} px (hh)`,\n `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ` +\n `${n1(front.head.half)} px front`,\n `turnSign ${result.turnSign} (the head turned toward the image's ${\n result.turnSign < 0 ? \"left\" : \"right\"\n })`,\n \"\",\n ...imageBlock(\"front\", front),\n \"\",\n ...imageBlock(\"turned\", turned),\n ];\n if (result.debug !== undefined) {\n lines.push(\"\", ...result.debug.map((p) => `debug overlay ${p}`));\n }\n return lines.join(\"\\n\");\n}\n","/**\n * Node (sharp-backed) re-host of the browser-only pixel functions used by the\n * auto-rig import flow. Only the DECODE/ENCODE halves are re-hosted here — the\n * alpha-bbox scan itself is shared with the browser path via\n * @ikijs/editor, so the two cannot drift. Still a controlled duplicate of:\n * - crop ← examples/editor/src/auto-rig-image.ts\n * - atlas render + edge-extrude ← examples/editor/src/atlas-image.ts\n * The pure parts (packAtlas / uvRectFor / generateIkiFromLayerSet / role parsing\n * / bbox→model math) are reused from @ikijs/editor, not reimplemented here.\n *\n * `sharp` is a heavy native dependency and MUST stay confined to @ikijs/mcp — it\n * may never reach @ikijs/editor, @ikijs/engine, or @ikijs/format.\n */\n\nimport sharp from \"sharp\";\nimport type { AtlasLayout } from \"@ikijs/editor\";\nimport { detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { AutoRigInputError, MAX_INPUT_PIXELS } from \"./limits\";\n\nexport interface DecodedPng {\n width: number;\n height: number;\n /** Straight-alpha RGBA bytes, stride-4 (parity with canvas getImageData). */\n rgba: Buffer;\n /** Whether the FILE carried an alpha channel, before `.ensureAlpha()` added\n * one. A generated part without it is opaque on a white background and needs\n * that white keyed out before it can layer (see ./compose). */\n hasAlpha: boolean;\n}\n\n/**\n * Decode a PNG file to straight-alpha RGBA bytes + dimensions.\n *\n * Decode is an input boundary: a missing/corrupt/unsupported file or a\n * limitInputPixels overflow surfaces as a path-qualified AutoRigInputError so\n * the tool returns { ok:false } rather than { isError:true }.\n *\n * `.ensureAlpha()` promotes RGB PNGs to RGBA so the alpha scan matches the\n * browser canvas getImageData path (which is always RGBA).\n */\nexport async function decodePng(filePath: string): Promise<DecodedPng> {\n try {\n const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });\n const metadata = await pipeline.metadata();\n if (metadata.format !== \"png\") {\n throw new AutoRigInputError(\n `non-PNG image (${metadata.format ?? \"unknown\"}): ${filePath}`,\n );\n }\n const { data, info } = await pipeline\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return {\n width: info.width,\n height: info.height,\n rgba: data,\n hasAlpha: metadata.hasAlpha ?? false,\n };\n } catch (e) {\n if (e instanceof AutoRigInputError) throw e;\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);\n }\n}\n\n/**\n * Node-side wrapper over the shared scan in @ikijs/editor: same bbox rule\n * as the browser path by construction, with this package's error type for an\n * empty layer.\n */\nexport function detectAlphaBbox(\n rgba: Buffer,\n width: number,\n height: number,\n): { x: number; y: number; w: number; h: number } {\n const bbox = scanAlphaBbox(rgba, width, height);\n if (bbox === null) {\n throw new AutoRigInputError(\"layer is empty after alpha threshold\");\n }\n return bbox;\n}\n\n/**\n * Crop the already-decoded RGBA to bbox, returning a PNG buffer. One decode per\n * file: the crop is taken from the raw RGBA, not a re-read of the file. Parity\n * with cropBitmap in examples/editor/src/auto-rig-image.ts.\n */\nexport function cropToBuffer(\n rgba: Buffer,\n width: number,\n height: number,\n bbox: { x: number; y: number; w: number; h: number },\n): Promise<Buffer> {\n return sharp(rgba, { raw: { width, height, channels: 4 } })\n .extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h })\n .png()\n .toBuffer();\n}\n\n/**\n * Draw `svg` over the image at `filePath` and return the composited PNG bytes.\n * The debug half of ./measure-turn: the measurement is only believable once the\n * boxes are seen sitting on the irises. The caller has already decoded the file\n * through {@link decodePng}, so a failure here is an encode/environment fault,\n * not caller input, and propagates as itself.\n */\nexport function encodeOverlayPng(\n filePath: string,\n svg: string,\n): Promise<Buffer> {\n return sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS })\n .composite([{ input: Buffer.from(svg) }])\n .png()\n .toBuffer();\n}\n\nexport interface AtlasCrop {\n id: string;\n buffer: Buffer;\n width: number;\n height: number;\n}\n\n/**\n * Composite packed crops onto a transparent page and return a base64 PNG data\n * URI. Each crop's right + bottom edge pixels are extruded across the padding\n * gutter (replicating renderAtlas's right/bottom/corner drawImage extrudes in\n * examples/editor/src/atlas-image.ts) so LINEAR sampling at the inset UV never\n * reads a transparent neighbor texel. packAtlas reserves padding on the RIGHT\n * and BOTTOM only, so a one-sided `extend` matches its layout exactly.\n *\n * Crops are looked up BY placement.id (packAtlas sorts placements by id).\n * ASSUMES a non-empty layout (the empty case is handled by the caller).\n *\n * `quantizeColors` palette-quantizes the page PNG (libimagequant via sharp).\n * Flat-shaded character art keeps its look at 256 colours while the atlas\n * drops to roughly a quarter of its lossless size — the hero demo went from\n * 3.5MB to 0.9MB at a mean channel delta of 1.5/255 — which is what makes a\n * generated model shippable on a page. Omitted = lossless, as before.\n */\nexport async function renderAtlasToDataUri(\n crops: AtlasCrop[],\n layout: AtlasLayout,\n quantizeColors?: number,\n): Promise<string> {\n const byId = new Map<string, AtlasCrop>();\n for (const crop of crops) byId.set(crop.id, crop);\n\n const pad = layout.padding;\n\n const composites = await Promise.all(\n layout.placements.map(async (placement) => {\n const crop = byId.get(placement.id);\n if (crop === undefined) {\n throw new AutoRigInputError(\n `no crop for atlas placement \"${placement.id}\"`,\n );\n }\n // Replicate the right + bottom (+ corner) edge pixels into the gutter.\n const input =\n pad > 0\n ? await sharp(crop.buffer)\n .extend({ right: pad, bottom: pad, extendWith: \"copy\" })\n .png()\n .toBuffer()\n : crop.buffer;\n return { input, left: placement.x, top: placement.y };\n }),\n );\n\n const page = await sharp({\n create: {\n width: layout.pageWidth,\n height: layout.pageHeight,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite(composites)\n .png(\n quantizeColors === undefined\n ? {}\n : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 },\n )\n .toBuffer();\n\n return `data:image/png;base64,${page.toString(\"base64\")}`;\n}\n","/**\n * Resource guards + fail-fast path resolution and atomic writes for the Node\n * auto-rig tool.\n *\n * These constants bound an agent-supplied layer set so a malformed or oversized\n * request fails fast with a path-qualified message rather than exhausting memory\n * or producing a multi-MB MCP response. All guards REJECT (never downscale).\n *\n * `sharp` must stay confined to @ikijs/mcp — none of @ikijs/engine, @ikijs/editor,\n * or @ikijs/format may take a heavy Node image dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/** Max number of input layers in one request. */\nexport const MAX_LAYERS = 64;\n/** Max per-side dimension (px) of any single input PNG. */\nexport const MAX_LAYER_DIM = 4096;\n/** Max per-side dimension (px) of the derived canvas. */\nexport const MAX_CANVAS_DIM = 4096;\n/** Max area (px²) of the packed atlas page. */\nexport const MAX_ATLAS_AREA = 4096 * 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request, so a set of\n * many large PNGs cannot exhaust memory even though each passes MAX_LAYER_DIM. */\nexport const MAX_TOTAL_PIXELS = 64 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model. */\nexport const MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Reject an empty/whitespace or URL-looking caller-supplied path, shared by\n * {@link resolveInputPath} and {@link resolveInputDir}. `noun` and `kind`\n * shape the thrown message so each caller reports in its own vocabulary\n * (e.g. a directory input was never supposed to look like \"a file path\").\n */\nfunction rejectEmptyOrUrl(inputPath: string, noun: string, kind: string): void {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(`${noun} is empty`);\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `${noun} must be a ${kind}, not a URL: ${inputPath}`,\n );\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which reads its part PNGs\n * from wherever the image generator dropped them (a downloads folder, a scratch\n * dir) while everything it writes — the composed layers, the model — stays\n * under the working directory. Revisit only if this server ever runs with wider\n * privileges than the person driving it. The same reasoning covers\n * {@link resolveInputDir}, its directory counterpart.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string): string {\n rejectEmptyOrUrl(inputPath, \"layer path\", \"file path\");\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layer file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `layer path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/** Directory counterpart to {@link resolveInputPath} — see its doc comment. */\nexport function resolveInputDir(dirPath: string): string {\n rejectEmptyOrUrl(dirPath, \"layers dir\", \"directory path\");\n const resolved = path.resolve(process.cwd(), dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layers dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`layers path is not a directory: ${resolved}`);\n }\n return resolved;\n}\n\n/**\n * Confine an already-verified-to-exist directory to the MCP process working\n * directory, comparing REAL paths (statSync/writeFileSync follow symlinks, so\n * a lexical startsWith check can be bypassed by a symlinked dir under cwd).\n * Shared by {@link resolveOutputPath} and {@link resolveOutputDir} — both are\n * write-side boundaries where an unrestricted target is an\n * arbitrary-file-overwrite surface. `label` and `original` shape the thrown\n * message (path-qualified with the caller's original, unresolved string).\n */\nfunction confineToWorkingDirectory(\n root: string,\n dir: string,\n label: string,\n original: string,\n): string {\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `${label} escapes the working directory: ${original}`,\n );\n }\n return realDir;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `.iki` AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(outputPath: string): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(\".iki\")) {\n throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n const realDir = confineToWorkingDirectory(\n root,\n dir,\n \"output path\",\n outputPath,\n );\n return path.join(realDir, path.basename(resolved));\n}\n\n/**\n * Resolve a caller-supplied output DIRECTORY against the MCP process cwd.\n * Unlike {@link resolveOutputPath}, no filename is appended — the directory\n * itself must already exist (the tool never creates directories, fail-fast) —\n * and is confined via {@link confineToWorkingDirectory}. Returns the\n * realpath'd directory.\n */\nexport function resolveOutputDir(dirPath: string): string {\n if (typeof dirPath !== \"string\" || dirPath.trim() === \"\") {\n throw new AutoRigInputError(\"output dir is empty\");\n }\n const root = process.cwd();\n const resolved = path.resolve(root, dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`output dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output dir is not a directory: ${resolved}`);\n }\n return confineToWorkingDirectory(root, resolved, \"output dir\", dirPath);\n}\n\n/**\n * Write `data` to `outPath` atomically: write to a fresh temp file in the\n * same directory, then `renameSync` over the target. `rename` REPLACES the\n * destination directory entry rather than following it, so an existing\n * symlink at `outPath` cannot redirect the write outside the working tree.\n * Throws AutoRigInputError(\"write: …\") on failure.\n */\nexport function writeFileAtomic(\n outPath: string,\n data: string | Uint8Array,\n): void {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(tmp, data);\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n } catch (e) {\n throw new AutoRigInputError(\n `write: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n","import path from \"node:path\";\nimport {\n parseIkiModel,\n loadIkiModel,\n IkiFormatError,\n StandardParameter,\n type IkiModel,\n type IkiDeformer,\n} from \"@ikijs/format\";\nimport {\n EditorDocument,\n packAtlas,\n uvRectFor,\n generateIkiFromLayerSet,\n parseLayerRoles,\n TurnTargetError,\n type LayerInput,\n type AtlasAssignment,\n type TurnTargets,\n type TurnSolveReport,\n} from \"@ikijs/editor\";\nimport {\n decodePng,\n detectAlphaBbox,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n ALPHA_OPAQUE,\n HEAD_BAND,\n foregroundSpan,\n headHalfOf,\n} from \"./measure-turn\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_AREA,\n MAX_TOTAL_PIXELS,\n MAX_OUTPUT_BYTES,\n resolveInputPath,\n resolveOutputPath,\n writeFileAtomic,\n} from \"./limits\";\n\nexport type ValidateResult = { ok: true } | { ok: false; error: string };\n\nexport interface IkiSummary {\n name: string;\n canvas: { width: number; height: number };\n parameters: { id: string; min: number; max: number; default: number }[];\n parts: { id: string; order: number; deformer?: string }[];\n deformers: DeformerSummary[];\n}\n\nexport interface DeformerSummary {\n id: string;\n kind: \"matrix\" | \"warp\";\n parent?: string;\n warp?:\n | { mode: \"1d\"; parameters: string[] }\n | {\n mode: \"2d\";\n parameterX: string;\n parameterY: string;\n gridX: number;\n gridY: number;\n };\n}\n\nexport type DescribeResult =\n | { ok: true; summary: IkiSummary }\n | { ok: false; error: string };\n\nexport interface StandardParameterInfo {\n id: string;\n description: string;\n}\n\nfunction coerceModel(\n model: unknown,\n): { ok: true; model: IkiModel } | { ok: false; error: string } {\n try {\n const parsed =\n typeof model === \"string\" ? loadIkiModel(model) : parseIkiModel(model);\n return { ok: true, model: parsed };\n } catch (e) {\n if (e instanceof IkiFormatError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\nexport function validateIki(model: unknown): ValidateResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n return { ok: true };\n}\n\nexport function describeIki(model: unknown): DescribeResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n\n const m = result.model;\n\n const parameters = m.parameters.map((p) => ({\n id: p.id,\n min: p.min,\n max: p.max,\n default: p.default,\n }));\n\n const parts = m.parts.map((p) => {\n const entry: { id: string; order: number; deformer?: string } = {\n id: p.id,\n order: p.order,\n };\n if (p.deformer !== undefined) entry.deformer = p.deformer;\n return entry;\n });\n\n const deformers = (m.deformers ?? []).map(\n (d: IkiDeformer): DeformerSummary => {\n const kind = d.kind === \"warp\" ? \"warp\" : \"matrix\";\n const entry: DeformerSummary = { id: d.id, kind };\n if (d.parent !== undefined) entry.parent = d.parent;\n\n if (d.kind === \"warp\") {\n if (d.warp2d !== undefined) {\n entry.warp = {\n mode: \"2d\",\n parameterX: d.warp2d.parameter,\n parameterY: d.warp2d.parameterY,\n gridX: d.grid.cols,\n gridY: d.grid.rows,\n };\n } else if (d.warps !== undefined && d.warps.length > 0) {\n entry.warp = {\n mode: \"1d\",\n parameters: d.warps.map((w) => w.parameter),\n };\n }\n }\n\n return entry;\n },\n );\n\n const summary: IkiSummary = {\n name: m.name,\n canvas: { width: m.canvas.width, height: m.canvas.height },\n parameters,\n parts,\n deformers,\n };\n\n return { ok: true, summary };\n}\n\n// Static map of standard parameter ids to human-readable descriptions,\n// sourced from JSDoc comments in parameters.ts (including range hints).\nconst STANDARD_PARAMETER_INFO: StandardParameterInfo[] = [\n {\n id: StandardParameter.MouthOpen,\n description: \"Mouth open amount for lip-sync (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.MouthForm,\n description: \"Mouth form / smile (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeOpenLeft,\n description:\n \"Left eye open (0 closed .. 1 open). Drive with the right eye for a blink.\",\n },\n {\n id: StandardParameter.EyeOpenRight,\n description: \"Right eye open (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.EyeballX,\n description: \"Eyeball gaze, horizontal (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeballY,\n description: \"Eyeball gaze, vertical (-1 .. 1).\",\n },\n {\n id: StandardParameter.AngleX,\n description: \"Head angle, horizontal degrees.\",\n },\n {\n id: StandardParameter.AngleY,\n description: \"Head angle, vertical degrees.\",\n },\n {\n id: StandardParameter.AngleZ,\n description:\n \"Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D.\",\n },\n {\n id: StandardParameter.Breath,\n description: \"Idle breath (0 .. 1), cycled by the host.\",\n },\n {\n id: StandardParameter.BrowLeftY,\n description: \"Left brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightY,\n description: \"Right brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowLeftAngle,\n description: \"Left brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightAngle,\n description: \"Right brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.HairSwayX,\n description:\n \"Horizontal hair-sway driver. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.HairSwayZ,\n description:\n \"Hair-sway driver behind a head tilt. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n];\n\nexport function listStandardParameters(): StandardParameterInfo[] {\n return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));\n}\n\n// ── auto_rig_from_layers ──────────────────────────────────────────────────────\n\n/** One role-named PNG layer; role is derived from `fileName ?? basename(path)`. */\nexport interface AutoRigLayerInput {\n fileName?: string;\n path: string;\n}\n\nexport interface AutoRigInput {\n layers: AutoRigLayerInput[];\n /** Output `.iki` path (relative paths resolve against the process cwd). */\n outputPath?: string;\n /** Palette-quantize the atlas PNG to this many colours (integer, 2..256).\n * Omitted = lossless. See renderAtlasToDataUri for the size/quality trade. */\n quantizeColors?: number;\n /** Head-turn cues to fit the rig to, as `measure_turn_reference` reports\n * them. */\n turnTargets?: AutoRigTurnTargets;\n}\n\n/** The turn cues a caller may pass, which is every one but `headHalfWidth`:\n * the pixels the shift fractions are fractions of are measured off the layers\n * themselves, not accepted from the caller. */\nexport type AutoRigTurnTargets = Omit<TurnTargets, \"headHalfWidth\">;\n\nexport type AutoRigResult =\n | {\n ok: true;\n path: string;\n canvas: { width: number; height: number };\n partCount: number;\n atlasBytes: number;\n /** The head's half-width at the eye row, measured off the layers.\n * Absent when the opaque (alpha >= 128) union has no span there — a\n * layer set painted translucent below that threshold — in which case\n * the face plate stands in for it, same as a span that measures\n * narrower than the plate. */\n headHalfWidth?: number;\n /** Whether the measured value was handed to the generator; the\n * face-half fallback applies otherwise, which is what happens when it\n * is no wider than the face plate, or absent entirely. */\n headHalfWidthApplied: boolean;\n /** Every role with an opaque pixel in the same eye-row band as\n * `headHalfWidth`, per side, each with its own rest x there (canvas px)\n * — present only when `headHalfWidthApplied` is true, since the\n * fallback path has no measured edge to report at all. Passed to the\n * generator so it can land each candidate through its OWN motion\n * (hair_front's silhouette hold, a turn group's grid for the face and\n * its features, the body's own turn translate; `hair_back` holds the\n * outline and lands where it rests, and a role outside that table is\n * refused) and take the outermost LANDING, not just the outermost\n * REST pixel. */\n headEdges?: {\n left: { role: string; x: number }[];\n right: { role: string; x: number }[];\n };\n /** What the turn solve settled on — the cues the rig reaches and the\n * defaulted targets it had to cut down. Absent for a layer set with no\n * nose, which solves no turn at all. */\n turn?: TurnSolveReport;\n }\n | { ok: false; error: string };\n\nexport type { TurnSolveReport };\n\n/**\n * Run a fallible input/environment-boundary call, re-tagging any throw as an\n * AutoRigInputError with context so the tool reports it as `{ ok:false }` rather\n * than an unexpected `isError`. Use ONLY around true caller-input / filesystem\n * boundaries — never around internal pipeline math (a throw there is a bug).\n */\nfunction expectInput<T>(label: string, fn: () => T): T {\n try {\n return fn();\n } catch (e) {\n throw new AutoRigInputError(\n `${label}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * The row the head's width is measured at: the mean of the iris centres, or of\n * the eye centres when the layer set has no irises. `measure_turn_reference`\n * picks the same row off a render — it finds the irises themselves — so the\n * head it spans there is the head spanned here.\n */\nfunction eyeRowOf(layers: LayerInput[]): number {\n const centreY = (role: string): number | undefined => {\n const layer = layers.find((l) => l.role === role);\n return layer && layer.bbox.y + layer.bbox.h / 2;\n };\n const pairRow = (left: string, right: string): number | undefined => {\n const a = centreY(left);\n const b = centreY(right);\n return a === undefined || b === undefined ? undefined : (a + b) / 2;\n };\n const row = pairRow(\"iris_L\", \"iris_R\") ?? pairRow(\"eye_L\", \"eye_R\");\n if (row === undefined) {\n // eye_L/eye_R are required roles, so parseLayerRoles refused this set long\n // before here — a miss is an invariant break, not caller input.\n throw new Error(\"auto-rig: no eye pair to measure the head width at\");\n }\n return Math.round(row);\n}\n\n/**\n * `foregroundSpan`, but over one layer's own already-reduced per-row\n * left/right (see `rowSpansByRole` in `autoRigFromLayers`) instead of a\n * pixel mask — the same row-band reduction, without re-scanning pixels.\n */\nfunction foregroundSpanOfRows(\n rowLeft: Int32Array,\n rowRight: Int32Array,\n rowLo: number,\n rowHi: number,\n): { left: number; right: number } {\n let left = Infinity;\n let right = -Infinity;\n for (\n let y = Math.max(0, rowLo);\n y <= Math.min(rowLeft.length - 1, rowHi);\n y++\n ) {\n if (rowLeft[y] < left) left = rowLeft[y];\n if (rowRight[y] > right) right = rowRight[y];\n }\n return { left, right };\n}\n\n/** The face plate's half-width, derived the way generateIkiFromLayerSet derives\n * it — off the `face` layer's cropped width — so the two agree on which head\n * is the wider one. */\nfunction facePlateHalfOf(layers: LayerInput[]): number {\n const face = layers.find((l) => l.role === \"face\");\n if (face === undefined) {\n // `face` is a required role; parseLayerRoles refused this set long before.\n throw new Error(\"auto-rig: no face layer to measure the plate against\");\n }\n return face.cropW / 2;\n}\n\n/**\n * Decode role-named PNG file paths, auto-rig a model from them, atlas + embed\n * the textures (Node sharp), validate, and write the renderable `.iki` to disk.\n * Returns the output path + summary stats (the multi-MB model is never inlined).\n *\n * The head turn is fitted to `input.turnTargets`, on the head half-width this\n * measures off the layers themselves; what the solve settled on comes back in\n * `turn`. The face layer alone also gets its per-row painted half-widths\n * (`LayerInput.rowHalfWidths`), which bend the face plate on a row-dependent\n * radius: the generator reads no other role's, so measuring any other layer's\n * would only hand it bytes it discards.\n *\n * Re-host of examples/editor/src/store.ts `importLayerSet` with the three DOM\n * pixel functions swapped for the sharp-backed ./node-images helpers; the pure\n * model math is reused from @ikijs/editor.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) → `{ ok:false }`;\n * any other throw (invariant break, programmer bug) propagates to `isError`.\n */\nexport async function autoRigFromLayers(\n input: AutoRigInput,\n): Promise<AutoRigResult> {\n try {\n const layers = input.layers;\n if (!Array.isArray(layers) || layers.length === 0) {\n throw new AutoRigInputError(\"layers must be a non-empty array\");\n }\n if (layers.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers: ${layers.length} > ${MAX_LAYERS}`,\n );\n }\n\n // Resolve the output path FIRST (fail-fast): reject a bad/escaping/non-.iki\n // target before spending the image-decode budget on a request that can't\n // be written anyway.\n const outPath = resolveOutputPath(\n input.outputPath ?? \"auto-rigged-model.iki\",\n );\n const quantizeColors = input.quantizeColors;\n if (\n quantizeColors !== undefined &&\n (!Number.isInteger(quantizeColors) ||\n quantizeColors < 2 ||\n quantizeColors > 256)\n ) {\n throw new AutoRigInputError(\n `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`,\n );\n }\n\n // Resolve paths + role-map up front (input boundary; no decode needed).\n // parseLayerRoles throws on unknown/duplicate/missing-required roles.\n const resolvedLayers = layers.map((layer) => {\n const resolved = resolveInputPath(layer.path);\n return { resolved, fileName: layer.fileName ?? path.basename(resolved) };\n });\n const rolePairs = expectInput(\"role parsing\", () =>\n parseLayerRoles(resolvedLayers.map((r) => r.fileName)),\n );\n const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));\n\n // Decode + alpha-bbox + crop SEQUENTIALLY: only ONE full-canvas RGBA buffer\n // is live at a time (a Promise.all over all layers would hold every decoded\n // buffer at once, allowing a multi-GB spike on inputs that each pass\n // MAX_LAYER_DIM). MAX_TOTAL_PIXELS bounds the aggregate work. Canvas size =\n // the first layer's full PNG dims (parity with buildLayerInputs in\n // examples/editor/src/auto-rig-image.ts); all layers must match it.\n let canvasW = 0;\n let canvasH = 0;\n let totalPixels = 0;\n // Union of EVERY layer's opaque pixels — the silhouette the head half-width\n // is measured off below. Every layer folds in, so a body or an accessory\n // crossing the eye band widens the span; that is deliberate, because a rest\n // render of the finished rig shows the same union and measures the same.\n // Sized once the first layer gives the canvas.\n let opaque = new Uint8Array(0);\n const layerInputs: LayerInput[] = [];\n const crops: AtlasCrop[] = [];\n // Per layer, per row: its OWN leftmost/rightmost opaque column (canvasW /\n // -1 where it has none that row) — recorded in the SAME pass as the union\n // fold, while the layer's decoded pixels are still live, rather than a\n // second decode pass. Reduced to a single left/right owner per side once\n // the eye row is known, below: which layer's own deformation actually\n // carries the union's outermost pixel through the turn.\n const rowSpansByRole: {\n role: string;\n rowLeft: Int32Array;\n rowRight: Int32Array;\n }[] = [];\n for (let i = 0; i < resolvedLayers.length; i++) {\n const { resolved, fileName } = resolvedLayers[i];\n const png = await decodePng(resolved);\n if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {\n throw new AutoRigInputError(\n `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`,\n );\n }\n totalPixels += png.width * png.height;\n if (totalPixels > MAX_TOTAL_PIXELS) {\n throw new AutoRigInputError(\n `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`,\n );\n }\n if (i === 0) {\n canvasW = png.width;\n canvasH = png.height;\n if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {\n throw new AutoRigInputError(\n `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`,\n );\n }\n opaque = new Uint8Array(canvasW * canvasH);\n } else if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `layer \"${fileName}\" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n\n const role = roleByFileName.get(fileName);\n if (role === undefined) {\n throw new AutoRigInputError(`no role resolved for \"${fileName}\"`);\n }\n let bbox: { x: number; y: number; w: number; h: number };\n try {\n bbox = detectAlphaBbox(png.rgba, png.width, png.height);\n } catch (e) {\n // Enrich the empty-layer error with role + file context.\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": ${msg}`,\n );\n }\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\n // Fold this layer into the silhouette AND record its own per-row extent\n // while its pixels are still here — one pass over the same pixels.\n const rowLeft = new Int32Array(canvasH).fill(canvasW);\n const rowRight = new Int32Array(canvasH).fill(-1);\n for (let y = 0; y < canvasH; y++) {\n for (let x = 0; x < canvasW; x++) {\n const p = y * canvasW + x;\n if (png.rgba[p * 4 + 3] < ALPHA_OPAQUE) continue;\n opaque[p] = 1;\n if (x < rowLeft[y]) rowLeft[y] = x;\n if (x > rowRight[y]) rowRight[y] = x;\n }\n }\n rowSpansByRole.push({ role, rowLeft, rowRight });\n // png.rgba (full-canvas) is dropped at the next iteration — GC reclaims it\n // before the next decode, so peak memory stays ~one canvas + the crops.\n const layer: LayerInput = {\n role,\n fileName,\n canvasW,\n canvasH,\n bbox,\n cropW: bbox.w,\n cropH: bbox.h,\n };\n if (role === \"face\") {\n // The plate's painted half-width on each of its crop rows — the same\n // alpha rule and halving as the head's own span, row by row (0 for a\n // row with no opaque pixel; a single opaque pixel IS a half-px row\n // here, where the head-span reads below treat a one-column band as\n // no span) — so the face plate can turn on a radius that tapers with\n // the jaw. The bbox admits alpha down to 8 while the span counts\n // alpha >= 128 only, so a row's span sits inside the crop and its\n // half never exceeds cropW / 2, the generator's bound.\n const rowHalfWidths: number[] = [];\n for (let y = bbox.y; y < bbox.y + bbox.h; y++) {\n rowHalfWidths.push(\n rowRight[y] >= rowLeft[y]\n ? headHalfOf({ left: rowLeft[y], right: rowRight[y] })\n : 0,\n );\n }\n layer.rowHalfWidths = rowHalfWidths;\n }\n layerInputs.push(layer);\n crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n\n // The head's own half-width at the eye row, in canvas px, taken off the\n // layers' opaque union the way measure_turn_reference takes it off a render\n // (alpha rule, same row band, same halving) — so a rest render of this rig\n // measures the same span back. It is what the turn's shift targets are\n // fractions of; the generator's own fallback is the face plate, which is\n // narrower than the head the hair draws, and every shift then lands short.\n const eyeRow = eyeRowOf(layerInputs);\n const span = foregroundSpan(\n opaque,\n canvasW,\n canvasH,\n eyeRow - HEAD_BAND,\n eyeRow + HEAD_BAND,\n );\n // A layer set painted below the ALPHA_OPAQUE threshold (translucent art —\n // still above detectAlphaBbox's own, much lower, floor) has no confident\n // span here. That is not the same as having no head: fall back to the face\n // plate, same as a span that measures narrower than it below, rather than\n // refuse the whole rig over a union that is merely non-opaque.\n const headHalfWidth = span.right > span.left ? headHalfOf(span) : undefined;\n // ...but only when it IS wider than the plate. A hairless set, one whose\n // face plate is what the eye row is widest at, or one with no confident\n // span at all, measures a head the generator refuses (the silhouette\n // hold's zone would sit inside the plate) — and the right answer there is\n // the plate it falls back to, not no rig at all.\n const headHalfWidthApplied =\n headHalfWidth !== undefined &&\n headHalfWidth > facePlateHalfOf(layerInputs);\n\n // Every layer's own opaque extent in the same band — a companion to\n // headHalfWidth, only meaningful once it is actually applied (the\n // fallback path has no measured edge to report at all). The generator\n // lands each candidate through its OWN deformation and takes the\n // outermost LANDING, not just the outermost REST pixel, since which part\n // ends up furthest out after the turn can differ from which one drew\n // furthest out at rest. Model x (canvas x minus half the canvas width),\n // matching bboxToTransform's own convention.\n let headEdges:\n | {\n left: { role: string; x: number }[];\n right: { role: string; x: number }[];\n }\n | undefined;\n if (headHalfWidthApplied) {\n const bandLo = eyeRow - HEAD_BAND;\n const bandHi = eyeRow + HEAD_BAND;\n const left: { role: string; x: number }[] = [];\n const right: { role: string; x: number }[] = [];\n for (const { role, rowLeft, rowRight } of rowSpansByRole) {\n const own = foregroundSpanOfRows(rowLeft, rowRight, bandLo, bandHi);\n if (own.right <= own.left) continue; // no opaque pixel here at all\n left.push({ role, x: own.left - canvasW / 2 });\n right.push({ role, x: own.right - canvasW / 2 });\n }\n headEdges = { left, right };\n }\n\n // Internal pipeline — direct calls. By here roles + bboxes are validated, so\n // a throw is an invariant break / bug and must propagate to `isError` —\n // except from the turn solve, the one part of the generator that reads\n // CALLER input. It marks those with TurnTargetError (a field that is not a\n // number, a target this layer set cannot reach), which is a fact about the\n // request, not a bug.\n let turn: TurnSolveReport | undefined;\n let model: IkiModel;\n try {\n // Destructured, not spread: a JS caller (unchecked by AutoRigTurnTargets'\n // own `Omit<TurnTargets, \"headHalfWidth\">`) could otherwise smuggle its\n // OWN headHalfWidth through untouched whenever headHalfWidthApplied is\n // false — headHalfWidth is measured off the layers, never accepted from\n // the caller, so only these five fields cross the boundary.\n const { eyeShift, farEyeRatio, silhouetteRatio, noseShift, mouthShift } =\n input.turnTargets ?? {};\n model = generateIkiFromLayerSet(\n layerInputs,\n { width: canvasW, height: canvasH },\n {\n turnTargets: {\n eyeShift,\n farEyeRatio,\n silhouetteRatio,\n noseShift,\n mouthShift,\n ...(headHalfWidthApplied ? { headHalfWidth } : {}),\n },\n onTurnSolved: (report) => {\n turn = report;\n },\n ...(headEdges === undefined ? {} : { headEdges }),\n },\n );\n } catch (e) {\n if (!(e instanceof TurnTargetError)) throw e;\n throw new AutoRigInputError(e.message);\n }\n const doc = new EditorDocument(model);\n\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n );\n if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`,\n );\n }\n\n const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);\n if (dataUri.length > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n const partTextureAssignments: AtlasAssignment[] = crops.map((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n return {\n partId: crop.id,\n uv: uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n }),\n };\n });\n\n doc.applyAtlas({ textures: [{ source: dataUri }], partTextureAssignments });\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(doc.getModel());\n\n // Write to a fresh temp file in the verified directory, then atomically\n // rename over the target — see writeFileAtomic for why an existing `.iki`\n // symlink at outPath cannot redirect the write outside the working tree.\n writeFileAtomic(outPath, JSON.stringify(finalModel));\n\n return {\n ok: true,\n path: outPath,\n canvas: { width: canvasW, height: canvasH },\n partCount: finalModel.parts.length,\n atlasBytes: dataUri.length,\n ...(headHalfWidth === undefined ? {} : { headHalfWidth }),\n headHalfWidthApplied,\n ...(headEdges === undefined ? {} : { headEdges }),\n ...(turn === undefined ? {} : { turn }),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * Measure composed Iki role layers and flag the failure modes that have\n * actually shipped broken characters. Read-only: it never edits anything.\n *\n * Ports the geometry checks that shipped as a script in the Claude Code plugin,\n * so a plugin user gets them from the MCP server instead of an ad-hoc `sharp`\n * install. They exist because \"the eyes look too big\" is not actionable but\n * \"the iris is 33% of the sclera width, target 0.45-0.72\" is. Every check below\n * is one that cost a real regeneration or re-tune round to find by eye.\n *\n * `sharp` must stay confined to @ikijs/mcp; the decode goes through\n * ./node-images, this package's single image-decode boundary.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { decodePng } from \"./node-images\";\nimport { AutoRigInputError, MAX_LAYERS, resolveInputDir } from \"./limits\";\n\n// Iris width as a fraction of sclera width. Below the floor the eye reads as a\n// bead floating in white — that is the failure this check was written for, and\n// it caught a model that shipped at 0.33. The ceiling was a guess and it was\n// too tight: measured on a real anime reference the iris runs about 0.70 of the\n// eye, with the white reduced to corner crescents, so 0.6 flagged the correct\n// value as a fault three rounds running.\nconst IRIS_RATIO_MIN = 0.45;\nconst IRIS_RATIO_MAX = 0.72;\n// A sclera flatter than this cannot hold a round iris: the iris overflows the\n// lids no matter how narrow it is.\nconst EYE_ASPECT_MIN = 0.5;\n// How far the iris centre may sit from the white's centre of mass. The two axes\n// are not the same problem. Sideways drift is always a fault — that is the bug\n// this check was written for, a lash that fell out of sync with its sclera by\n// 14px. Vertically the reference itself rides its iris HIGH, tucked under the\n// lash with roughly a sixth of the aperture showing as white below it, so a\n// deliberate lift of that order is correct and a 3px ceiling flagged it.\nconst IRIS_OFFSET_MAX_X = 3;\nconst IRIS_OFFSET_MAX_Y = 10;\n// A cropped part shows a long, nearly-continuous opaque run along one bbox edge,\n// and that straight seam appears the moment the head turns. A round part's edge\n// row is a short tangent run, so a fraction test alone flags every iris; both a\n// high fraction AND real length are required to separate the two. Observed:\n// genuine crops read 60-93%, circle tangents 8-14%.\nconst EDGE_SOLID_MAX = 0.5;\n/** Lash-vs-sclera ink-centre drift tolerated as intrinsic asymmetry, as a\n * fraction of the eye width. See the check for why it is not zero. */\nconst LASH_CENTRE_TOL_FRAC = 0.03;\nconst EDGE_RUN_MIN_PX = 40;\n// Longest straight \"art appears out of nothing\" run tolerated inside a part, as\n// a fraction of its width. A body generated with hair draped over the shoulders\n// had that hair cut flat by its own frame; the cut hid behind the head at rest\n// and opened into a seam on turn. Measured: that part ran 15% of its width,\n// a clean one 5%, so the boundary sits between them.\nconst FLAT_CUT_MAX_FRAC = 0.1;\n// ...and long in absolute terms. A mouth's upper lip is a naturally horizontal\n// run that clears the fraction test on a narrow part while being only ~15px.\nconst FLAT_CUT_MIN_PX = 40;\n// The cut is antialiased, so the transition is a soft cliff rather than\n// transparent-to-opaque; 8/200 finds nothing at all on real art.\nconst FLAT_CUT_ALPHA_ABOVE = 120;\nconst FLAT_CUT_ALPHA_BELOW = 140;\n\n/** Alpha-derived geometry of one layer, in canvas pixels. */\nexport interface LayerStats {\n w: number;\n h: number;\n /** Longest flat cut through the art, and the row it runs along (-1 if none). */\n flatCutRun: number;\n flatCutY: number;\n bboxCx: number;\n bboxCy: number;\n massCx: number;\n massCy: number;\n /** Distance from the layer's content to each canvas edge. */\n marginTop: number;\n marginBottom: number;\n marginLeft: number;\n marginRight: number;\n /** Fraction of each bbox edge that is opaque. */\n edgeTop: number;\n edgeBottom: number;\n edgeLeft: number;\n edgeRight: number;\n canvasW: number;\n canvasH: number;\n}\n\nexport interface MeasureReport {\n /** Measured stats by role (the layer's file name without `.png`). */\n layers: Record<string, LayerStats>;\n /** Roles whose PNG is fully transparent — nothing to measure. */\n empty: string[];\n warnings: string[];\n}\n\nexport type MeasureResult =\n | ({ ok: true; layersDir: string; passed: boolean } & MeasureReport)\n | { ok: false; error: string };\n\nexport interface MeasureInput {\n /** Directory of role-named layer PNGs (relative paths resolve against cwd). */\n layersDir: string;\n}\n\n/**\n * Scan one layer PNG's alpha channel. Returns null for a fully transparent\n * layer. A decode failure surfaces as a path-qualified AutoRigInputError.\n */\nexport async function layerStats(filePath: string): Promise<LayerStats | null> {\n const { width: W, height: H, rgba } = await decodePng(filePath);\n const alpha = (x: number, y: number) => rgba[(y * W + x) * 4 + 3];\n\n let minX = W;\n let minY = H;\n let maxX = -1;\n let maxY = -1;\n let sumX = 0;\n let sumY = 0;\n let n = 0;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (alpha(x, y) > 8) {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n sumX += x;\n sumY += y;\n n++;\n }\n }\n }\n if (maxX < 0) return null; // fully transparent\n\n const edge = (pts: number[]) =>\n pts.filter((v) => v > 200).length / pts.length;\n const top: number[] = [];\n const bottom: number[] = [];\n const left: number[] = [];\n const right: number[] = [];\n for (let x = minX; x <= maxX; x++) {\n top.push(alpha(x, minY));\n bottom.push(alpha(x, maxY));\n }\n for (let y = minY; y <= maxY; y++) {\n left.push(alpha(minX, y));\n right.push(alpha(maxX, y));\n }\n\n // Longest contiguous run of pixels where the art appears out of nothing along\n // one row — transparent above, opaque below. Organic art (hair, cloth) meets\n // its silhouette at an angle, so a long FLAT run like this means the source\n // image was cropped through the drawing. It is often interior to the bbox\n // (a hair strand cut short above a wider shoulder line), which is why the\n // bbox-edge test alone misses it, and it only becomes visible once the head\n // turns and uncovers the cut.\n let flatCutRun = 0;\n let flatCutY = -1;\n for (let y = minY + 1; y <= maxY; y++) {\n let run = 0;\n for (let x = minX; x <= maxX; x++) {\n if (\n alpha(x, y - 1) < FLAT_CUT_ALPHA_ABOVE &&\n alpha(x, y) > FLAT_CUT_ALPHA_BELOW\n ) {\n run++;\n if (run > flatCutRun) {\n flatCutRun = run;\n flatCutY = y;\n }\n } else {\n run = 0;\n }\n }\n }\n\n return {\n w: maxX - minX + 1,\n h: maxY - minY + 1,\n flatCutRun,\n flatCutY,\n bboxCx: (minX + maxX) / 2,\n bboxCy: (minY + maxY) / 2,\n massCx: sumX / n,\n massCy: sumY / n,\n marginTop: minY,\n marginBottom: H - 1 - maxY,\n marginLeft: minX,\n marginRight: W - 1 - maxX,\n edgeTop: edge(top),\n edgeBottom: edge(bottom),\n edgeLeft: edge(left),\n edgeRight: edge(right),\n canvasW: W,\n canvasH: H,\n };\n}\n\nconst pct = (v: number) => `${(v * 100).toFixed(0)}%`;\n\n/**\n * Measure every `*.png` in an already-resolved layers directory (`preview.png`\n * is the composer's contact sheet, not a role) and run the geometry checks.\n */\nexport async function measureDir(absDir: string): Promise<MeasureReport> {\n const files = fs\n .readdirSync(absDir)\n .filter((f) => f.endsWith(\".png\") && f !== \"preview.png\")\n .sort();\n if (files.length === 0) {\n throw new AutoRigInputError(`no role layers in ${absDir}`);\n }\n // Same agent-supplied-input surface autoRigFromLayers bounds: a `layersDir`\n // pointed at an asset folder would decode every PNG in it before reporting.\n if (files.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers in ${absDir}: ${files.length} > ${MAX_LAYERS}`,\n );\n }\n\n const layers: Record<string, LayerStats> = {};\n const empty: string[] = [];\n for (const f of files) {\n const role = path.basename(f, \".png\");\n const m = await layerStats(path.join(absDir, f));\n if (!m) {\n empty.push(role);\n continue;\n }\n layers[role] = m;\n }\n\n const warnings: string[] = [];\n\n // 1. Art running to its own edge → a straight seam appears on head turn.\n // Two very different faults look identical in the flattened layer, and the\n // remedies cost differently, so tell them apart before prescribing one: a\n // part the CANVAS clipped has no margin left on that side (retune, free),\n // while a part placed with room whose own drawing runs to its frame does\n // (regenerate, billed). A real run lost a regeneration to this: the source\n // kept 44 px of margin and the default layout pushed it 70 px off-canvas,\n // so redrawing it reproduced the clip exactly.\n for (const [role, m] of Object.entries(layers)) {\n const edges: [string, number, number, number][] = [\n [\"top\", m.edgeTop, m.w, m.marginTop],\n [\"left\", m.edgeLeft, m.h, m.marginLeft],\n [\"right\", m.edgeRight, m.h, m.marginRight],\n ];\n // A torso is meant to run off the bottom of the canvas.\n if (role !== \"body\")\n edges.push([\"bottom\", m.edgeBottom, m.w, m.marginBottom]);\n for (const [side, v, span, margin] of edges) {\n if (v > EDGE_SOLID_MAX && v * span >= EDGE_RUN_MIN_PX) {\n const remedy =\n margin === 0\n ? // margin 0 is consistent with a clipped placement AND with art\n // already cropped flush that happens to sit on the boundary, and\n // the flattened layer cannot separate them — so name the free\n // move rather than the cause. If moving it inward leaves the\n // edge opaque, the drawing is the one at fault.\n `it sits flush against the canvas ${side}, which a clipped placement and already-cropped ` +\n `art both produce. Move it inward first — retune layout.${role}.cx/cy/w, free — and ` +\n `remeasure; regenerate only if the edge is still opaque with margin to spare.`\n : `its own drawing runs to the frame ${margin} px inside the canvas — regenerate that part ` +\n `with empty margin on that side. Billed.`;\n warnings.push(\n `${role}: ${pct(v)} of its ${side} edge is opaque — the art is cut off there, ` +\n `which shows as a straight seam once the head turns. Cause: ${remedy}`,\n );\n }\n }\n }\n\n // 1b. A straight cut through the drawing, wherever it falls in the bbox.\n for (const [role, m] of Object.entries(layers)) {\n // `body` moves only as a rigid whole (a light share of the head's turn\n // and breath), so no pose can uncover a cut in it; its top is deliberately\n // cut flat where the jaw covers it.\n if (role === \"body\") continue;\n if (\n m.flatCutRun > FLAT_CUT_MAX_FRAC * m.w &&\n m.flatCutRun >= FLAT_CUT_MIN_PX\n ) {\n warnings.push(\n `${role}: ${m.flatCutRun}px of straight flat edge at y=${m.flatCutY} ` +\n `(${pct(m.flatCutRun / m.w)} of its width) — the source art is cut through there. ` +\n `It hides while the head faces front and opens into a seam on turn. ` +\n `Regenerate this part with the whole subject inside the frame.`,\n );\n }\n }\n\n // 2/3/4. Eye stack geometry, per side.\n for (const side of [\"L\", \"R\"]) {\n const eye: LayerStats | undefined = layers[`eye_${side}`];\n const iris: LayerStats | undefined = layers[`iris_${side}`];\n const lash: LayerStats | undefined = layers[`lash_${side}`];\n if (!eye) continue;\n\n const aspect = eye.h / eye.w;\n if (aspect < EYE_ASPECT_MIN) {\n warnings.push(\n `eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} — ` +\n `a round iris cannot sit inside it. Free fix first: set layout.eye_${side}.h and ` +\n `layout.lash_${side}.h to ${Math.ceil(eye.w * EYE_ASPECT_MIN)} (both, or the fold tears) — ` +\n `stretching a flat white lens is invisible. Regenerate the eyewhite taller only if that ` +\n `distorts the lash.`,\n );\n }\n\n if (iris) {\n const ratio = iris.w / eye.w;\n if (ratio < IRIS_RATIO_MIN || ratio > IRIS_RATIO_MAX) {\n warnings.push(\n `iris_${side}: width is ${pct(ratio)} of the sclera (target ${IRIS_RATIO_MIN}-${IRIS_RATIO_MAX}) — ` +\n `retune layout.iris_${side}.w (keep it a fraction of the eye width), no regeneration needed.`,\n );\n }\n const dx = iris.bboxCx - eye.massCx;\n const dy = iris.bboxCy - eye.massCy;\n if (\n Math.abs(dx) > IRIS_OFFSET_MAX_X ||\n Math.abs(dy) > IRIS_OFFSET_MAX_Y\n ) {\n warnings.push(\n `iris_${side}: sits (${dx.toFixed(1)}, ${dy.toFixed(1)}) px from the white's centre of mass — ` +\n `retune layout.iris_${side}.cx/cy. The sclera's bbox centre is NOT its visual centre when the ` +\n `lash flick stretches the box.`,\n );\n }\n }\n\n // 5. The lash and the white are split from ONE source and pasted with the\n // same cx/cy/w, so their frames coincide even though the lash only inks the\n // upper part of it (its content sits higher — that is the fold working, not\n // a fault). What must line up is the horizontal centre and the top edge; a\n // drift there means the two layout entries fell out of sync and the fold\n // will tear.\n if (lash) {\n const dx = lash.bboxCx - eye.bboxCx;\n const dTop = lash.marginTop - eye.marginTop;\n // dx compares INK centres, and the lash's ink is narrower than the frame it\n // shares with the sclera, so a lash whose flick runs one way sits a pixel or\n // two off-centre while its layout entry is perfectly in sync — a real run\n // measured 1.5 px on a 128 px eye and the warning could not be acted on.\n // Scale the tolerance with the eye so the desync this guards (14 px on a\n // real character) still trips it. dTop stays strict: the fold seam rides\n // that edge, and both layers ink the same top row when they are in sync.\n if (Math.abs(dx) > eye.w * LASH_CENTRE_TOL_FRAC || Math.abs(dTop) > 0.5) {\n warnings.push(\n `lash_${side}: centre is ${dx.toFixed(1)} px and top edge ${dTop.toFixed(1)} px off eye_${side}. ` +\n `They are split from one source and MUST share cx/cy/w in layout, or the blink fold tears. Retune to match.`,\n );\n }\n }\n }\n\n // 6. Optional roles that change how finished the character reads.\n for (const [role, why] of [\n [\"body\", \"without it the character reads as a floating head on head-turn\"],\n [\"hair_back\", \"without it the silhouette is flat behind the face\"],\n [\n \"nose\",\n \"without it nothing on the face slides on the head turn — the features stay on the plate\",\n ],\n ]) {\n if (layers[role] === undefined) warnings.push(`${role}: missing — ${why}.`);\n }\n\n return { layers, empty, warnings };\n}\n\n/**\n * Measure a caller-supplied layers directory.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function measureLayers(\n input: MeasureInput,\n): Promise<MeasureResult> {\n try {\n const layersDir = resolveInputDir(input.layersDir);\n const report = await measureDir(layersDir);\n return {\n ok: true,\n layersDir,\n ...report,\n passed: report.warnings.length === 0,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n\n/**\n * Render a measurement as plain text: the per-layer table first (numbers to\n * argue with), then the checks that fired. Takes the report itself rather than\n * a MeasureResult so a caller holding one inline (no `ok` to unwrap) can print\n * it too; a failed measurement has no report to render.\n */\nexport function formatMeasureReport(\n result: MeasureReport & { layersDir: string },\n): string {\n const lines = [\n `# layers (${result.layersDir})`,\n \"\",\n \"role size bbox-centre mass-centre margins t/b/l/r\",\n ];\n // Roles come off a sorted file listing, so sorting the two groups back\n // together restores that order.\n for (const role of [...Object.keys(result.layers), ...result.empty].sort()) {\n const m = result.layers[role];\n if (m === undefined) {\n lines.push(`${role.padEnd(13)} EMPTY (fully transparent)`);\n continue;\n }\n lines.push(\n `${role.padEnd(13)} ${`${m.w}x${m.h}`.padEnd(11)} ` +\n `${`${m.bboxCx.toFixed(0)},${m.bboxCy.toFixed(0)}`.padEnd(14)} ` +\n `${`${m.massCx.toFixed(0)},${m.massCy.toFixed(0)}`.padEnd(13)} ` +\n `${m.marginTop}/${m.marginBottom}/${m.marginLeft}/${m.marginRight}`,\n );\n }\n\n lines.push(\"\", \"# checks\", \"\");\n if (result.warnings.length === 0) {\n lines.push(\"all geometry checks passed\");\n } else {\n for (const w of result.warnings) lines.push(`- ${w}`);\n }\n return lines.join(\"\\n\");\n}\n","/**\n * Compose AI-generated part PNGs into canvas-aligned, role-named layers for the\n * Iki auto-rig (`auto_rig_from_layers` / `@ikijs/editor` generateIkiFromLayerSet).\n * Each part is alpha-trimmed, resized to a target width, optionally mirrored,\n * and pasted at a chosen center on a shared transparent CANVAS x CANVAS canvas.\n *\n * Ports the composer that shipped as a script in the Claude Code plugin, so a\n * plugin user gets it from the MCP server instead of an ad-hoc `sharp` install.\n * Composing is deterministic: same parts -> same layers, so re-run freely after\n * tuning `layout` (no image re-generation needed).\n *\n * `sharp` must stay confined to @ikijs/mcp; part decoding goes through\n * ./node-images, this package's single image-decode boundary.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport sharp from \"sharp\";\nimport { cropToBuffer, decodePng } from \"./node-images\";\nimport { measureDir, type MeasureReport } from \"./measure\";\nimport {\n AutoRigInputError,\n resolveInputDir,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n/**\n * Side of the square layer canvas, in px. NOT an input: the layout defaults\n * below place parts against this size (hair_front alone is 660px wide, and\n * sharp rejects a composite input larger than its destination), so a different\n * canvas would need its own layout. The tuning surface is `layout` overrides.\n */\nexport const CANVAS = 1100;\n\n// Iris width as a fraction of the sclera width. Anime irises fill most of the\n// eye opening and are clipped by the lids — the auto-rig clips iris->sclera at\n// runtime, so a large iris cannot spill. The first sample's 32% iris read as a\n// bead floating in white, so the defaults below use 56.25% (72px in a 128px\n// opening) to reduce excess white below the iris. A caller retunes eye size\n// through `layout.eye_L/eye_R.w` and MUST move `layout.iris_L/iris_R.w` with it\n// to keep that ratio.\nconst EYE_W = 128;\nconst IRIS_W = Math.round(EYE_W * 0.5625);\n\n/** The eyewhite source that prepEyeSplit() splits into sclera + lash. */\nconst EYEWHITE_SRC = \"eyewhite.png\";\n/** Luminance below this (0..255) = a dark lash/outline pixel in the eyewhite. */\nconst EYE_LASH_LUMA = 120;\n// Of the eye's dark pixels, keep only those in the TOP this-fraction as the lash\n// (drops the lower almond rim/outline) so the lash reads as an upper arc that\n// folds DOWN over the eye on blink, instead of a full ring that shrinks in place.\nconst LASH_KEEP_FRACTION = 0.5;\n\ninterface RoleLayout {\n /** Part file name in the parts dir (the eye pair's two are split in memory). */\n src: string;\n /** Center in canvas px, origin top-left, y down. */\n cx: number;\n cy: number;\n /** Target width in px. */\n w: number;\n /**\n * Target height in px. Omitted, the height follows the part's own aspect\n * ratio — which is the right default for every role whose drawing already has\n * the proportions it should. It exists for the one that does not: an eyewhite\n * comes back flatter than the reference often enough that three generations\n * asking for \"taller\" landed at 0.47, while stretching a flat white lens ~15%\n * is invisible and free. Set it on the sclera and its lash together or the\n * fold tears — they share one frame.\n */\n h?: number;\n optional?: boolean;\n mirror?: boolean;\n noTrim?: boolean;\n}\n\n// ── DEFAULT LAYOUT (tune per character through `layout`) ──────────────────────\n// These defaults assume the standard framing the character skill prompts for\n// (a front-facing face centered on the canvas). If the rendered model is\n// misaligned, tune cx/cy/w through the `layout` override and re-run — composing\n// is cheap and the parts do not need regenerating.\n//\n// eyeSide reminder: eye_L = character's LEFT eye = screen RIGHT (larger cx).\n// eye_* = clean WHITE sclera (lashes recolored white) = the blink clip mask + fold.\n// iris_* = colored disc on top, clipped to the sclera, drives gaze.\n// lash_* = the dark lashes, a separate layer ABOVE the iris that folds down to\n// cover the closed-eye seam. eye_* and lash_* are split from a single\n// `eyewhite.png` (white almond + dark lashes) by prepEyeSplit().\nconst DEFAULT_LAYOUT = {\n // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir\n // without them still composes (head-only character).\n hair_back: { src: \"hair_back.png\", cx: 550, cy: 523, w: 800, optional: true },\n // The torso, cut off by the canvas bottom. It rides its own `bodyDeformer`: a\n // light share of the head turn and half its breath bob, so the character is\n // not a floating head.\n body: { src: \"body.png\", cx: 550, cy: 1017, w: 840, optional: true },\n face: { src: \"face.png\", cx: 550, cy: 475, w: 400 },\n // The nose, drawn on its own (the face is drawn without one): the auto-rig\n // leads the head turn with it and keys the other features' slide on its\n // presence, so without it the features stay on the face plate. Sits between\n // the eyes and above the mouth. OPTIONAL: a parts dir without it composes.\n nose: { src: \"nose.png\", cx: 550, cy: 586, w: 40, optional: true },\n mouth: { src: \"mouth.png\", cx: 550, cy: 619, w: 68 },\n // Cross-fades with `mouth` on ParamMouthOpenY (opacity, not scaleY) once the\n // auto-rig sees both roles. Same cx/w as `mouth` so the lip width matches;\n // its top edge (not center) lines up with the closed mouth's top edge since\n // the mouth opens downward from a fixed upper lip — hence the +2 cy nudge\n // rather than sharing cy outright. Optional: composes fine without it.\n mouth_open: {\n src: \"mouth_open.png\",\n cx: 550,\n cy: 621,\n w: 68,\n optional: true,\n },\n // eye_* (sclera) and lash_* share the eyewhite's cropped frame via noTrim (so\n // they are NOT re-bboxed independently): the upper lash stays anchored ABOVE\n // the sclera center, so on blink it folds DOWN over the eye like the sample\n // model instead of the whole eye shrinking in place. Same cx/cy/w.\n eye_L: { src: \"eyewhite_sclera.png\", cx: 657, cy: 475, w: EYE_W, mirror: true, noTrim: true }, // prettier-ignore\n eye_R: { src: \"eyewhite_sclera.png\", cx: 443, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n iris_L: { src: \"iris.png\", cx: 653, cy: 475, w: IRIS_W, mirror: false },\n iris_R: { src: \"iris.png\", cx: 447, cy: 475, w: IRIS_W, mirror: false },\n lash_L: {\n src: \"eyewhite_lash.png\",\n cx: 657,\n cy: 475,\n w: EYE_W,\n mirror: true,\n noTrim: true,\n },\n lash_R: { src: \"eyewhite_lash.png\", cx: 443, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n brow_L: { src: \"brow.png\", cx: 645, cy: 405, w: 135, mirror: false },\n brow_R: { src: \"brow.png\", cx: 455, cy: 405, w: 135, mirror: true },\n hair_front: { src: \"hair_front.png\", cx: 550, cy: 425, w: 660 },\n} satisfies Record<string, RoleLayout>;\n\nexport type Role = keyof typeof DEFAULT_LAYOUT;\n\n/** Draw order (back -> front), mirrors @ikijs/editor ROLE_TABLE order. */\nconst ORDER: Role[] = [\n \"hair_back\",\n \"body\",\n \"face\",\n \"nose\",\n \"mouth\",\n \"mouth_open\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"lash_L\",\n \"lash_R\",\n \"brow_L\",\n \"brow_R\",\n \"hair_front\",\n];\n\n/** Per-role placement overrides; anything omitted keeps the default above. */\nexport type LayoutOverride = Partial<\n Record<Role, { cx?: number; cy?: number; w?: number; h?: number }>\n>;\n\nexport interface ComposeInput {\n /** Directory of the generated part PNGs (relative paths resolve against cwd). */\n partsDir: string;\n /**\n * Existing directory under cwd to write the role layers into. Callers reuse\n * one across runs (it must pre-exist), so the compose leaves it holding\n * exactly the roles it reports: a skipped role's layer from an earlier run is\n * removed rather than left for the next tool to pick up.\n */\n outDir: string;\n layout?: LayoutOverride;\n}\n\nexport interface ComposedLayer {\n role: Role;\n path: string;\n /** Size of the placed part itself (the file is always CANVAS x CANVAS). */\n width: number;\n height: number;\n left: number;\n top: number;\n}\n\nexport type ComposeResult =\n | {\n ok: true;\n outDir: string;\n layers: ComposedLayer[];\n /** Roles whose optional part was absent from the parts dir. */\n skipped: Role[];\n preview: string;\n measure: MeasureReport;\n }\n | { ok: false; error: string };\n\n/**\n * Merge caller overrides onto the defaults. Input boundary: an unknown role, a\n * non-finite centre or an out-of-range width fails fast, path-qualified, before\n * any decode. `w` is capped at CANVAS so a resized part can never exceed the\n * canvas width; `cx`/`cy` are unbounded here because a part may legitimately\n * hang off an edge — placement() rejects the one that lands nowhere on it.\n */\nfunction resolveLayout(\n overrides: LayoutOverride | undefined,\n): Record<Role, RoleLayout> {\n const resolved: Record<Role, RoleLayout> = { ...DEFAULT_LAYOUT };\n if (overrides === undefined) return resolved;\n for (const [role, override] of Object.entries(overrides)) {\n if (!Object.prototype.hasOwnProperty.call(DEFAULT_LAYOUT, role)) {\n throw new AutoRigInputError(\n `layout.${role}: unknown role — expected one of ${Object.keys(DEFAULT_LAYOUT).join(\", \")}`,\n );\n }\n if (override === undefined) continue;\n const next = { ...resolved[role as Role] };\n for (const field of [\"cx\", \"cy\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n if (!Number.isFinite(value)) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be a finite number, got ${String(value)}`,\n );\n }\n next[field] = value;\n }\n for (const field of [\"w\", \"h\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n if (!Number.isInteger(value) || value < 1 || value > CANVAS) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be an integer in 1..${CANVAS}, got ${String(value)}`,\n );\n }\n next[field] = value;\n }\n resolved[role as Role] = next;\n }\n return resolved;\n}\n\n/**\n * Some generated parts come back opaque on a white background (no alpha).\n * Key near-white pixels to transparent so they can layer cleanly.\n */\nfunction keyWhiteToAlpha(rgba: Buffer): Buffer {\n const keyed = Buffer.from(rgba);\n for (let i = 0; i < keyed.length; i += 4) {\n if (keyed[i] > 238 && keyed[i + 1] > 238 && keyed[i + 2] > 238) {\n keyed[i + 3] = 0;\n }\n }\n return keyed;\n}\n\n/**\n * Trim/mirror a part and resize it to its layout width. `inMemory` carries the\n * eye pair's two split buffers; every other role is read from the parts dir.\n * Missing optional part -> null; missing required part -> AutoRigInputError.\n */\nasync function partBuffer(\n role: Role,\n cfg: RoleLayout,\n partsDir: string,\n inMemory: Buffer | undefined,\n): Promise<{ buf: Buffer; w: number; h: number } | null> {\n let img: sharp.Sharp;\n if (inMemory !== undefined) {\n img = sharp(inMemory);\n } else {\n const srcPath = path.join(partsDir, cfg.src);\n if (!fs.existsSync(srcPath)) {\n // Optional roles (hair_back, body, mouth_open) are absent from a\n // head-only parts dir; the auto-rig only requires face/eye_L/eye_R/mouth.\n if (cfg.optional) return null;\n // Name the role, not just the file: one source feeds two roles\n // (brow.png -> brow_L/brow_R), so the path alone does not say what broke.\n throw new AutoRigInputError(\n `missing part source for role \"${role}\": ${srcPath}`,\n );\n }\n const png = await decodePng(srcPath);\n // decodePng is the package's decode boundary: it caps the source at\n // MAX_INPUT_PIXELS and reports a bad/corrupt file as a path-qualified\n // AutoRigInputError, so the raw re-wrap below is already bounded.\n img = sharp(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {\n raw: { width: png.width, height: png.height, channels: 4 },\n });\n }\n // noTrim parts (the eye and lash pairs) keep their shared pre-cropped frame so\n // sclera and lash stay aligned; everything else is alpha-trimmed to its own bbox.\n if (!cfg.noTrim) img = img.trim({ threshold: 12 });\n if (cfg.mirror) img = img.flop();\n // Materialise the trimmed part BEFORE resizing: its size is bounded by the\n // source decode limit, so the height the resize WOULD produce can be checked\n // against the canvas while only the bounded buffer is allocated.\n const trimmed = await img.png().toBuffer({ resolveWithObject: true });\n // An explicit h is already bounded by resolveLayout; only the aspect-derived\n // height can run past the canvas.\n if (cfg.h === undefined) {\n const scaledH = Math.round(\n (trimmed.info.height * cfg.w) / trimmed.info.width,\n );\n if (scaledH > CANVAS) {\n throw new AutoRigInputError(\n `layout.${role}.w: resized part ${cfg.w}x${scaledH} exceeds the ${CANVAS} canvas`,\n );\n }\n }\n const resized = await sharp(trimmed.data)\n // Width alone keeps the source aspect. With h, fit:\"fill\" is the point —\n // stretch to the given box instead. Both options stay off the width-only\n // path: passing height:undefined alongside fit:\"fill\" makes sharp drop the\n // aspect it would otherwise preserve.\n .resize(\n cfg.h === undefined\n ? { width: cfg.w }\n : { width: cfg.w, height: cfg.h, fit: \"fill\" },\n )\n .png()\n .toBuffer({ resolveWithObject: true });\n return {\n buf: resized.data,\n w: resized.info.width,\n h: resized.info.height,\n };\n}\n\n/**\n * Where the part lands, centred on its layout cx/cy. Running off an edge is\n * legitimate — `body` is meant to be cut off by the canvas bottom — so the test\n * is INTERSECTION, not containment. A part that misses the canvas entirely\n * composes to a fully transparent layer that nothing downstream flags\n * (measureDir warns per measured layer, and an empty one has no geometry), so a\n * sign-flipped centre would otherwise read as success.\n */\nfunction placement(role: Role, cfg: RoleLayout, w: number, h: number) {\n const left = Math.round(cfg.cx - w / 2);\n const top = Math.round(cfg.cy - h / 2);\n if (left + w <= 0 || top + h <= 0 || left >= CANVAS || top >= CANVAS) {\n throw new AutoRigInputError(\n `layout.${role}.cx/cy: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${CANVAS} canvas`,\n );\n }\n return { left, top };\n}\n\nfunction blankCanvas() {\n return sharp({\n create: {\n width: CANVAS,\n height: CANVAS,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n });\n}\n\n/**\n * Split eyewhite.png (white almond + dark lashes) into a clean white sclera\n * (the dark outline/lash recolored to white = the blink clip-mask shape) and a\n * dark UPPER-lash-only layer. Both are cropped to the SAME eye bbox so they stay\n * aligned (consumed with noTrim): the lash arc keeps its position at the top of\n * the sclera, so on blink it folds DOWN over the eye rather than the eye shrinking\n * in place.\n *\n * Both come back as PNG buffers. The script this ports wrote them back into the\n * parts dir, but that dir is an INPUT here (reads are deliberately unconfined),\n * so the tool never writes there — only under the confined outDir.\n */\nasync function prepEyeSplit(\n partsDir: string,\n): Promise<{ sclera: Buffer; lash: Buffer }> {\n const srcPath = path.join(partsDir, EYEWHITE_SRC);\n if (!fs.existsSync(srcPath)) {\n throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);\n }\n const { width: W, height: H, rgba: data } = await decodePng(srcPath);\n\n // Eye content bbox (alpha) → the shared cropped frame for both outputs.\n let minX = W;\n let minY = H;\n let maxX = -1;\n let maxY = -1;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (data[(y * W + x) * 4 + 3] > 8) {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n }\n }\n if (maxX < 0) {\n throw new AutoRigInputError(`eyewhite is fully transparent: ${srcPath}`);\n }\n // Keep only the upper lash: dark pixels above this row become the lash layer.\n const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);\n\n const sclera = Buffer.from(data);\n const lash = Buffer.from(data);\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n const i = (y * W + x) * 4;\n const lum = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];\n const isDark = data[i + 3] > 0 && lum < EYE_LASH_LUMA;\n if (isDark) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255; // dark -> white\n if (!(isDark && y <= lashCutoffY)) lash[i + 3] = 0; // keep upper dark only\n }\n }\n const region = {\n x: minX,\n y: minY,\n w: maxX - minX + 1,\n h: maxY - minY + 1,\n };\n return {\n sclera: await cropToBuffer(sclera, W, H, region),\n lash: await cropToBuffer(lash, W, H, region),\n };\n}\n\n/**\n * Compose a parts directory into role-named layers plus a flattened preview,\n * then measure the result so the caller sees the geometry checks inline.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function composeLayersFromParts(\n input: ComposeInput,\n): Promise<ComposeResult> {\n try {\n // Resolve the output dir FIRST (fail-fast): reject a missing or escaping\n // target before spending the decode budget on a run that cannot be written.\n const outDir = resolveOutputDir(input.outDir);\n const partsDir = resolveInputDir(input.partsDir);\n // resolveOutputDir already realpath's outDir; resolveInputDir does not (its\n // reads are deliberately unconfined), so realpath partsDir here too before\n // comparing — otherwise a symlink alias of the same directory would slip\n // past a lexical check. Composing a parts dir into itself would overwrite\n // originals like face.png/hair_front.png with resized, cropped layers, and\n // skipped-role cleanup would delete sources with no surviving part.\n if (fs.realpathSync(partsDir) === outDir) {\n throw new AutoRigInputError(\n `partsDir and outDir resolve to the same directory (${outDir}): composing would overwrite the source parts`,\n );\n }\n const layout = resolveLayout(input.layout);\n\n const split = await prepEyeSplit(partsDir);\n const splitSources = new Map<string, Buffer>([\n [\"eyewhite_sclera.png\", split.sclera],\n [\"eyewhite_lash.png\", split.lash],\n ]);\n\n const layers: ComposedLayer[] = [];\n const skipped: Role[] = [];\n const preview: { input: Buffer; left: number; top: number }[] = [];\n for (const role of ORDER) {\n const cfg = layout[role];\n const part = await partBuffer(\n role,\n cfg,\n partsDir,\n splitSources.get(cfg.src),\n );\n if (part === null) {\n skipped.push(role);\n // Drop this role's layer from an earlier compose into the same dir:\n // left behind it would contradict `skipped`, since measureDir globs the\n // directory (the report would still show a body) and the next\n // auto_rig_from_layers would rig the stale file into the model. Only the\n // fixed ORDER role names, under the confined outDir, are ever removed.\n fs.rmSync(path.join(outDir, `${role}.png`), { force: true });\n continue;\n }\n const { left, top } = placement(role, cfg, part.w, part.h);\n // role layer: this part alone on a full canvas at its position.\n const layer = await blankCanvas()\n .composite([{ input: part.buf, left, top }])\n .png()\n .toBuffer();\n const outPath = path.join(outDir, `${role}.png`);\n writeFileAtomic(outPath, layer);\n layers.push({\n role,\n path: outPath,\n width: part.w,\n height: part.h,\n left,\n top,\n });\n preview.push({ input: part.buf, left, top });\n }\n\n // Flattened preview over a light bg so transparency reads clearly.\n const previewPng = await sharp({\n create: {\n width: CANVAS,\n height: CANVAS,\n channels: 4,\n background: { r: 245, g: 245, b: 248, alpha: 1 },\n },\n })\n .composite(preview)\n .png()\n .toBuffer();\n const previewPath = path.join(outDir, \"preview.png\");\n writeFileAtomic(previewPath, previewPng);\n\n return {\n ok: true,\n outDir,\n layers,\n skipped,\n preview: previewPath,\n measure: await measureDir(outDir),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n validateIki,\n describeIki,\n listStandardParameters,\n autoRigFromLayers,\n} from \"./tools\";\nimport { composeLayersFromParts } from \"./compose\";\nimport { measureLayers, formatMeasureReport } from \"./measure\";\nimport { measureTurnReference, formatTurnReport } from \"./measure-turn\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers; returns an error for an invalid model.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"Auto-rigs role-named PNG layers (face, eye_L/eye_R, mouth required; iris_L/R, brow_L/R, hair_front, etc. optional) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n quantizeColors: z\n .number()\n .int()\n .min(2)\n .max(256)\n .optional()\n .describe(\n \"Palette-quantize the atlas PNG to this many colours (2..256). Flat-shaded art keeps its look at 256 and the model shrinks to about a quarter; omit for lossless.\",\n ),\n turnTargets: z\n .object({\n eyeShift: z.number().optional(),\n farEyeRatio: z.number().optional(),\n silhouetteRatio: z.number().optional(),\n noseShift: z.number().optional(),\n mouthShift: z.number().optional(),\n })\n .optional()\n .describe(\n \"What the head turn is fitted to, as `measure_turn_reference` reports it off a front/turned reference pair. `eyeShift` (and the optional `noseShift`/`mouthShift`, derived from it when absent) is how far that feature slides across the head at full turn, as a fraction of the head's half-width — a MAGNITUDE: the rig turns both ways, so the sign is ignored. `farEyeRatio` is the far/near eye width at full turn over that same ratio at rest, `silhouetteRatio` the head's half-width turned over at rest. The half-width the shifts are fractions of is measured off the layers themselves, so it is not an input. An omitted field falls back to a default, which is clamped to what this layer set can do (the result's `turn.clamped` lists the ones that were, `turn.achieved` what the rig reaches); a target you DO pass that this layer set cannot reach comes back as `INVALID: …` naming the field and the attainable range, since it is a measurement rather than a preference.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await autoRigFromLayers(args);\n const text = r.ok ? r.path : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"compose_layers_from_parts\",\n {\n description:\n \"Composes AI-generated part PNGs into canvas-aligned, role-named PNG layers on disk, ready for auto_rig_from_layers (the eyewhite split, alpha-trim/white-key, and placement pipeline the character-generation skill needs), with the same geometry report measure_layers returns standalone included inline. face, mouth, eyewhite, iris, brow, hair_front are required; hair_back, body, mouth_open, nose are optional — without a nose layer the rig does not slide the features on the head turn.\",\n inputSchema: {\n partsDir: z\n .string()\n .describe(\n \"Directory of the source part PNGs (resolved against cwd).\",\n ),\n outDir: z\n .string()\n .describe(\n \"Existing directory to write the role layer PNGs + preview.png into (resolved against cwd; must already exist; confined to the working directory). Reused across runs: a role this run skips has its stale PNG from an earlier run deleted.\",\n ),\n layout: z\n .record(\n z.string(),\n z\n .object({\n cx: z.number(),\n cy: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .partial(),\n )\n .optional()\n .describe(\n \"Per-role override merged over the built-in defaults, keyed by role — hair_back, body, face, nose, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front — e.g. `{ eye_L: { cx: 660 } }`. `w` and `h` are integers in 1..1100; omit `h` to keep the part's own aspect, set it to stretch (set it on a sclera and its lash together, or the blink fold tears).\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await composeLayersFromParts(args);\n const text = r.ok\n ? [\n ...r.layers.map((l) => l.path),\n formatMeasureReport({ ...r.measure, layersDir: r.outDir }),\n ].join(\"\\n\")\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"measure_layers\",\n {\n description:\n \"Reports read-only geometry checks over an already-composed layers directory — the same checks compose_layers_from_parts returns inline (iris ratio/offset, eye aspect, cropped/cut edges, missing optional roles). Use to re-check a layers dir without recomposing.\",\n inputSchema: {\n layersDir: z\n .string()\n .describe(\n \"Directory of role-named layer PNGs (resolved against cwd).\",\n ),\n },\n },\n async ({ layersDir }) => {\n try {\n const r = await measureLayers({ layersDir });\n const text = r.ok ? formatMeasureReport(r) : `INVALID: ${r.error}`;\n // Spread into a fresh object: MeasureResult's ok:true arm is an\n // intersection with the MeasureReport interface, which TS won't accept\n // directly against the SDK's `Record<string, unknown>` structuredContent\n // — spreading drops that nominal interface identity, same value.\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { ...r },\n };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"measure_turn_reference\",\n {\n description:\n \"Measures how far a head turns between two images of the same character — a front view and a turned one, at the SAME scale — as three ratios, so a rigged turn can be compared to a reference turn (or to an earlier rig) without registering the images: farEyeRatio (turned far/near iris width over the same ratio at rest), eyeShift (how far the eye pair slides across the head, in units of the FRONT head half-width; NEGATIVE = toward the image's left), silhouetteRatio (head half-width, turned over front). The ratios divide out crop and position, not scale, so the pair must already share framing and head size; since a yaw never changes iris height, a pair whose mean iris height differs by more than 10% is refused instead of measured as a turn. Reads engine renders (transparent backdrop) and opaque reference art alike.\",\n inputSchema: {\n front: z\n .string()\n .describe(\"Front-facing PNG file path (resolved against cwd).\"),\n turned: z\n .string()\n .describe(\"The same character turned, as a PNG file path.\"),\n iris: z\n .object({\n hueMin: z.number().min(0).max(360),\n hueMax: z.number().min(0).max(360),\n satMin: z.number().min(0).max(1),\n })\n .partial()\n .optional()\n .describe(\n \"Iris colour window override merged over the violet default (hue 230..300, sat > 0.22) — set it for a character whose eyes are another colour.\",\n ),\n debugDir: z\n .string()\n .optional()\n .describe(\n \"Existing directory (resolved against cwd; confined to the working directory) to write `front-<name>.debug.png` / `turned-<name>.debug.png` overlays into, with the iris boxes and head edges drawn.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await measureTurnReference(args);\n const text = r.ok ? formatTurnReport(r) : `INVALID: ${r.error}`;\n // Spread into a fresh object: the ok:true arm is an intersection with\n // the TurnMeasurement interface, which TS won't accept directly against\n // the SDK's Record<string, unknown> structuredContent.\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { ...r },\n };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n return server;\n}\n"],"mappings":";AA6BA,OAAOA,WAAU;;;ACfjB,OAAO,WAAW;AAElB,SAAS,mBAAmB,qBAAqB;;;ACJjD,OAAO,QAAQ;AACf,OAAO,UAAU;AAGV,IAAM,aAAa;AAEnB,IAAM,gBAAgB;AAEtB,IAAM,iBAAiB;AAEvB,IAAM,iBAAiB,OAAO;AAE9B,IAAM,mBAAmB,OAAO;AAGhC,IAAM,mBAAmB,KAAK,OAAO;AAErC,IAAM,mBAAmB,IAAI,OAAO;AAOpC,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAQA,SAAS,iBAAiB,WAAmB,MAAc,MAAoB;AAC7E,MAAI,OAAO,cAAc,YAAY,UAAU,KAAK,MAAM,IAAI;AAC5D,UAAM,IAAI,kBAAkB,GAAG,IAAI,WAAW;AAAA,EAChD;AACA,MAAI,2BAA2B,KAAK,SAAS,GAAG;AAC9C,UAAM,IAAI;AAAA,MACR,GAAG,IAAI,cAAc,IAAI,gBAAgB,SAAS;AAAA,IACpD;AAAA,EACF;AACF;AAoBO,SAAS,iBAAiB,WAA2B;AAC1D,mBAAiB,WAAW,cAAc,WAAW;AACrD,QAAM,WAAW,KAAK,QAAQ,QAAQ,IAAI,GAAG,SAAS;AACtD,MAAI;AACJ,MAAI;AACF,WAAO,GAAG,SAAS,QAAQ;AAAA,EAC7B,QAAQ;AACN,UAAM,IAAI,kBAAkB,yBAAyB,QAAQ,EAAE;AAAA,EACjE;AACA,MAAI,KAAK,YAAY,GAAG;AACtB,UAAM,IAAI;AAAA,MACR,0CAA0C,QAAQ;AAAA,IACpD;AAAA,EACF;AACA,SAAO;AACT;AAGO,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AA,MACF,SAAS,KAAK;AACZ,cAAM,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC7D,eAAO;AAAA,UACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,qBAAqB,KAAK,GAAG,CAAC;AAAA,UAC9D,mBAAmB,EAAE,IAAI,OAAO,MAAM;AAAA,UACtC,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["path","placement","path","path","path","placement","fs","path","fs","path","fs","path","sharp","sharp","path","fs"]}
|
package/dist/cli.js
CHANGED
|
@@ -864,7 +864,7 @@ async function autoRigFromLayers(input) {
|
|
|
864
864
|
}
|
|
865
865
|
}
|
|
866
866
|
rowSpansByRole.push({ role, rowLeft, rowRight });
|
|
867
|
-
|
|
867
|
+
const layer = {
|
|
868
868
|
role,
|
|
869
869
|
fileName,
|
|
870
870
|
canvasW,
|
|
@@ -872,7 +872,17 @@ async function autoRigFromLayers(input) {
|
|
|
872
872
|
bbox,
|
|
873
873
|
cropW: bbox.w,
|
|
874
874
|
cropH: bbox.h
|
|
875
|
-
}
|
|
875
|
+
};
|
|
876
|
+
if (role === "face") {
|
|
877
|
+
const rowHalfWidths = [];
|
|
878
|
+
for (let y = bbox.y; y < bbox.y + bbox.h; y++) {
|
|
879
|
+
rowHalfWidths.push(
|
|
880
|
+
rowRight[y] >= rowLeft[y] ? headHalfOf({ left: rowLeft[y], right: rowRight[y] }) : 0
|
|
881
|
+
);
|
|
882
|
+
}
|
|
883
|
+
layer.rowHalfWidths = rowHalfWidths;
|
|
884
|
+
}
|
|
885
|
+
layerInputs.push(layer);
|
|
876
886
|
crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
|
|
877
887
|
}
|
|
878
888
|
const eyeRow = eyeRowOf(layerInputs);
|
|
@@ -1508,7 +1518,7 @@ async function composeLayersFromParts(input) {
|
|
|
1508
1518
|
|
|
1509
1519
|
// src/server.ts
|
|
1510
1520
|
function createIkiMcpServer() {
|
|
1511
|
-
const server = new import_mcp.McpServer({ name: "iki", version: "0.8.
|
|
1521
|
+
const server = new import_mcp.McpServer({ name: "iki", version: "0.8.1" });
|
|
1512
1522
|
server.registerTool(
|
|
1513
1523
|
"validate_iki",
|
|
1514
1524
|
{
|