@ikijs/mcp 0.19.1 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/dist/{chunk-RBQJ5FJA.mjs → chunk-EKGWFKU2.mjs} +289 -34
- package/dist/chunk-EKGWFKU2.mjs.map +1 -0
- package/dist/cli.js +296 -47
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +21 -3
- package/dist/index.d.ts +21 -3
- package/dist/index.js +296 -47
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +3 -3
- package/dist/chunk-RBQJ5FJA.mjs.map +0 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/tools.ts","../src/node-images.ts","../src/limits.ts","../src/compose.ts","../src/measure.ts","../src/measure-arms.ts","../src/measure-turn.ts","../src/compose-arms.ts","../src/cli.ts"],"sourcesContent":["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 and its expressions and motion clips (with the descriptions a host picks them by); 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, body, arm_L/arm_R, etc. optional; an arm needs the body) 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. A `nose` layer stays lossless on a second atlas page of its own, since the palette rims a soft-shaded nose's feather; the nose's own lossless page adds a content-dependent amount, since splitting it off also changes how page 0 re-quantizes without it; the result's `atlasBytes` sums both pages.\",\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 .passthrough()\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`) 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 leaves that part of the turn at the profile the rig defaults to. A passed `eyeShift` is fitted by the turn's amount and clamped to the room the art leaves the far eye — the face plate's edge, or the bangs' side strand over the far iris (the result's `turn.clamped` lists every clamped field, `turn.achieved` what the rig reaches, and `turn.strandOverlap` how much of a far iris the bangs still cover). A passed `silhouetteRatio` is clamped too, only on a face drawn without hair and with ear islands, where narrowing the head that far would no longer cover the far ear's slide. Any other passed target 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. A field not named here is refused the same way.\",\n ),\n style: z\n .object({\n turn: z.number().optional(),\n featureLead: z.number().optional(),\n hairFollow: z.number().optional(),\n outlineFollow: z.number().optional(),\n blink: z.number().optional(),\n sway: z.number().optional(),\n })\n .passthrough()\n .optional()\n .describe(\n \"Per-character tuning from the profile the rig defaults to: `turn` scales the whole head turn (plate, features, hair and the eyes' foreshortening; 0..3, 1 = the profile; ignored when `turnTargets.eyeShift` is given), `featureLead` how far the features lead the face plate (0..3, 1 = the profile), `hairFollow` the front hair's share of the face's turn (0..2, profile 1), `outlineFollow` its outer edge's share where the front hair draws the head's outline (0..2, profile 0: the outline holds), `blink` how far the upper lid comes down over the eye's height (0.1..1, profile 0.6), `sway` the hair sway amplitude (0..5, 1 = the profile). A value out of range, or a knob not named here, comes back as `INVALID: …`.\",\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, blush (one blush.png makes the blush_L/blush_R pair) and nose are optional — without a nose layer the head still turns on the rig's default profile, but it has no nose to lead the turn, and `auto_rig_from_layers` fits no turn to the art (`turnTargets` is inert, no `turn` report). One arm.png — the arm on the screen LEFT, drawn hanging with its shoulder at the top — makes both arms of a full body: arm_R takes it as drawn and arm_L mirrored. The arms are opt-in: without arm.png the compose is a bust's and `skipped` never lists them. arm.png needs body.png, and each arm is hung on the body's shoulder by default (see `layout`). The inline report carries the full-body checks too: a body whose feet a tall canvas's bottom cuts off, an arm without a body, and an arm whose shoulder cap does not reach under the torso's edge. A nose whose dense core is a speck — under a quarter of its trimmed part's width or height, such as a lone nostril mark or highlight — is sized and placed whole, and the inline report warns of it. A light mark drawn detached above the eye white, such as a double-eyelid crease, is dropped from the sclera (the iris's clip); dark strokes there stay lash ink. The eyewhite's dark lower lid — its line and lashes — becomes lash_lower_L/lash_lower_R, drawn over the iris; a white with none writes none and lists them in `skipped`.\",\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 does not write — one it skips, or an arm once arm.png is gone — 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, arm_L, arm_R, face, blush_L, blush_R, 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` is an integer in 1..1100 (the canvas width) and `h` in 1..canvasHeight; omit `h` to keep the part's own aspect, set it to stretch. The defaults of the face's features — blush, nose, mouth, mouth_open, eyes, irises, lashes, brows — are proportions of the face: an override of face.cx, face.cy or face.w carries them with it (scaled by the width; face.h stretches the face alone), while a feature's own override names canvas px. The nose is sized and placed by its dense core (its pixels at alpha >= 128, the drawing inside a soft nose's feather), not its whole part: `w`/`h` size the core, `cx` centres it, and a set `cy` centres its rows. A nose whose core is a speck — under a quarter of the trimmed part's width or height, such as a lone nostril mark or highlight — is sized and placed whole instead, and the report warns of it. Its `cy` defaults to unset, which lands the core's bottom row (the tip) 0.66 of the way from the eye row down to the mouth's, so the nose follows a retuned eye or mouth row. eye_L/lash_L and eye_R/lash_R are cut from one eyewhite into one frame, so each pair must land on the same frame — a pair set to land apart is rejected. lash_lower_L/lash_lower_R are cut from it too and have no key: they land on their eye's frame. arm_L/arm_R have no cx/cy/w defaults: an unset `w` is 0.4 of the placed body's width, and an unset `cx` or `cy` hangs the arm's shoulder pivot — the one auto_rig_from_layers turns it about — on the body box's shoulder corner on that axis: its left edge for arm_R, its right edge for arm_L, 0.12 of its height under its top. A set one centres the arm as for every other role.\",\n ),\n mirrorParts: z\n .array(z.string())\n .optional()\n .describe(\n \"Part files to flip left-right as they are read, e.g. `[\\\"eyewhite.png\\\"]`. The composer reads eyewhite.png as the eye on the screen LEFT (lash wing at the image's left end, lash-free tear duct at its right), brow.png as the brow on the screen RIGHT (thick head at the image's left end, tail at its right), blush.png as the blush on the screen LEFT (outer end, toward the face's edge, at the image's left end, inner end at its right), and arm.png as the arm on the screen LEFT (the character's right, hanging, its shoulder at the image's top); a part drawn the other way round is fixed here for free. It flips the source, so every role cut from it flips together and an eye's sclera and lash stay in one frame.\",\n ),\n canvasHeight: z\n .number()\n .optional()\n .describe(\n \"The canvas's height in px: an even integer in 1100..4096, default 1100 (a square bust canvas; at 1100 every output is byte-identical to leaving it out). The width stays 1100. The canvas grows downward: every default and every override keeps its canvas px from the top-left, so the head lands where it does on a bust and a full body gets room below. An odd height is refused — model space is centred on the canvas, so it would put the head on a half pixel — and it is checked before any part decodes.\",\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, a nose whose dense core is a speck of its crop, missing optional roles, a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge on its shoulder pivot's row). Every preview*.png is skipped. Use to re-check a layers dir without recomposing. Its nose check reads the composed file against its crop, which is what auto_rig_from_layers acts on. Compose's inline report does the same unless the composer found the source part's core a speck, which it reports instead — so a speck that resampling erased from the layer shows there and not here.\",\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","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 createLayerSetMeasurer,\n generateIkiFromLayerSet,\n parseLayerRoles,\n partIdsOfRole,\n LayerGeometryError,\n TurnTargetError,\n type IrisStrand,\n type LayerSetMeasurer,\n type AtlasAssignment,\n type AtlasLayout,\n type RigStyle,\n type TurnTargets,\n type TurnSolveReport,\n} from \"@ikijs/editor\";\nimport {\n decodePng,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_SIDE,\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 /** Each expression's id and the description a host picks it by. */\n expressions: { id: string; description: string }[];\n /** Each motion group's clip descriptions, by clip index. */\n motions: Record<string, string[]>;\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 expressions = (m.expressions ?? []).map((e) => ({\n id: e.id,\n description: e.description,\n }));\n\n const motions = Object.fromEntries(\n Object.entries(m.motions ?? {}).map(([group, clips]) => [\n group,\n clips.map((c) => c.description),\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 expressions,\n motions,\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.BodyAngleX,\n description:\n \"Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head.\",\n },\n {\n id: StandardParameter.BodyAngleY,\n description:\n \"Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows.\",\n },\n {\n id: StandardParameter.BodyAngleZ,\n description:\n \"Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head.\",\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.Cheek,\n description: \"Cheek blush strength (0 .. 1), raised by an expression.\",\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 id: StandardParameter.ArmLeft,\n description:\n \"Left shoulder, degrees; positive raises the arm outward (mirrored on the right).\",\n },\n {\n id: StandardParameter.ArmRight,\n description:\n \"Right shoulder, degrees; positive raises the arm outward (mirrored on the left).\",\n },\n {\n id: StandardParameter.ElbowLeft,\n description:\n \"Left elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right).\",\n },\n {\n id: StandardParameter.ElbowRight,\n description:\n \"Right elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left).\",\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 * A `nose` layer is left out of the quantized page, on a second, lossless\n * page of its own, because the palette rims a soft-shaded nose's feather. */\n quantizeColors?: number;\n /** Head-turn cues to fit the rig to, as `measure_turn_reference` reports\n * them. */\n turnTargets?: AutoRigTurnTargets;\n /** Per-character tuning from the profile's defaults (see\n * @ikijs/editor's `RigStyle`). */\n style?: RigStyle;\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 /** The atlas's embedded size: its data URI's length, summed over both\n * pages when a quantized rig puts the nose on a page of its own. */\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 /** Each side's iris and the `hair_front` run it would slide under on\n * the turn, as pixel edges on the row holding that iris's centre, in\n * model coordinates (`IrisStrand`: canvas x minus half the canvas\n * width) — measured whenever the layer set has `hair_front`, `iris_L`\n * and `iris_R`, and passed to the generator as `options.strandEdges`.\n * A run narrower than half that iris's painted width on the row is\n * hair detail, not a strand, and is skipped as if clear. A side is\n * absent only when its iris has no opaque pixel on that row, or when no\n * run it keeps covers the pixel on that side of the iris's centre or\n * lies outward of it; the whole field only when neither side has one. */\n strandEdges?: { left?: IrisStrand; right?: IrisStrand };\n /** The nose's dense core, canvas px — its pixels at alpha >= 128, not\n * grown — the box handed to the generator as the nose layer's\n * `denseCore` and, there, its turn landmark. Absent without a `nose`\n * layer, when the nose has no pixel at that threshold (painted wholly\n * translucent), or when its core is a speck of its crop\n * (`isSpeckCore`: a lone nostril mark or highlight); the crop stands\n * in for it in both cases. */\n noseCore?: { x: number; y: number; w: number; h: number };\n /** What the turn solve settled on — the cues the rig reaches, the\n * targets it had to cut down (`clamped`) and, per side whose far iris\n * the bangs' run still covers at some far stop, how much of it\n * (`strandOverlap`). Absent for a layer set with no nose, which solves\n * 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 role that keeps a lossless atlas page of its own under `quantizeColors`.\n * At 256 colours a soft nose's feather took the hair edge's lavender palette\n * entries and drew a rim around the nose; changing the dither, the effort, the\n * alpha floor or the alpha curve did not fix it. A lossless page for the nose\n * alone did, and the hero's model came to about 1.28 MB, against 3.18 MB with\n * the whole atlas lossless.\n */\nconst LOSSLESS_PAGE_ROLE = \"nose\";\n\n/** Pack `crops` onto one atlas page and render it — palette-quantized to\n * `quantizeColors` when that is set. A page over MAX_ATLAS_SIDE on either side\n * is refused before rendering, naming its widest (or tallest) crop. */\nasync function renderAtlasPage(\n crops: AtlasCrop[],\n quantizeColors: number | undefined,\n): Promise<{ crops: AtlasCrop[]; layout: AtlasLayout; dataUri: string }> {\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n );\n const over =\n layout.pageWidth > MAX_ATLAS_SIDE\n ? ({ side: \"width\", crop: \"widest\" } as const)\n : layout.pageHeight > MAX_ATLAS_SIDE\n ? ({ side: \"height\", crop: \"tallest\" } as const)\n : undefined;\n if (over !== undefined) {\n const crop = layout.placements.reduce((a, b) =>\n b[over.side] > a[over.side] ? b : a,\n );\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max side ${MAX_ATLAS_SIDE} (its ${over.crop} crop: \"${crop.id}\" ${crop.width}x${crop.height})`,\n );\n }\n const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);\n return { crops, layout, dataUri };\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 what @ikijs/editor's\n * `createLayerSetMeasurer` measures off the decoded layers (the head\n * half-width, `headEdges`, `strandEdges`, the face's `rowHalfWidths`, the face's\n * and hair layers' opaque runs and the nose's dense core, returned as\n * `noseCore`); what the solve settled on comes back in `turn`. Under\n * `quantizeColors` the nose is atlased alone on a second, lossless page, which\n * the palette would otherwise rim; `atlasBytes` sums both pages.\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 // Checked before the generator call spreads it: a spread turns null or an\n // array into {}, which would rig on the defaults instead of refusing.\n const turnTargets: unknown = input.turnTargets;\n if (turnTargets !== undefined) {\n if (\n typeof turnTargets !== \"object\" ||\n turnTargets === null ||\n Array.isArray(turnTargets)\n ) {\n throw new AutoRigInputError(\"turnTargets must be a plain object\");\n }\n // Excluded from AutoRigTurnTargets, but a JS caller can still pass one:\n // the half-width is measured off the layers below, so a caller's own is\n // refused rather than silently dropped.\n if ((turnTargets as TurnTargets).headHalfWidth !== undefined) {\n throw new AutoRigInputError(\n \"turnTargets.headHalfWidth is measured off the layers, not accepted as input\",\n );\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 // Measures each layer while its decoded pixels are live, keeping none of\n // them (see createLayerSetMeasurer). Created once the first layer gives the\n // canvas.\n let measurer: LayerSetMeasurer | undefined;\n const crops: AtlasCrop[] = [];\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 measurer = createLayerSetMeasurer({ width: canvasW, height: 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 // Created at i === 0 above.\n const layer = measurer!.add({ role, fileName, rgba: png.rgba });\n if (layer === null) {\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": layer is empty after alpha threshold`,\n );\n }\n const { bbox } = layer;\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\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 crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n // `layers` is non-empty (checked above), so the loop created the measurer.\n const measurement = measurer!.finish();\n const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;\n const { headEdges, strandEdges } = turnOptions;\n\n // The nose layer's own denseCore, for the result — undefined without a\n // `nose` layer, or when the measurer's denseCoreOf found no pixel at\n // ALPHA_OPAQUE or a speck of the crop.\n const noseCore = measurement.layers.find(\n (l) => l.role === \"nose\",\n )?.denseCore;\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 for the generator's two input errors, each a fact about the\n // request, not a bug: the turn solve, the one part of it that reads CALLER\n // input, throws TurnTargetError (a field that is not a number, a target\n // this layer set cannot reach); and art geometry the rig cannot build on\n // (a body's hips with no room under its pivots) throws LayerGeometryError.\n let turn: TurnSolveReport | undefined;\n let model: IkiModel;\n try {\n // The caller's fields cross as passed (a headHalfWidth was refused\n // above), so the generator refuses a misspelt one; the measured\n // headHalfWidth, when applied, is merged in after them.\n model = generateIkiFromLayerSet(\n measurement.layers,\n { width: canvasW, height: canvasH },\n {\n turnTargets: {\n ...input.turnTargets,\n ...turnOptions.turnTargets,\n },\n onTurnSolved: (report) => {\n turn = report;\n },\n ...(input.style === undefined ? {} : { style: input.style }),\n ...(headEdges === undefined ? {} : { headEdges }),\n ...(strandEdges === undefined ? {} : { strandEdges }),\n },\n );\n } catch (e) {\n if (!(e instanceof TurnTargetError || e instanceof LayerGeometryError)) {\n throw e;\n }\n throw new AutoRigInputError(e.message);\n }\n const doc = new EditorDocument(model);\n\n // Under quantizeColors the nose is page 1, alone and lossless (see\n // LOSSLESS_PAGE_ROLE), and page 0 every other crop; otherwise one page.\n const losslessCrop =\n quantizeColors === undefined\n ? undefined\n : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);\n const pages =\n losslessCrop === undefined\n ? [await renderAtlasPage(crops, quantizeColors)]\n : [\n await renderAtlasPage(\n crops.filter((c) => c !== losslessCrop),\n quantizeColors,\n ),\n await renderAtlasPage([losslessCrop], undefined),\n ];\n const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);\n if (atlasBytes > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n // Each crop's uv is on its own page, normalised to that page's size.\n const partTextureAssignments: AtlasAssignment[] = pages.flatMap(\n ({ crops: pageCrops, layout }) =>\n pageCrops.flatMap((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 const uv = uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n });\n // Every part of a role samples its crop: a forearm shares its arm's.\n return partIdsOfRole(crop.id).map((partId) => ({ partId, uv }));\n }),\n );\n\n // applyAtlas takes a single page: it sets every part's index to 0 and\n // remaps each mesh's uvs into its rect, which for the nose is already in\n // page 1's space — so the nose only needs its index, set on a clone\n // because getModel() hands back the document's live model, read-only.\n doc.applyAtlas({\n textures: [{ source: pages[0].dataUri }],\n partTextureAssignments,\n });\n let patched = doc.getModel();\n if (losslessCrop !== undefined) {\n patched = structuredClone(patched);\n patched.textures = pages.map((p) => ({ source: p.dataUri }));\n for (const partId of partIdsOfRole(losslessCrop.id)) {\n patched.parts.find((p) => p.id === partId)!.texture!.index = 1;\n }\n }\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(patched);\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,\n ...(headHalfWidth === undefined ? {} : { headHalfWidth }),\n headHalfWidthApplied,\n ...(headEdges === undefined ? {} : { headEdges }),\n ...(strandEdges === undefined ? {} : { strandEdges }),\n ...(noseCore === undefined ? {} : { noseCore }),\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 * 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. Soft\n * alpha is where it fails: a shaded nose's feather rims in borrowed palette\n * entries, so the auto-rig renders the nose on its own page without it.\n * Splitting it off also changes how page 0 re-quantizes, so the size effect\n * is content-dependent — on the playground hero the split model came to\n * 1.28MB, about the same as the all-quantized 1.29MB and well under the\n * 3.18MB lossless model.\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 per-side length (px) of each packed atlas page. WebGL2 guarantees only\n * 2048, but 4096 or more is near-universal; the engine refuses a texture over\n * the device's own limit on either side and leaves its parts untextured. Both\n * sides within it also bound a page's area at 4096². */\nexport const MAX_ATLAS_SIDE = 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. Layers\n * decode one at a time, so it bounds the request's total work, not its peak\n * memory. A full body's 21 layers at 1100 × 3650 decode 84.3 M px. */\nexport const MAX_TOTAL_PIXELS = 128 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model,\n * summed over its pages. Sized for the loop's lossless re-rig of a full body:\n * measured on bob's layers, a lossless atlas costs 1.56 data-URI bytes per\n * crop px (1,677,898 B over 1,075,888 px), and a full body on a canvas up to\n * 4096 tall crops to at most ~5 M px, about 8 MB. */\nexport const MAX_OUTPUT_BYTES = 12 * 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","/**\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, CANVAS wide and\n * `canvasHeight` tall (CANVAS unless a full body sets it) — the nose by its\n * dense core, the drawing inside a soft nose's feather.\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 { ALPHA_OPAQUE, detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { cropToBuffer, decodePng } from \"./node-images\";\nimport { measureDir, type MeasureReport, type NoseSpeck } from \"./measure\";\nimport { denseCoreOf, isSpeckCore } from \"./measure-turn\";\nimport { ARM_WIDTH, armPlacement } from \"./compose-arms\";\nimport {\n AutoRigInputError,\n MAX_CANVAS_DIM,\n resolveInputDir,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n/**\n * The layer canvas's width, and its default height, in px. The width is NOT an\n * input: the layout defaults below place parts against it (hair_front alone is\n * 660px wide, and sharp rejects a composite input larger than its\n * destination), so a different width would need its own layout. The height is\n * `canvasHeight`: the canvas grows downward from this square, so every default\n * keeps its place. The tuning surface is `layout` overrides.\n */\nexport const CANVAS = 1100;\n\n/** The layer canvas, in px: CANVAS wide and `canvasHeight` tall. */\ninterface Canvas {\n width: number;\n height: number;\n}\n\n/**\n * The canvas as error messages name it: \"1100\" when square, as every message\n * did before the height could grow, and \"1100x3650\" when tall.\n */\nfunction canvasName(canvas: Canvas): string {\n return canvas.width === canvas.height\n ? `${canvas.width}`\n : `${canvas.width}x${canvas.height}`;\n}\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; the defaults below are the hero bob's, 50px in a\n// 98px opening (0.51). A caller retunes eye size through\n// `layout.eye_L/eye_R.w` and MUST move `layout.iris_L/iris_R.w` with it to keep\n// that ratio.\nconst EYE_W = 98;\nconst IRIS_W = 50;\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, those in the TOP this-fraction are the upper lash,\n// an arc that folds DOWN over the eye on blink instead of a full ring that\n// shrinks in place; those below it are the lower lid's line and lashes.\nconst LASH_KEEP_FRACTION = 0.5;\n\n/** The alpha a part's trim cuts at: what it keeps is over this. */\nconst TRIM_THRESHOLD = 12;\n/** Of a part's kept pixels, the share under which a faint detached set is a stray speck. */\nconst STRAY_SPECK_FRACTION = 0.01;\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/**\n * The nose's layout. Its `w`, `h` and `cx` size and place its dense core\n * (`denseCoreOf`), not its whole trimmed part: a soft nose is mostly feather,\n * and sized by its extent it renders as a dot. A part with no core, or whose\n * core is a speck of it (`isSpeckCore`: a lone nostril mark or highlight,\n * which sized to `w` would blow the whole nose up), is sized and placed whole\n * instead, and the speck is warned about. Unlike every other role's, its `cy`\n * is optional. Set, it is the core's centre row; absent, the core's bottom row\n * — the tip — lands NOSE_TIP_AT of the way from the eye row down to the\n * mouth's.\n */\ninterface NoseLayout extends Omit<RoleLayout, \"cy\"> {\n cy?: number;\n}\n\n/**\n * An arm's layout. Its `cx`, `cy` and `w` are optional, each derived from the\n * placed body when unset (compose-arms.ts): `w` is ARM_WIDTH of the body's\n * width, and an unset `cx` or `cy` hangs the arm's shoulder pivot, the one\n * the rig turns it about, on the body box's shoulder corner on that axis. A\n * set one keeps every other role's meaning.\n */\nexport interface ArmLayout extends Omit<RoleLayout, \"cx\" | \"cy\" | \"w\"> {\n cx?: number;\n cy?: number;\n w?: number;\n}\n\n/** A box in a part's own px, origin top-left. */\ninterface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Where a nose with no `cy` puts its tip, as a fraction of the way from the\n * eye row down to the mouth's. Bob's: tip row 554 between eye row 475 and\n * mouth row 594 (79/119 ≈ 0.66), so the default rows land bob's nose where his\n * own layout placed it.\n */\nconst NOSE_TIP_AT = 0.66;\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 centred across the canvas, in its top CANVAS rows).\n// They are canvas px from the top-left, so a taller canvas only adds room\n// below them. The face, eyes, irises,\n// lashes, brows, nose and mouth are the hero bob's own tuning; bob wears his\n// blush at its default placement, picked on his face (below). The features'\n// defaults are proportions of the face: resolveLayout carries them with the\n// face's cx, cy and w. The hair and\n// the torso depend on the hairstyle and on how the torso is framed, so they are\n// older defaults every character retunes from the report. If the rendered model is misaligned, tune cx/cy/w through the\n// `layout` override and re-run — composing is cheap and the parts do not need\n// regenerating.\n//\n// eyeSide reminder: eye_L = character's LEFT eye = screen RIGHT (larger cx).\n// Which way a source faces is fixed by the mirror flags below, and \"left eye\"\n// cannot say it — it reads as the viewer's left or the character's. So in\n// image terms: eyewhite.png is the eye on the SCREEN LEFT, its lash wing (outer\n// corner) at the image's left end and its lash-free tear duct at the right;\n// brow.png is the brow on the SCREEN RIGHT, its thick head at the image's left\n// end and its tail at the right; blush.png is the blush on the SCREEN LEFT,\n// its outer end (toward the face's edge) at the image's left end and its\n// inner end (toward the nose) at the right; arm.png is the arm on the SCREEN\n// LEFT (the character's right), hanging, its shoulder at the image's top and\n// its hand at the bottom. A part drawn the other way round is flipped for\n// free with `mirrorParts`.\n// eye_* = the WHITE sclera (upper lashes recolored white) = the blink clip mask + fold.\n// iris_* = colored disc on top, clipped to the sclera, drives gaze.\n// lash_lower_* = the lower lid's dark line and lashes, ABOVE the iris (it\n// covers the iris's bottom edge, as the drawing does) and folding\n// with the white. Placed on the eye's frame, so it has no layout key.\n// lash_* = the dark upper lashes, a separate layer ABOVE the iris that folds\n// down to cover the closed-eye seam. eye_*, lash_lower_* and lash_* are\n// split from a single `eyewhite.png` (white almond + dark lashes) by\n// 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 bust's torso, cut off by a square canvas's bottom, so the character is\n // not a floating head; a full body on a tall canvas sets `layout.body`\n // itself. It rides the rig's `bodyWarp`, which the head hangs from.\n body: { src: \"body.png\", cx: 550, cy: 1017, w: 840, optional: true },\n // The arms, one part for both: arm_R (screen left) takes arm.png as drawn\n // and arm_L mirrors it, like the blush. They draw over the body and under\n // the face. They have no cx/cy/w defaults: each is derived from the placed\n // body (ArmLayout). OPTIONAL and opt-in: a parts dir without arm.png\n // composes as a bust does, and `skipped` never lists them.\n arm_L: { src: \"arm.png\", optional: true, mirror: true },\n arm_R: { src: \"arm.png\", optional: true, mirror: false },\n // The face is drawn without a neck, so its box is the skull and centres\n // above the eye row (bob's skull at 437 against his eyes' 475).\n face: { src: \"face.png\", cx: 550, cy: 437, w: 400 },\n // The cheek blush, one part for both cheeks: blush_R (screen left) takes it\n // as drawn and blush_L mirrors it, like the eyewhite. It draws over the face\n // and under the nose. Its box sits below each eye, centred 5 px outside the\n // eye's centre and 55 px under its row, above the nose tip: on bob's face,\n // which narrows fast below the eye row, a 2:1 blush there stays on the\n // cheek through the turn, where one 26 px further out reached the ears.\n // OPTIONAL: a parts dir without it composes, and nothing reports it missing.\n blush_L: { src: \"blush.png\", cx: 641, cy: 530, w: 56, optional: true, mirror: true }, // prettier-ignore\n blush_R: { src: \"blush.png\", cx: 459, cy: 530, w: 56, optional: true, mirror: false }, // prettier-ignore\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. `w` is the\n // width of its dense core, and it has no `cy`: its row comes from the tip\n // rule (NOSE_TIP_AT), between the eyes and the mouth, so it follows them\n // when they are retuned. OPTIONAL: a parts dir without it composes.\n nose: { src: \"nose.png\", cx: 550, w: 20, optional: true },\n mouth: { src: \"mouth.png\", cx: 550, cy: 594, w: 76 },\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: 596,\n w: 76,\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: 636, cy: 475, w: EYE_W, mirror: true, noTrim: true }, // prettier-ignore\n eye_R: { src: \"eyewhite_sclera.png\", cx: 464, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n // A little under the white's centre and toward the nose, as bob's sits.\n iris_L: { src: \"iris.png\", cx: 631, cy: 480, w: IRIS_W, mirror: false },\n iris_R: { src: \"iris.png\", cx: 469, cy: 480, w: IRIS_W, mirror: false },\n lash_L: {\n src: \"eyewhite_lash.png\",\n cx: 636,\n cy: 475,\n w: EYE_W,\n mirror: true,\n noTrim: true,\n },\n lash_R: { src: \"eyewhite_lash.png\", cx: 464, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n brow_L: { src: \"brow.png\", cx: 645, cy: 405, w: 105, mirror: false },\n brow_R: { src: \"brow.png\", cx: 455, cy: 405, w: 105, mirror: true },\n hair_front: { src: \"hair_front.png\", cx: 550, cy: 425, w: 660 },\n} satisfies Record<string, RoleLayout | NoseLayout | ArmLayout>;\n\nexport type Role = keyof typeof DEFAULT_LAYOUT;\n\n/** The lower lash of each eye, and the eye whose placement it takes. */\nconst LOWER_LASH = { lash_lower_L: \"eye_L\", lash_lower_R: \"eye_R\" } as const;\n/** The eyewhite's lower lid, split in memory like the sclera and lash. */\nconst LOWER_LASH_SRC = \"eyewhite_lash_lower.png\";\n\n/** A role the composer writes a layer for. */\nexport type LayerRole = Role | keyof typeof LOWER_LASH;\n\n/** The arm roles, placed off the body (ArmLayout). */\ntype ArmRole = \"arm_L\" | \"arm_R\";\n\n/**\n * The merged layout, typed so a default other than the nose's and the arms'\n * that drops its `cy` fails to compile: `resolveLayout` builds it from\n * DEFAULT_LAYOUT.\n */\ntype ResolvedLayout = Record<Exclude<Role, \"nose\" | ArmRole>, RoleLayout> & {\n nose: NoseLayout;\n} & Record<ArmRole, ArmLayout>;\n\n/**\n * Draw order (back -> front): the roles of @ikijs/editor ROLE_TABLE the\n * composer writes, in its order — a test holds it to that subsequence.\n */\nexport const ORDER: LayerRole[] = [\n \"hair_back\",\n \"body\",\n \"arm_L\",\n \"arm_R\",\n \"face\",\n \"blush_L\",\n \"blush_R\",\n \"nose\",\n \"mouth\",\n \"mouth_open\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"lash_lower_L\",\n \"lash_lower_R\",\n \"lash_L\",\n \"lash_R\",\n \"brow_L\",\n \"brow_R\",\n \"hair_front\",\n];\n\n/**\n * The part files a parts dir holds: every source the layout reads from disk,\n * and the eyewhite the eye pair is split from in memory.\n */\nconst PART_FILES = [\n ...new Set(\n Object.values(DEFAULT_LAYOUT)\n .map((cfg) => cfg.src)\n .filter((src) => !src.startsWith(\"eyewhite_\")),\n ),\n EYEWHITE_SRC,\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: the layer an earlier run wrote for any role\n * this run does not write — a skipped role, or an arm once arm.png is gone\n * — is removed rather than left for the next tool to pick up.\n */\n outDir: string;\n layout?: LayoutOverride;\n /**\n * Part files to flip left-right as they are read, e.g. `[\"eyewhite.png\"]`\n * for an eye drawn facing the other way. It flips the SOURCE, so every role\n * cut from it flips together — the eye pair's sclera and lash stay in one\n * frame, which a per-role flag would leave to the caller to keep in sync.\n */\n mirrorParts?: string[];\n /**\n * The canvas's height in px: an even integer in CANVAS..MAX_CANVAS_DIM,\n * CANVAS (a square bust canvas) when omitted, and every output at CANVAS is\n * byte-identical to an omitted one. The width stays CANVAS. The canvas grows\n * downward: every default and every override keeps its canvas px from the\n * top-left, so the head lands where it does on a bust and a full body gets\n * room below. Model space is centred on the canvas, so an odd height, which\n * would put the head on a half pixel, is refused.\n */\n canvasHeight?: number;\n}\n\nexport interface ComposedLayer {\n role: LayerRole;\n path: string;\n /** Size of the placed part itself (the file is always CANVAS x the canvas\n * height). */\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 /**\n * Roles whose optional part was absent from the parts dir, and the lower\n * lashes when the eyewhite draws no dark lower lid. The arms are opt-in\n * and never listed: a parts dir without arm.png composes as a bust does,\n * though an earlier compose's arm layers are still removed.\n */\n skipped: LayerRole[];\n preview: string;\n measure: MeasureReport;\n }\n | { ok: false; error: string };\n\n/**\n * The roles drawn on the face, but the nose (resolveLayout places it on its\n * own). Their defaults are placed relative to the face's: a layout that moves\n * or scales the face carries them with it.\n */\nconst FACE_FEATURES = [\n \"blush_L\",\n \"blush_R\",\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] as const satisfies readonly Exclude<Role, \"nose\">[];\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 or height fails fast,\n * path-qualified, before any decode. `w` is capped at the canvas's width and\n * `h` at its height, so a part sized whole can never exceed the canvas width\n * (a nose, sized by its core, is checked in partBuffer); `cx`/`cy` are\n * unbounded here because a part may legitimately hang off an edge —\n * assertOnCanvas() rejects the one that lands nowhere on it.\n *\n * The face's override applies first. Each feature's default is then moved\n * with the face's centre and scaled by its width against the default face's,\n * so the defaults are proportions of the face; a feature's own override still\n * names canvas px.\n */\nfunction resolveLayout(\n overrides: LayoutOverride | undefined,\n canvas: Canvas,\n): ResolvedLayout {\n const resolved: ResolvedLayout = { ...DEFAULT_LAYOUT };\n if (overrides === undefined) return resolved;\n const sets = new Map<\n Role,\n { cx?: number; cy?: number; w?: number; h?: number }\n >();\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 // Only the fields the override sets: spread over the entry, an explicit\n // undefined would erase the default it leaves alone.\n const set: { cx?: number; cy?: number; w?: number; h?: number } = {};\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 set[field] = value;\n }\n for (const field of [\"w\", \"h\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n const max = field === \"w\" ? canvas.width : canvas.height;\n if (!Number.isInteger(value) || value < 1 || value > max) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be an integer in 1..${max}, got ${String(value)}`,\n );\n }\n set[field] = value;\n }\n sets.set(role as Role, set);\n }\n const face = { ...resolved.face, ...sets.get(\"face\") };\n resolved.face = face;\n const base = DEFAULT_LAYOUT.face;\n const scale = face.w / base.w;\n const x = (cx: number) => face.cx + (cx - base.cx) * scale;\n const w = (width: number) => Math.max(1, Math.round(width * scale));\n for (const role of FACE_FEATURES) {\n const d = DEFAULT_LAYOUT[role];\n const cy = face.cy + (d.cy - base.cy) * scale;\n resolved[role] = { ...d, cx: x(d.cx), cy, w: w(d.w), ...sets.get(role) };\n }\n // The nose has no default cy (the tip rule places it, off the eye and\n // mouth rows above), so it merges on its own.\n const nose = DEFAULT_LAYOUT.nose;\n resolved.nose = {\n ...nose,\n cx: x(nose.cx),\n w: w(nose.w),\n ...sets.get(\"nose\"),\n };\n for (const [role, set] of sets) {\n if (role === \"face\" || role === \"nose\") continue;\n if ((FACE_FEATURES as readonly Role[]).includes(role)) continue;\n mergeRole(resolved, role, set);\n }\n return resolved;\n}\n\n/**\n * Merge an override's set fields onto a role's resolved entry. Generic over\n * the role so one statement types for every kind of entry, the arms' among\n * them, whose cx/cy/w may stay unset.\n */\nfunction mergeRole<R extends Role>(\n resolved: ResolvedLayout,\n role: R,\n set: { cx?: number; cy?: number; w?: number; h?: number },\n): void {\n resolved[role] = { ...resolved[role], ...set };\n}\n\n/**\n * Input boundary for `canvasHeight`: an even integer in CANVAS..MAX_CANVAS_DIM,\n * CANVAS when omitted. Model space is centred on the canvas, so an odd height\n * would put the head on a half pixel.\n */\nfunction resolveCanvasHeight(value: number | undefined): number {\n if (value === undefined) return CANVAS;\n if (\n !Number.isInteger(value) ||\n value % 2 !== 0 ||\n value < CANVAS ||\n value > MAX_CANVAS_DIM\n ) {\n throw new AutoRigInputError(\n `canvasHeight must be an even integer in ${CANVAS}..${MAX_CANVAS_DIM}, got ${String(value)}`,\n );\n }\n return value;\n}\n\n/**\n * Input boundary for `mirrorParts`: a name that is not a part file (a typo, or\n * a role such as `eye_L`) would otherwise flip nothing and read as success.\n */\nfunction resolveMirrorParts(names: string[] | undefined): Set<string> {\n const mirrored = new Set<string>();\n for (const [i, name] of (names ?? []).entries()) {\n if (!PART_FILES.includes(name)) {\n throw new AutoRigInputError(\n `mirrorParts[${i}]: unknown part ${JSON.stringify(name)} — expected one of ${PART_FILES.join(\", \")}`,\n );\n }\n mirrored.add(name);\n }\n return mirrored;\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/** A PNG part's dense core (`null` when no pixel reaches the core's alpha)\n * and its own bounds, both in its own px. */\nasync function coreAndBoundsOf(\n png: Buffer,\n): Promise<{ core: Box | null; bounds: Box }> {\n const { data, info } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return {\n core: denseCoreOf(data, info.width, info.height),\n bounds: { x: 0, y: 0, w: info.width, h: info.height },\n };\n}\n\n/** Whether a part keeps a pixel the auto-rig counts as coverage. */\nasync function hasCoverage(png: Buffer): Promise<boolean> {\n const { data, info } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return scanAlphaBbox(data, info.width, info.height) !== null;\n}\n\n/** What a nose part's layout sizes, decided on the trimmed source part. */\ninterface NoseSizing {\n /** The box layout `w`/`h` size, in the trimmed source part's px (not the\n * resized part's). */\n box: Box;\n /** The whole part stood in for the core: it has none, or it is a speck. */\n whole: boolean;\n /** The core's and the part's sizes when a speck was the reason. */\n speck?: NoseSpeck;\n}\n\n/**\n * What a nose part's layout sizes: its dense core, in its own px — or its own\n * bounds, so it is sized and placed whole, when no pixel reaches the core's\n * alpha (a nose painted wholly translucent) or the core is a speck of those\n * bounds (`isSpeckCore`).\n */\nasync function noseSizingOf(png: Buffer): Promise<NoseSizing> {\n const { core, bounds } = await coreAndBoundsOf(png);\n if (core === null) return { box: bounds, whole: true };\n if (isSpeckCore(core, bounds)) {\n return {\n box: bounds,\n whole: true,\n speck: {\n core: { w: core.w, h: core.h },\n part: { w: bounds.w, h: bounds.h },\n },\n };\n }\n return { box: core, whole: false };\n}\n\n/**\n * Trim/mirror a part and resize it to its layout width. The nose is resized so\n * its dense core, not its whole part, comes out `w` wide (and `h` tall when\n * set), unless its whole part stood in for the core. Either way the nose's\n * sizing decision (`noseSizingOf`) always comes back as `nose`, and no other\n * role has one. `inMemory` carries the eye pair's two split buffers; every\n * other role is read from the parts dir. `flipSource` is a `mirrorParts` entry\n * for the file the role is cut from.\n * Missing optional part -> null; missing required part -> AutoRigInputError.\n */\nasync function partBuffer(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\">,\n partsDir: string,\n inMemory: Buffer | undefined,\n flipSource: boolean,\n canvas: Canvas,\n): Promise<{ buf: Buffer; w: number; h: number; nose?: NoseSizing } | 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 // An optional role's part may be absent from the parts dir; the\n // 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\n // bbox, less any stray speck beside the drawing.\n if (!cfg.noTrim) {\n // The rest of the pipeline reads this trimmed raw, so the source is\n // decoded and trimmed once. Only file sources are trimmed, and they are\n // raw already, so a part with no stray speck composes byte-identically.\n const kept = await img\n .trim({ threshold: TRIM_THRESHOLD })\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const { width: keptW, height: keptH } = kept.info;\n img = sharp(kept.data, {\n raw: { width: keptW, height: keptH, channels: 4 },\n });\n const box = boxWithoutStraySpecks(kept.data, keptW, keptH);\n if (box !== null) img = img.extract(box);\n }\n // A flipped source under a mirrored role cancels out. sharp's flop() sets a\n // flag rather than toggling it, so the two cannot simply be applied in turn.\n if ((cfg.mirror ?? false) !== flipSource) img = img.flop();\n // Materialise the trimmed part BEFORE resizing: its size is bounded by the\n // source decode limit, so the size 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 const { width: trimmedW, height: trimmedH } = trimmed.info;\n // What `w`/`h` size: the nose's dense core, measured on the trimmed, flipped\n // part — the whole part scales with it, feather and all — or that whole\n // part when it has no core or the core is a speck, and every other role's\n // whole part.\n const nose = role === \"nose\" ? await noseSizingOf(trimmed.data) : undefined;\n const sized = nose?.box ?? { x: 0, y: 0, w: trimmedW, h: trimmedH };\n const width = Math.round((trimmedW * cfg.w) / sized.w);\n const height =\n cfg.h === undefined\n ? Math.round((trimmedH * width) / trimmedW)\n : Math.round((trimmedH * cfg.h) / sized.h);\n // resolveLayout bounds w and an explicit h, so for a part sized whole only\n // the aspect-derived height can run past the canvas; a nose sized by its\n // core can overrun either dimension.\n if (width > canvas.width || height > canvas.height) {\n const field = width > canvas.width || cfg.h === undefined ? \"w\" : \"h\";\n throw new AutoRigInputError(\n `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${canvasName(canvas)} canvas`,\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(cfg.h === undefined ? { width } : { width, height, fit: \"fill\" })\n .png()\n .toBuffer({ resolveWithObject: true });\n return {\n buf: resized.data,\n w: resized.info.width,\n h: resized.info.height,\n nose,\n };\n}\n\n/**\n * Refuse a placed part that lands nowhere on the canvas. Running off an edge is\n * legitimate — a bust's `body` is meant to be cut off by the canvas bottom — so\n * the test is INTERSECTION, not containment. A part that misses the canvas\n * entirely 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 assertOnCanvas(\n source: string,\n w: number,\n h: number,\n left: number,\n top: number,\n canvas: Canvas,\n): void {\n if (\n left + w <= 0 ||\n top + h <= 0 ||\n left >= canvas.width ||\n top >= canvas.height\n ) {\n throw new AutoRigInputError(\n `${source}: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${canvasName(canvas)} canvas`,\n );\n }\n}\n\n/** Where a part lands, centred on its layout cx/cy. The nose has its own. */\nfunction placement(\n role: Exclude<Role, \"nose\" | ArmRole>,\n cfg: RoleLayout,\n w: number,\n h: number,\n canvas: Canvas,\n) {\n const left = Math.round(cfg.cx - w / 2);\n const top = Math.round(cfg.cy - h / 2);\n assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);\n return { left, top };\n}\n\n/**\n * Where the nose lands: by the box it was sized by (`noseSizingOf`), in the\n * resized part's px — its dense core, or its whole bounds when those stood in.\n * `cx` centres the box's columns. A set `cy` centres its rows; absent, its\n * bottom row — the tip, the last row index at alpha ≥ 128 — lands on\n * round(E + NOSE_TIP_AT·(M − E)), E the eyes' mean row and M the mouth's. A\n * box's centre is `x + w/2`, as placement() takes it: pixel x covers\n * [x, x + 1).\n */\nfunction nosePlacement(\n layout: ResolvedLayout,\n box: Box,\n w: number,\n h: number,\n canvas: Canvas,\n) {\n const { cx, cy } = layout.nose;\n const left = Math.round(cx - (box.x + box.w / 2));\n let top: number;\n if (cy !== undefined) {\n top = Math.round(cy - (box.y + box.h / 2));\n } else {\n const eyeRow = (layout.eye_L.cy + layout.eye_R.cy) / 2;\n const tipRow = Math.round(\n eyeRow + NOSE_TIP_AT * (layout.mouth.cy - eyeRow),\n );\n top = tipRow - (box.y + box.h - 1);\n }\n assertOnCanvas(\n cy !== undefined\n ? \"layout.nose.cx/cy\"\n : \"layout.nose.cx/cy (cy unset: its tip row comes from layout.eye_L/eye_R/mouth.cy)\",\n w,\n h,\n left,\n top,\n canvas,\n );\n return { left, top };\n}\n\nfunction blankCanvas(canvas: Canvas) {\n return sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n });\n}\n\n/** Luma (0..255) of the RGBA pixel at byte offset `i`. */\nfunction luma(rgba: Buffer, i: number): number {\n return 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];\n}\n\n/**\n * The box of a trimmed part without its stray specks, or null when no stray\n * speck lies outside its drawing. The part's kept pixels (alpha over\n * TRIM_THRESHOLD, the trim's own cut) form 8-connected sets; a stray speck is\n * a set that never reaches ALPHA_OPAQUE and holds under STRAY_SPECK_FRACTION of\n * them, the residue a background removal leaves beside a drawing. Kept, one\n * such speck widened a generated body's box by 70 px on one side and placed\n * the body 32 px off its centre. A drawn stroke reaches ALPHA_OPAQUE, so a\n * detached wisp or strand is never dropped, and a part painted wholly under\n * it (a soft blush) drops nothing.\n */\nfunction boxWithoutStraySpecks(\n rgba: Buffer,\n W: number,\n H: number,\n): { left: number; top: number; width: number; height: number } | null {\n const n = W * H;\n // The share is of the whole part, so count it before any set is judged.\n let kept = 0;\n for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] > TRIM_THRESHOLD) kept++;\n // Each set is judged as its fill ends and only its box is kept, so memory\n // is a byte per pixel plus a stack grown to the deepest fill, not a label\n // per pixel and a record per set. A pixel is marked as it is pushed, so the\n // stack never outgrows the image.\n const visited = new Uint8Array(n);\n let stack = new Int32Array(1024);\n // [left, top, right, bottom] of the drawing's sets and of the stray ones.\n const drawing = [W, H, -1, -1];\n const strays = [W, H, -1, -1];\n let anyOpaque = false;\n for (let start = 0; start < n; start++) {\n if (visited[start] || rgba[start * 4 + 3] <= TRIM_THRESHOLD) continue;\n let setLeft = W;\n let setTop = H;\n let setRight = -1;\n let setBottom = -1;\n let size = 0;\n let opaque = false;\n let depth = 0;\n visited[start] = 1;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n if (rgba[p * 4 + 3] >= ALPHA_OPAQUE) opaque = true;\n const px = p % W;\n const py = (p - px) / W;\n setLeft = Math.min(setLeft, px);\n setTop = Math.min(setTop, py);\n setRight = Math.max(setRight, px);\n setBottom = Math.max(setBottom, py);\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n const q = y * W + x;\n if (!visited[q] && rgba[q * 4 + 3] > TRIM_THRESHOLD) {\n visited[q] = 1;\n if (depth === stack.length) {\n const grown = new Int32Array(Math.min(n, stack.length * 2));\n grown.set(stack);\n stack = grown;\n }\n stack[depth++] = q;\n }\n }\n }\n }\n anyOpaque ||= opaque;\n const into =\n !opaque && size < kept * STRAY_SPECK_FRACTION ? strays : drawing;\n into[0] = Math.min(into[0], setLeft);\n into[1] = Math.min(into[1], setTop);\n into[2] = Math.max(into[2], setRight);\n into[3] = Math.max(into[3], setBottom);\n }\n if (!anyOpaque || strays[2] < 0) return null;\n const [left, top, right, bottom] = drawing;\n // A set's box reaches past the drawing's only where one of its pixels does,\n // and a speck inside the drawing's box moves nothing, so it is left be.\n if (\n strays[0] >= left &&\n strays[1] >= top &&\n strays[2] <= right &&\n strays[3] <= bottom\n )\n return null;\n return { left, top, width: right - left + 1, height: bottom - top + 1 };\n}\n\n/**\n * The eyewhite's light ink drawn detached above its white, as a row-major\n * mask (1 = detached). Light ink is non-transparent at luma EYE_LASH_LUMA or\n * over. Its sets are 8-connected through visibly painted pixels only (alpha\n * ALPHA_OPAQUE or over), so a faint antialiased pixel between a crease and\n * the white does not join them. Each fainter pixel is fringe of the nearest\n * painted set it reaches through faint pixels whose alpha never rises on the\n * way (ties go to the set met first in row-major order, the higher one).\n * Antialiasing fades away from what it edges, so a translucent stroke past a\n * fainter halo does not become the fringe of the set the halo edges. Faint\n * ink that no painted set reaches this way forms sets of its own. So does a\n * noisy faint pixel brighter than every claimed neighbour and touching no\n * painted pixel: above the white's top, it is dropped. The white is the\n * largest painted set. Another set is detached above it when each of its own\n * pixels, fringe aside, lies above the white's topmost painted pixel in its\n * column, or, past either end of the white, above the top of that end's\n * column; it goes with its fringe. A crease often runs on past the eye's\n * corners, and judged only over the white, one pixel out there would keep\n * the whole crease. A shade painted on the white touches it, so it is part\n * of the white; a mark below the white, or beside an end and level with it,\n * is left.\n */\nfunction detachedAboveWhite(rgba: Buffer, W: number, H: number): Uint8Array {\n const n = W * H;\n // 2 = painted light ink, 1 = fainter light ink, 0 = neither.\n const ink = new Uint8Array(n);\n for (let p = 0; p < n; p++) {\n const alpha = rgba[p * 4 + 3];\n if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)\n ink[p] = alpha >= ALPHA_OPAQUE ? 2 : 1;\n }\n const label = new Int32Array(n).fill(-1);\n // A pixel is labelled as it is pushed, so it is pushed once and neither the\n // flood fill's stack nor the fringe's queue outgrows the image.\n const stack = new Int32Array(n);\n const near = (p: number, visit: (q: number) => void) => {\n const px = p % W;\n const py = (p - px) / W;\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n visit(y * W + x);\n }\n }\n };\n const sizes: number[] = [];\n const fill = (start: number) => {\n const id = sizes.length;\n let size = 0;\n let depth = 0;\n label[start] = id;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n near(p, (q) => {\n if (ink[q] === ink[start] && label[q] === -1) {\n label[q] = id;\n stack[depth++] = q;\n }\n });\n }\n sizes.push(size);\n };\n for (let p = 0; p < n; p++) if (ink[p] === 2 && label[p] === -1) fill(p);\n const paintedSets = sizes.length;\n // The fringe: breadth-first from every painted pixel at once, each faint\n // pixel no more opaque than the one before taking the set that reaches it\n // first.\n let head = 0;\n let tail = 0;\n for (let p = 0; p < n; p++) if (ink[p] === 2) stack[tail++] = p;\n while (head < tail) {\n const p = stack[head++];\n near(p, (q) => {\n if (\n ink[q] === 1 &&\n label[q] === -1 &&\n rgba[q * 4 + 3] <= rgba[p * 4 + 3]\n ) {\n label[q] = label[p];\n stack[tail++] = q;\n }\n });\n }\n for (let p = 0; p < n; p++) if (ink[p] === 1 && label[p] === -1) fill(p);\n\n const detached = new Uint8Array(n);\n if (paintedSets === 0 || sizes.length < 2) return detached;\n let white = 0;\n for (let id = 1; id < paintedSets; id++) {\n if (sizes[id] > sizes[white]) white = id;\n }\n // A set's own pixels: a painted set's painted ones, a faint set's all.\n const own = (p: number) => ink[p] === 2 || label[p] >= paintedSets;\n // The white's topmost painted row per column (the scan is row-major, so\n // the first pixel met is the top).\n const whiteTop = new Int32Array(W).fill(-1);\n for (let p = 0; p < n; p++) {\n const x = p % W;\n if (label[p] === white && own(p) && whiteTop[x] === -1)\n whiteTop[x] = (p - x) / W;\n }\n // An 8-connected set covers one unbroken run of columns, so every column\n // the white misses lies past one of its ends and takes that end's top.\n let first = 0;\n while (whiteTop[first] === -1) first++;\n let last = W - 1;\n while (whiteTop[last] === -1) last--;\n whiteTop.fill(whiteTop[first], 0, first);\n whiteTop.fill(whiteTop[last], last + 1);\n const above = new Uint8Array(sizes.length).fill(1);\n for (let p = 0; p < n; p++) {\n const id = label[p];\n if (id === -1 || id === white || !own(p)) continue;\n const x = p % W;\n if ((p - x) / W >= whiteTop[x]) above[id] = 0;\n }\n for (let p = 0; p < n; p++) {\n const id = label[p];\n if (id !== -1 && id !== white && above[id]) detached[p] = 1;\n }\n return detached;\n}\n\n/**\n * Split eyewhite.png (white almond + dark lashes) into a sclera (the upper\n * lash recolored to white; the whole drawing's alpha = the blink clip-mask\n * shape), a dark UPPER-lash layer and a dark LOWER-lid layer. All are cropped\n * to the SAME eye bbox so they stay aligned (consumed with noTrim): the lash\n * arc keeps its position at the top of the sclera, so on blink it folds DOWN\n * over the eye rather than the eye shrinking in place.\n *\n * The lower lid's dark line and lashes stay in the sclera as drawn and are\n * copied into their own layer, which draws over the iris. Recolored white they\n * would show as white flicks wherever a lash hangs below the white, and left\n * in the sclera alone the iris would paint over the line. The sclera keeps\n * them so its alpha, which the rig measures the eye by, is the drawing's.\n * `lashLower` is null when the eyewhite draws no dark pixel below the upper\n * lash's fraction.\n *\n * A light mark drawn detached above the white, such as a double-eyelid crease,\n * is dropped from the sclera (`detachedAboveWhite`). The sclera is the iris's\n * clip, and at half blink the fold carries such a mark down into the iris's\n * path. The frame is still the source's alpha bbox, crease and all, so the\n * layout places the pair where it did before.\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; lashLower: Buffer | null }> {\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 // Dark pixels above this row are the upper lash; below it, the lower lid.\n const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);\n const detached = detachedAboveWhite(data, W, H);\n\n const sclera = Buffer.from(data);\n const lash = Buffer.from(data);\n const lashLower = Buffer.from(data);\n let lowerInk = false;\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 isDark = data[i + 3] > 0 && luma(data, i) < EYE_LASH_LUMA;\n const upper = y <= lashCutoffY;\n if (isDark && upper) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255; // dark -> white\n if (detached[y * W + x]) sclera[i + 3] = 0;\n if (!(isDark && upper)) lash[i + 3] = 0;\n if (isDark && !upper) lowerInk = true;\n else lashLower[i + 3] = 0;\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 lashLower: lowerInk ? await cropToBuffer(lashLower, W, H, region) : null,\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 // Before anything decodes, like every other input check.\n const canvas: Canvas = {\n width: CANVAS,\n height: resolveCanvasHeight(input.canvasHeight),\n };\n const layout = resolveLayout(input.layout, canvas);\n const mirrored = resolveMirrorParts(input.mirrorParts);\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 if (split.lashLower !== null) {\n splitSources.set(LOWER_LASH_SRC, split.lashLower);\n }\n\n // Place every role before writing any: a rejected placement must leave\n // outDir as the last compose left it, not half overwritten.\n const placed: {\n role: LayerRole;\n part: { buf: Buffer; w: number; h: number };\n left: number;\n top: number;\n }[] = [];\n const skipped: LayerRole[] = [];\n // Compose's verdict on the nose's source part when its core was a speck,\n // for the report; otherwise the report judges the composed nose layer.\n let noseSpeck: NoseSpeck | undefined;\n for (const role of ORDER) {\n // A lower lash is placed by its eye's layout, on the sclera's frame.\n const lower = role === \"lash_lower_L\" || role === \"lash_lower_R\";\n const key: Role = lower ? LOWER_LASH[role] : role;\n if (lower && split.lashLower === null) {\n skipped.push(role);\n continue;\n }\n if (key === \"arm_L\" || key === \"arm_R\") {\n const arm = layout[key];\n // Arms are opt-in: a parts dir without arm.png composes as a bust\n // does, the arms neither placed nor listed in `skipped`.\n if (!fs.existsSync(path.join(partsDir, arm.src))) continue;\n const body = placed.find((p) => p.role === \"body\");\n if (body === undefined) {\n throw new AutoRigInputError(\n \"arm.png: an arm needs body.png — the composer hangs each arm on the body's shoulder, and auto_rig_from_layers hangs it from the body\",\n );\n }\n const w = arm.w ?? Math.max(1, Math.round(ARM_WIDTH * body.part.w));\n // Never null: the part is there, checked above.\n const part = (await partBuffer(\n role,\n { ...arm, w },\n partsDir,\n undefined,\n mirrored.has(arm.src),\n canvas,\n ))!;\n const { left, top } = await armPlacement(key, arm, part, {\n left: body.left,\n top: body.top,\n w: body.part.w,\n h: body.part.h,\n });\n const unset = ([\"cx\", \"cy\"] as const).filter(\n (field) => arm[field] === undefined,\n );\n assertOnCanvas(\n unset.length === 0\n ? `layout.${key}.cx/cy`\n : `layout.${key}.cx/cy (${unset.join(\"/\")} unset: its shoulder pivot hangs on the shoulder corner of layout.body's box)`,\n part.w,\n part.h,\n left,\n top,\n canvas,\n );\n placed.push({ role, part, left, top });\n continue;\n }\n const cfg = lower ? { ...layout[key], src: LOWER_LASH_SRC } : layout[key];\n const inMemory = splitSources.get(cfg.src);\n const part = await partBuffer(\n role,\n cfg,\n partsDir,\n inMemory,\n // The split halves are cut from eyewhite.png, the file a caller names.\n mirrored.has(inMemory === undefined ? cfg.src : EYEWHITE_SRC),\n canvas,\n );\n // A lower lid too faint for the alpha the rig reads coverage at, or\n // that the resize erased, would be a layer it refuses as empty.\n if (part === null || (lower && !(await hasCoverage(part.buf)))) {\n skipped.push(role);\n continue;\n }\n // The nose is placed by the box it was sized by. A whole part that stood\n // in is placed by the resized part's own bounds. A core is measured\n // again on the resized part rather than scaled, since resampling moves\n // its edges and the tip rule lands its exact bottom row — and is not\n // judged again here: the source part's verdict decided how it was sized.\n let left: number;\n let top: number;\n if (key === \"nose\") {\n noseSpeck = part.nose?.speck;\n const { core, bounds } = await coreAndBoundsOf(part.buf);\n const box = part.nose?.whole ? bounds : (core ?? bounds);\n ({ left, top } = nosePlacement(layout, box, part.w, part.h, canvas));\n } else {\n ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));\n }\n // The eye pair's halves are cut from one eyewhite into one frame. Set\n // apart, the blink fold tears — and a lash narrowed inside its sclera\n // still lies on it and inks its top row, so nothing in the composed\n // layers would show it. Compared as placed, not as set: an h equal to\n // the one the aspect gives lands on the same frame as leaving it unset.\n if (role === \"lash_L\" || role === \"lash_R\") {\n const eyeRole = role === \"lash_L\" ? \"eye_L\" : \"eye_R\";\n const eye = placed.find((p) => p.role === eyeRole);\n if (\n eye !== undefined &&\n (eye.left !== left ||\n eye.top !== top ||\n eye.part.w !== part.w ||\n eye.part.h !== part.h)\n ) {\n throw new AutoRigInputError(\n `layout.${role} places the lash at ${part.w}x${part.h} (${left},${top}), but layout.${eyeRole} ` +\n `places its sclera at ${eye.part.w}x${eye.part.h} (${eye.left},${eye.top}) — they are cut from one ` +\n `eyewhite into one frame, and the blink fold tears where they part. Set cx/cy/w/h the same on both.`,\n );\n }\n }\n placed.push({ role, part, left, top });\n }\n\n // Drop the layer an earlier compose into the same dir wrote for each role\n // this run does not write — a skipped one, or an arm once arm.png is\n // gone: left behind it would contradict the result, since measureDir\n // globs the 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 for (const role of ORDER) {\n if (placed.some((p) => p.role === role)) continue;\n fs.rmSync(path.join(outDir, `${role}.png`), { force: true });\n }\n const layers: ComposedLayer[] = [];\n const preview: { input: Buffer; left: number; top: number }[] = [];\n for (const { role, part, left, top } of placed) {\n // role layer: this part alone on a full canvas at its position.\n const layer = await blankCanvas(canvas)\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.width,\n height: canvas.height,\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, noseSpeck),\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, detectAlphaBbox } from \"./node-images\";\nimport { AutoRigInputError, MAX_LAYERS, resolveInputDir } from \"./limits\";\nimport { ARM_ROLES, armWarnings } from \"./measure-arms\";\nimport { SPECK_CORE_FRACTION, denseCoreOf, isSpeckCore } from \"./measure-turn\";\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/** Share of a lash's opaque pixels tolerated off its sclera. In sync there\n * are none — the sclera was recoloured from those very pixels. A real eye\n * measured 0 of 934 in sync, then 6-12 at a 1 px drift, 45-50 at 2 px and\n * 104-110 at 4 px, whichever way it drifted. */\nconst LASH_STRAY_TOL_FRAC = 0.02;\n/** How much further short of the outer corner than of the nose side an eye's\n * lash may stop, as a fraction of the eye width, before the eye reads as\n * drawn facing the other way. Three real eyewhites drawn reversed stopped\n * 4.0-6.1% further short there; one drawn the right way stops short at the\n * nose side instead, and one with a wing at each end at neither. */\nconst EYE_FACING_TOL_FRAC = 0.02;\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/** An arm's seams show once it raises, every other part's on the head turn. */\nconst isArm = (role: string) => (ARM_ROLES as readonly string[]).includes(role);\n\n/** A nose's dense core that `isSpeckCore` judged a speck of its part, as sizes\n * in px: compose's verdict on the trimmed source part, or the composed\n * layer's against its crop. */\nexport interface NoseSpeck {\n core: { w: number; h: number };\n part: { w: number; h: number };\n}\n\n/**\n * The nose-speck warning. Each source says only what its own reader did:\n * `\"compose\"` judged the trimmed source part, before resampling, and composed\n * it whole; `\"layer\"` judged the layer file against its crop, which is what\n * `auto_rig_from_layers` reads. The remedy is the same either way.\n */\nfunction noseSpeckWarning(\n { core, part }: NoseSpeck,\n source: \"compose\" | \"layer\",\n): string {\n const [found, consequence] =\n source === \"compose\"\n ? [\n `the source part's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} trimmed part`,\n `compose_layers_from_parts sized and placed the whole part instead — layout.nose's w and h now size it, feather included`,\n ]\n : [\n `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,\n `auto_rig_from_layers turns and tilts the nose about its whole crop instead`,\n ];\n return (\n `nose: ${found} — under ${SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril ` +\n `mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with ` +\n `its shading painted denser, so the drawing itself reaches alpha 128. Billed.`\n );\n}\n\n/**\n * Count the lash's opaque pixels, and those of them that land where its\n * sclera is transparent. Both are canvas-sized layers, so a pixel's position\n * is the same canvas point in each.\n */\nasync function lashOffSclera(\n eyePath: string,\n lashPath: string,\n): Promise<{ opaque: number; off: number }> {\n const eye = await decodePng(eyePath);\n const lash = await decodePng(lashPath);\n let opaque = 0;\n let off = 0;\n for (let y = 0; y < lash.height; y++) {\n for (let x = 0; x < lash.width; x++) {\n if (lash.rgba[(y * lash.width + x) * 4 + 3] < 128) continue;\n opaque++;\n const onEye = x < eye.width && y < eye.height;\n if (!onEye || eye.rgba[(y * eye.width + x) * 4 + 3] <= 8) off++;\n }\n }\n return { opaque, off };\n}\n\n/**\n * Measure every `*.png` in an already-resolved layers directory but the\n * `preview*.png` ones (`preview.png` is the composer's contact sheet, and a\n * caller's own previews sit beside it; none is a role) and run the geometry\n * checks.\n * `noseSpeck` is compose's own verdict on the nose's source part when that\n * part's core was a speck, and the nose check reports it as given. Left out —\n * compose found no speck, or `measure_layers` — that check judges the `nose`\n * layer file against its crop instead, as `auto_rig_from_layers` does.\n */\nexport async function measureDir(\n absDir: string,\n noseSpeck?: NoseSpeck,\n): Promise<MeasureReport> {\n const files = fs\n .readdirSync(absDir)\n .filter((f) => f.endsWith(\".png\") && !f.startsWith(\"preview\"))\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 bust's torso is meant to run off the bottom of a square canvas. A\n // full body stands on a taller one with its soles inside it, where two\n // soles' flat bottoms could trip the generic check, so a check of its own\n // replaces it: paint on the canvas's last row is feet cut off.\n if (role !== \"body\") {\n edges.push([\"bottom\", m.edgeBottom, m.w, m.marginBottom]);\n } else if (m.canvasH > m.canvasW && m.marginBottom === 0) {\n warnings.push(\n `body: its bottom row is the canvas's last — on a tall canvas that cuts the feet off. ` +\n `Free fix: raise canvasHeight (the canvas grows downward, nothing else moves) and ` +\n `remeasure; regenerate body.png only if the drawing itself stops short of the soles.`,\n );\n }\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 ${isArm(role) ? \"once the arm raises\" : \"once the head turns\"}. ` +\n `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` bends as one drawing, so no pose opens a cut in it; its top is\n // deliberately cut flat where the jaw covers it, and stays under the jaw\n // because the head rides the body.\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 (isArm(role)\n ? `It hides at rest and opens into a seam once the arm raises. `\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 // 1c. The arms: each needs a body, and its shoulder cap the torso under it.\n warnings.push(...(await armWarnings(absDir, layers)));\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). In sync, the lash is ink the sclera was recoloured from, so\n // every opaque lash pixel lies on the sclera, and both ink the same top\n // row; a drift moves pixels off it, and a lash scaled down inside it (a w\n // or h out of sync) drops its top row — the seam the fold rides — either\n // way tearing the fold. Neither the ink centres nor the frame's sides can\n // stand in for that: a lash stops short of the tear duct (5b), so a\n // correctly composed eye's ink sits 3-5% of its width off the sclera's\n // centre, while a lash drifting in toward that bare end stays inside the\n // frame.\n //\n // 5b. Which way the eye was drawn. A lash runs out to the outer corner,\n // wing and all, and stops short of the tear duct at the inner one, so in\n // the frame it shares with the sclera it is the nose end that the lash\n // leaves bare. A lash that stops short of the OUTER end instead is an\n // eyewhite drawn facing the other way: the wings point in, and \"left eye\"\n // in a prompt cannot prevent it, since it reads as the viewer's left or\n // the character's. The ends are read, not the ink's centroid: a thin wing\n // widens the frame far more than it moves the centroid, which reads a\n // correctly drawn eye as reversed. Only a lash in sync is read — a drift\n // moves the ends too, and is check 5's to report, not the drawing's.\n if (lash) {\n const { opaque, off } = await lashOffSclera(\n path.join(absDir, `eye_${side}.png`),\n path.join(absDir, `lash_${side}.png`),\n );\n const dTop = lash.marginTop - eye.marginTop;\n const faults = [\n ...(off > opaque * LASH_STRAY_TOL_FRAC\n ? [`${off} of its ${opaque} opaque px lie off eye_${side}'s sclera`]\n : []),\n ...(Math.abs(dTop) > 0.5\n ? [`its top edge is ${dTop.toFixed(1)} px off the sclera's`]\n : []),\n ];\n if (faults.length > 0) {\n warnings.push(\n `lash_${side}: ${faults.join(\" and \")} — they are split from one source and MUST share ` +\n `cx/cy/w/h in layout, or the blink fold tears. Retune to match.`,\n );\n } else {\n // How far short of each side of the frame the lash stops.\n const bareLeft = lash.marginLeft - eye.marginLeft;\n const bareRight = lash.marginRight - eye.marginRight;\n // eye_R is the screen-left eye: its outer corner is its left end.\n const [bareOuter, bareInner] =\n side === \"R\" ? [bareLeft, bareRight] : [bareRight, bareLeft];\n if ((bareOuter - bareInner) / eye.w > EYE_FACING_TOL_FRAC) {\n warnings.push(\n `eye_${side}: its lash stops ${pct(bareOuter / eye.w)} of the eye width short of the outer corner ` +\n `and ${pct(bareInner / eye.w)} short of the nose side — the eyewhite is drawn facing the other way, ` +\n `lash wing at the inner corner. The composer reads eyewhite.png as the eye on the screen LEFT: lash ` +\n `wing at the image's left end, lash-free tear duct at its right. Free fix: compose again with ` +\n `mirrorParts: [\"eyewhite.png\"] — no regeneration.`,\n );\n }\n }\n }\n }\n\n // 6. A nose whose dense core is a speck of its part (`isSpeckCore`). A\n // speck compose found in the source part, before resampling, is reported\n // as given: a dot blurred under alpha 128 no longer shows in the file.\n // Otherwise the file is judged against its crop — what the rig reads —\n // which also catches a core that only resampling made a speck.\n if (noseSpeck !== undefined) {\n warnings.push(noseSpeckWarning(noseSpeck, \"compose\"));\n } else if (layers.nose !== undefined) {\n const nose = await decodePng(path.join(absDir, \"nose.png\"));\n const core = denseCoreOf(nose.rgba, nose.width, nose.height);\n if (core !== null) {\n const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);\n if (isSpeckCore(core, crop))\n warnings.push(noseSpeckWarning({ core, part: crop }, \"layer\"));\n }\n }\n\n // 7. 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 the head still turns on the default profile, but there is no nose to lead it, and no turn fit to the art (`turnTargets` is inert, no `turn` report)\",\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 * The measure's arm checks. An arm hangs from the body's shoulder, and raising\n * it turns its shoulder cap about the rig's shoulder pivot, so the torso has\n * to reach under that cap or a gap opens beside the shoulder. The pivot is\n * the rig's own: `armGeometry`, run on the layer as `auto_rig_from_layers`\n * runs it, so the cap measured here is the one the rig turns.\n */\n\nimport path from \"node:path\";\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n type ArmGeometry,\n type LayerInput,\n type LayerSetMeasurer,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { decodePng } from \"./node-images\";\n\n/** The arm roles, screen right (`arm_L`) then screen left (`arm_R`). */\nexport const ARM_ROLES = [\"arm_L\", \"arm_R\"] as const;\n\n/** How far an arm's shoulder cap must reach under the torso's edge on the\n * shoulder pivot's row, as a share of its radius r_u. Our own value: a\n * raised arm turns its cap about the pivot, so a cap that barely meets the\n * torso's edge swings clear of it and bares the gap beside the shoulder. */\nexport const CAP_OVERLAP = 0.5;\n\n/** A px figure as the report prints it: pivots sit on half px. */\nconst px = (v: number) => `${Number(v.toFixed(1))}`;\n\n/** Decode a role's layer in `absDir` and measure it on `measurer`. */\nasync function measured(\n measurer: LayerSetMeasurer,\n absDir: string,\n role: string,\n): Promise<LayerInput> {\n const fileName = `${role}.png`;\n const { rgba } = await decodePng(path.join(absDir, fileName));\n // layerStats counts alpha > 8 and the measurer alpha >= 8, so a layer\n // measured non-empty is never empty here.\n return measurer.add({ role, fileName, rgba })!;\n}\n\n/**\n * Warn of an arm layer the rig refuses or would hang with a gap at the\n * shoulder: one without a body, one on another canvas than the body's, one\n * too short to place an elbow under its shoulder, and one whose shoulder cap\n * does not reach `CAP_OVERLAP` of its radius under the torso's edge.\n * `layers` holds the measured, non-empty layers of `absDir` by role.\n */\nexport async function armWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n): Promise<string[]> {\n const warnings: string[] = [];\n const body = layers.body;\n // Opened for the first arm that reaches the overlap, so the body decodes once.\n let set: { measurer: LayerSetMeasurer; body: LayerInput } | undefined;\n\n for (const arm of ARM_ROLES) {\n const stats = layers[arm];\n if (stats === undefined) continue;\n if (body === undefined) {\n warnings.push(\n `${arm}: no body layer — an arm hangs from the body's shoulder, and auto_rig_from_layers refuses it.`,\n );\n continue;\n }\n // One measurer reads every buffer at one size, and a buffer of another\n // shape but the same area would pass its length check and be read with\n // the wrong stride.\n if (stats.canvasW !== body.canvasW || stats.canvasH !== body.canvasH) {\n warnings.push(\n `${arm}: its canvas ${stats.canvasW}x${stats.canvasH} differs from body's ` +\n `${body.canvasW}x${body.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n continue;\n }\n if (set === undefined) {\n const measurer = createLayerSetMeasurer({\n width: body.canvasW,\n height: body.canvasH,\n });\n set = { measurer, body: await measured(measurer, absDir, \"body\") };\n }\n\n let g: ArmGeometry;\n try {\n // The body box's centre, model x: the axis the rig reads an arm's side\n // off.\n g = armGeometry(\n await measured(set.measurer, absDir, arm),\n set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2,\n );\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n warnings.push(\n `${arm}: ${err.message} — auto_rig_from_layers refuses it. Regenerate arm.png drawn ` +\n `hanging, shoulder at the top. Billed.`,\n );\n continue;\n }\n throw err;\n }\n const cap = capWarning(arm, g, set.body);\n if (cap !== undefined) warnings.push(cap);\n }\n return warnings;\n}\n\n/**\n * The shoulder cap against the torso's edge on the arm's side, on the canvas\n * row holding the shoulder pivot: the cap reaches r_u past the pivot, so it\n * overlaps the torso by r_u less the pivot's distance outside that edge.\n */\nfunction capWarning(\n arm: (typeof ARM_ROLES)[number],\n g: ArmGeometry,\n body: LayerInput,\n): string | undefined {\n // Model space is centred on the canvas, y up.\n const pivotX = g.shoulder.x + body.canvasW / 2;\n const row = Math.floor(body.canvasH / 2 - g.shoulder.y);\n const runs = body.rowRuns?.[row - body.bbox.y] ?? [];\n if (runs.length === 0) {\n return (\n `${arm}: the body has no paint on its shoulder pivot's row (y=${row}) — the torso shows a ` +\n `gap beside the shoulder once the arm raises. Retune layout.${arm}.cy onto the shoulder (free).`\n );\n }\n // The outermost run's end on the arm's side; a run's end column is exclusive.\n const edge = g.side === 1 ? runs[runs.length - 1] : runs[0];\n const overlap = g.shoulderRadius - g.side * (pivotX - edge);\n const need = CAP_OVERLAP * g.shoulderRadius;\n if (overlap >= need) return undefined;\n return (\n `${arm}: its shoulder cap reaches ${px(overlap)} px under the torso's edge on its pivot row ` +\n `(y=${row}), under half its radius (${px(need)} px) — a gap opens beside the shoulder once ` +\n `the arm raises. Move layout.${arm}.cx ${Math.ceil(need - overlap)} px toward the body (free).`\n );\n}\n","/**\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 {\n ALPHA_OPAQUE,\n HEAD_BAND,\n foregroundSpan,\n headHalfOf,\n} from \"@ikijs/editor\";\nimport { decodePng, encodeOverlayPng } from \"./node-images\";\nimport {\n AutoRigInputError,\n resolveInputPath,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n// Re-exported so compose.ts, measure.ts and the tests keep their imports.\nexport {\n SPECK_CORE_FRACTION,\n denseCoreOf,\n headHalfOf,\n isSpeckCore,\n} from \"@ikijs/editor\";\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\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.\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/** 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 * Where the composer hangs an arm. One arm.png is the arm on the screen LEFT:\n * `arm_R` takes it as drawn and `arm_L` mirrored. Each of an arm's `cx` / `cy`\n * that the layout leaves unset is derived from the placed body's box: the\n * arm's shoulder pivot lands on the box's shoulder corner on that axis — the\n * box's left edge for `arm_R`, its right edge for `arm_L`, SHOULDER_DROP of\n * its height under its top. On a torso widest at its shoulders, the cap's\n * centre then sits on the torso's edge, overlapping it by the cap's radius.\n * An unset `w` is ARM_WIDTH of the body's width.\n *\n * The pivot is the rig's own: `armGeometry`, run on the resized part as\n * `auto_rig_from_layers` runs it on the composed layer, so the rig turns the\n * composed arm about the target to the pixel, with no second copy of its\n * shoulder rule here to keep in step.\n */\n\nimport sharp from \"sharp\";\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n} from \"@ikijs/editor\";\nimport type { ArmLayout } from \"./compose\";\nimport { AutoRigInputError } from \"./limits\";\n\n/** An arm's default width, as a share of the placed body's width. Our own\n * value, provisional: to be picked by eye on the first full-body character. */\nexport const ARM_WIDTH = 0.4;\n/** How far under the body box's top its shoulder corners lie, as a share of\n * its height. Our own value, provisional: to be picked by eye on the first\n * full-body character. */\nexport const SHOULDER_DROP = 0.12;\n\n/** A placed part's box on the canvas, px. */\ninterface PlacedBox {\n left: number;\n top: number;\n w: number;\n h: number;\n}\n\n/**\n * Where an arm's resized part lands: by its rig shoulder pivot on the body\n * box's shoulder corner for each of `cx` / `cy` left unset, centred on a set\n * one as every other role's part is. An arm the rig would refuse as too short\n * is refused here, path-qualified.\n */\nexport async function armPlacement(\n role: \"arm_L\" | \"arm_R\",\n cfg: Pick<ArmLayout, \"cx\" | \"cy\">,\n part: { buf: Buffer; w: number; h: number },\n body: PlacedBox,\n): Promise<{ left: number; top: number }> {\n const { data } = await sharp(part.buf)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const layer = createLayerSetMeasurer({ width: part.w, height: part.h }).add({\n role,\n fileName: \"arm.png\",\n rgba: data,\n });\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.${role}: arm.png is empty after alpha threshold once resized`,\n );\n }\n let shoulder: { x: number; y: number };\n try {\n // Only the shoulder is read. The axis keeps `side` the role's own all\n // the same: arm_R on the screen left, arm_L on the right.\n ({ shoulder } = armGeometry(\n layer,\n role === \"arm_R\" ? Infinity : -Infinity,\n ));\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n throw new AutoRigInputError(`layout.${role}: ${err.message}`);\n }\n throw err;\n }\n // Model space is centred on the measured canvas, here the part itself.\n const pivotX = shoulder.x + part.w / 2;\n const pivotY = part.h / 2 - shoulder.y;\n const cornerX = role === \"arm_R\" ? body.left : body.left + body.w;\n const cornerY = body.top + SHOULDER_DROP * body.h;\n return {\n left: Math.round(\n cfg.cx === undefined ? cornerX - pivotX : cfg.cx - part.w / 2,\n ),\n top: Math.round(\n cfg.cy === undefined ? cornerY - pivotY : cfg.cy - part.h / 2,\n ),\n };\n}\n","#!/usr/bin/env node\nimport { createIkiMcpServer } from \"./server\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\n\nasync function main() {\n const server = createIkiMcpServer();\n await server.connect(new StdioServerTransport());\n}\n\nmain().catch((err) => {\n console.error(err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iBAA0B;AAC1B,iBAAkB;;;ACDlB,IAAAA,oBAAiB;AACjB,oBAOO;AACP,IAAAC,iBAiBO;;;ACZP,mBAAkB;AAElB,oBAAiD;;;ACJjD,qBAAe;AACf,uBAAiB;AAGV,IAAM,aAAa;AAEnB,IAAM,gBAAgB;AAEtB,IAAM,iBAAiB;AAKvB,IAAM,iBAAiB;AAEvB,IAAM,mBAAmB,OAAO;AAIhC,IAAM,mBAAmB,MAAM,OAAO;AAMtC,IAAM,mBAAmB,KAAK,OAAO;AAOrC,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,iBAAAC,QAAK,QAAQ,QAAQ,IAAI,GAAG,SAAS;AACtD,MAAI;AACJ,MAAI;AACF,WAAO,eAAAC,QAAG,SAAS,QAAQ;AAAA,EAC7B,QAAQ;AACN,UAAM,IAAI,kBAAkB,yBAAyB,QAAQ,EAAE;AAAA,EACjE;AACA,MAAI,KAAK,YAAY,GAAG;AACtB,UAAM,IAAI;AAAA,MACR,0C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AAqB,CAAC;AACjD;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["import_node_path","import_editor","path","fs","sharp","scanAlphaBbox","placement","path","placement","import_node_fs","import_node_path","import_sharp","import_editor","import_node_fs","import_node_path","import_node_path","import_editor","path","import_node_path","import_editor","import_editor","path","fs","path","import_sharp","import_editor","sharp","sharp","scanAlphaBbox","path","fs","px","part","left","top"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/tools.ts","../src/node-images.ts","../src/limits.ts","../src/compose.ts","../src/measure.ts","../src/measure-arms.ts","../src/measure-forearm-pose.ts","../src/measure-turn.ts","../src/compose-arms.ts","../src/cli.ts"],"sourcesContent":["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 and its expressions and motion clips (with the descriptions a host picks them by); 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 and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, etc. optional; an arm needs the body, a pose forearm needs its arm, and a partial lip set or one mixed with mouth/mouth_open is refused) 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. A `nose` layer stays lossless on a second atlas page of its own, since the palette rims a soft-shaded nose's feather; the nose's own lossless page adds a content-dependent amount, since splitting it off also changes how page 0 re-quantizes without it; the result's `atlasBytes` sums both pages.\",\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 .passthrough()\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`) 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 leaves that part of the turn at the profile the rig defaults to. A passed `eyeShift` is fitted by the turn's amount and clamped to the room the art leaves the far eye — the face plate's edge, or the bangs' side strand over the far iris (the result's `turn.clamped` lists every clamped field, `turn.achieved` what the rig reaches, and `turn.strandOverlap` how much of a far iris the bangs still cover). A passed `silhouetteRatio` is clamped too, only on a face drawn without hair and with ear islands, where narrowing the head that far would no longer cover the far ear's slide. Any other passed target 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. A field not named here is refused the same way.\",\n ),\n style: z\n .object({\n turn: z.number().optional(),\n featureLead: z.number().optional(),\n hairFollow: z.number().optional(),\n outlineFollow: z.number().optional(),\n blink: z.number().optional(),\n sway: z.number().optional(),\n })\n .passthrough()\n .optional()\n .describe(\n \"Per-character tuning from the profile the rig defaults to: `turn` scales the whole head turn (plate, features, hair and the eyes' foreshortening; 0..3, 1 = the profile; ignored when `turnTargets.eyeShift` is given), `featureLead` how far the features lead the face plate (0..3, 1 = the profile), `hairFollow` the front hair's share of the face's turn (0..2, profile 1), `outlineFollow` its outer edge's share where the front hair draws the head's outline (0..2, profile 0: the outline holds), `blink` how far the upper lid comes down over the eye's height (0.1..1, profile 0.6), `sway` the hair sway amplitude (0..5, 1 = the profile). A value out of range, or a knob not named here, comes back as `INVALID: …`.\",\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, blush (one blush.png makes the blush_L/blush_R pair) and nose are optional — without a nose layer the head still turns on the rig's default profile, but it has no nose to lead the turn, and `auto_rig_from_layers` fits no turn to the art (`turnTargets` is inert, no `turn` report). One arm.png — the arm on the screen LEFT, drawn hanging with its shoulder at the top — makes both arms of a full body: arm_R takes it as drawn and arm_L mirrored. The arms are opt-in: without arm.png the compose is a bust's and `skipped` never lists them. arm.png needs body.png, and each arm is hung on the body's shoulder by default (see `layout`). One forearm_pose.png — the arm's forearm raised, on the screen LEFT, standing up from its elbow with the hand at the top — makes both pose forearms (forearm_pose_R as drawn, forearm_pose_L mirrored): each is scaled so its elbow end is as wide as its arm's elbow run and pinned on that arm's elbow (see `layout`), and it needs arm.png. With one, preview-pose.png shows the switch at 1 as the rig draws it (the hanging forearms hidden below the elbow, the pose forearms over everything) while preview.png stays the rest pose; without one it is removed. The inline report carries the full-body checks too: a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge, and a pose forearm without its arm or off its arm's elbow in pivot, width or length. A nose whose dense core is a speck — under a quarter of its trimmed part's width or height, such as a lone nostril mark or highlight — is sized and placed whole, and the inline report warns of it. A light mark drawn detached above the eye white, such as a double-eyelid crease, is dropped from the sclera (the iris's clip); dark strokes there stay lash ink. The eyewhite's dark lower lid — its line and lashes — becomes lash_lower_L/lash_lower_R, drawn over the iris; a white with none writes none and lists them in `skipped`.\",\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 (and preview-pose.png when there is a forearm_pose.png) into (resolved against cwd; must already exist; confined to the working directory). Reused across runs: a role this run does not write — one it skips, or an arm or pose forearm once arm.png or forearm_pose.png is gone, preview-pose.png included — 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, arm_L, arm_R, face, blush_L, blush_R, nose, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front, forearm_pose_L, forearm_pose_R — e.g. `{ eye_L: { cx: 660 } }`. `w` is an integer in 1..1100 (the canvas width) and `h` in 1..canvasHeight; omit `h` to keep the part's own aspect, set it to stretch. The defaults of the face's features — blush, nose, mouth, mouth_open, eyes, irises, lashes, brows — are proportions of the face: an override of face.cx, face.cy or face.w carries them with it (scaled by the width; face.h stretches the face alone), while a feature's own override names canvas px. The nose is sized and placed by its dense core (its pixels at alpha >= 128, the drawing inside a soft nose's feather), not its whole part: `w`/`h` size the core, `cx` centres it, and a set `cy` centres its rows. A nose whose core is a speck — under a quarter of the trimmed part's width or height, such as a lone nostril mark or highlight — is sized and placed whole instead, and the report warns of it. Its `cy` defaults to unset, which lands the core's bottom row (the tip) 0.66 of the way from the eye row down to the mouth's, so the nose follows a retuned eye or mouth row. eye_L/lash_L and eye_R/lash_R are cut from one eyewhite into one frame, so each pair must land on the same frame — a pair set to land apart is rejected. lash_lower_L/lash_lower_R are cut from it too and have no key: they land on their eye's frame. arm_L/arm_R have no cx/cy/w defaults: an unset `w` is 0.4 of the placed body's width, and an unset `cx` or `cy` hangs the arm's shoulder pivot — the one auto_rig_from_layers turns it about — on the body box's shoulder corner on that axis: its left edge for arm_R, its right edge for arm_L, 0.12 of its height under its top. A set one centres the arm as for every other role. forearm_pose_L/forearm_pose_R have no cx/cy/w defaults either: an unset `w` scales the forearm so its elbow end (the shoulder rule run from its bottom) is as wide as the placed arm's elbow run, and an unset `cx` or `cy` pins that elbow end's pivot on the arm's elbow — the one auto_rig_from_layers hangs it from.\",\n ),\n mirrorParts: z\n .array(z.string())\n .optional()\n .describe(\n \"Part files to flip left-right as they are read, e.g. `[\\\"eyewhite.png\\\"]`. The composer reads eyewhite.png as the eye on the screen LEFT (lash wing at the image's left end, lash-free tear duct at its right), brow.png as the brow on the screen RIGHT (thick head at the image's left end, tail at its right), blush.png as the blush on the screen LEFT (outer end, toward the face's edge, at the image's left end, inner end at its right), arm.png as the arm on the screen LEFT (the character's right, hanging, its shoulder at the image's top), and forearm_pose.png as the raised forearm on the screen LEFT (standing up from its elbow, the hand at the image's top, the thumb toward the body at the image's right); a part drawn the other way round is fixed here for free. It flips the source, so every role cut from it flips together and an eye's sclera and lash stay in one frame.\",\n ),\n canvasHeight: z\n .number()\n .optional()\n .describe(\n \"The canvas's height in px: an even integer in 1100..4096, default 1100 (a square bust canvas; at 1100 every output is byte-identical to leaving it out). The width stays 1100. The canvas grows downward: every default and every override keeps its canvas px from the top-left, so the head lands where it does on a bust and a full body gets room below. An odd height is refused — model space is centred on the canvas, so it would put the head on a half pixel — and it is checked before any part decodes.\",\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, a nose whose dense core is a speck of its crop, missing optional roles, a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge on its shoulder pivot's row, a pose forearm without its arm or whose elbow end is off its arm's elbow in pivot, width or length). Every preview*.png is skipped. Use to re-check a layers dir without recomposing. Its nose check reads the composed file against its crop, which is what auto_rig_from_layers acts on. Compose's inline report does the same unless the composer found the source part's core a speck, which it reports instead — so a speck that resampling erased from the layer shows there and not here.\",\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","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 createLayerSetMeasurer,\n generateIkiFromLayerSet,\n parseLayerRoles,\n partIdsOfRole,\n LayerGeometryError,\n TurnTargetError,\n type IrisStrand,\n type LayerSetMeasurer,\n type AtlasAssignment,\n type AtlasLayout,\n type RigStyle,\n type TurnTargets,\n type TurnSolveReport,\n} from \"@ikijs/editor\";\nimport {\n decodePng,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_SIDE,\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 /** Each expression's id and the description a host picks it by. */\n expressions: { id: string; description: string }[];\n /** Each motion group's clip descriptions, by clip index. */\n motions: Record<string, string[]>;\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 expressions = (m.expressions ?? []).map((e) => ({\n id: e.id,\n description: e.description,\n }));\n\n const motions = Object.fromEntries(\n Object.entries(m.motions ?? {}).map(([group, clips]) => [\n group,\n clips.map((c) => c.description),\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 expressions,\n motions,\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.BodyAngleX,\n description:\n \"Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head.\",\n },\n {\n id: StandardParameter.BodyAngleY,\n description:\n \"Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows.\",\n },\n {\n id: StandardParameter.BodyAngleZ,\n description:\n \"Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head.\",\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.Cheek,\n description: \"Cheek blush strength (0 .. 1), raised by an expression.\",\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 id: StandardParameter.ArmLeft,\n description:\n \"Left shoulder, degrees; positive raises the arm outward (mirrored on the right).\",\n },\n {\n id: StandardParameter.ArmRight,\n description:\n \"Right shoulder, degrees; positive raises the arm outward (mirrored on the left).\",\n },\n {\n id: StandardParameter.ElbowLeft,\n description:\n \"Left elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right).\",\n },\n {\n id: StandardParameter.ElbowRight,\n description:\n \"Right elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left).\",\n },\n {\n id: StandardParameter.ArmPoseLeft,\n description:\n \"Left pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm.\",\n },\n {\n id: StandardParameter.ArmPoseRight,\n description:\n \"Right pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm.\",\n },\n {\n id: StandardParameter.ArmPoseAngleLeft,\n description:\n \"Left pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the right).\",\n },\n {\n id: StandardParameter.ArmPoseAngleRight,\n description:\n \"Right pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the left).\",\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 * A `nose` layer is left out of the quantized page, on a second, lossless\n * page of its own, because the palette rims a soft-shaded nose's feather. */\n quantizeColors?: number;\n /** Head-turn cues to fit the rig to, as `measure_turn_reference` reports\n * them. */\n turnTargets?: AutoRigTurnTargets;\n /** Per-character tuning from the profile's defaults (see\n * @ikijs/editor's `RigStyle`). */\n style?: RigStyle;\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 /** The atlas's embedded size: its data URI's length, summed over both\n * pages when a quantized rig puts the nose on a page of its own. */\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 /** Each side's iris and the `hair_front` run it would slide under on\n * the turn, as pixel edges on the row holding that iris's centre, in\n * model coordinates (`IrisStrand`: canvas x minus half the canvas\n * width) — measured whenever the layer set has `hair_front`, `iris_L`\n * and `iris_R`, and passed to the generator as `options.strandEdges`.\n * A run narrower than half that iris's painted width on the row is\n * hair detail, not a strand, and is skipped as if clear. A side is\n * absent only when its iris has no opaque pixel on that row, or when no\n * run it keeps covers the pixel on that side of the iris's centre or\n * lies outward of it; the whole field only when neither side has one. */\n strandEdges?: { left?: IrisStrand; right?: IrisStrand };\n /** The nose's dense core, canvas px — its pixels at alpha >= 128, not\n * grown — the box handed to the generator as the nose layer's\n * `denseCore` and, there, its turn landmark. Absent without a `nose`\n * layer, when the nose has no pixel at that threshold (painted wholly\n * translucent), or when its core is a speck of its crop\n * (`isSpeckCore`: a lone nostril mark or highlight); the crop stands\n * in for it in both cases. */\n noseCore?: { x: number; y: number; w: number; h: number };\n /** What the turn solve settled on — the cues the rig reaches, the\n * targets it had to cut down (`clamped`) and, per side whose far iris\n * the bangs' run still covers at some far stop, how much of it\n * (`strandOverlap`). Absent for a layer set with no nose, which solves\n * 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 role that keeps a lossless atlas page of its own under `quantizeColors`.\n * At 256 colours a soft nose's feather took the hair edge's lavender palette\n * entries and drew a rim around the nose; changing the dither, the effort, the\n * alpha floor or the alpha curve did not fix it. A lossless page for the nose\n * alone did, and the hero's model came to about 1.28 MB, against 3.18 MB with\n * the whole atlas lossless.\n */\nconst LOSSLESS_PAGE_ROLE = \"nose\";\n\n/** Pack `crops` onto one atlas page and render it — palette-quantized to\n * `quantizeColors` when that is set. A page over MAX_ATLAS_SIDE on either side\n * is refused before rendering, naming its widest (or tallest) crop. */\nasync function renderAtlasPage(\n crops: AtlasCrop[],\n quantizeColors: number | undefined,\n): Promise<{ crops: AtlasCrop[]; layout: AtlasLayout; dataUri: string }> {\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n );\n const over =\n layout.pageWidth > MAX_ATLAS_SIDE\n ? ({ side: \"width\", crop: \"widest\" } as const)\n : layout.pageHeight > MAX_ATLAS_SIDE\n ? ({ side: \"height\", crop: \"tallest\" } as const)\n : undefined;\n if (over !== undefined) {\n const crop = layout.placements.reduce((a, b) =>\n b[over.side] > a[over.side] ? b : a,\n );\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max side ${MAX_ATLAS_SIDE} (its ${over.crop} crop: \"${crop.id}\" ${crop.width}x${crop.height})`,\n );\n }\n const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);\n return { crops, layout, dataUri };\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 what @ikijs/editor's\n * `createLayerSetMeasurer` measures off the decoded layers (the head\n * half-width, `headEdges`, `strandEdges`, the face's `rowHalfWidths`, the face's\n * and hair layers' opaque runs and the nose's dense core, returned as\n * `noseCore`); what the solve settled on comes back in `turn`. Under\n * `quantizeColors` the nose is atlased alone on a second, lossless page, which\n * the palette would otherwise rim; `atlasBytes` sums both pages.\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 // Checked before the generator call spreads it: a spread turns null or an\n // array into {}, which would rig on the defaults instead of refusing.\n const turnTargets: unknown = input.turnTargets;\n if (turnTargets !== undefined) {\n if (\n typeof turnTargets !== \"object\" ||\n turnTargets === null ||\n Array.isArray(turnTargets)\n ) {\n throw new AutoRigInputError(\"turnTargets must be a plain object\");\n }\n // Excluded from AutoRigTurnTargets, but a JS caller can still pass one:\n // the half-width is measured off the layers below, so a caller's own is\n // refused rather than silently dropped.\n if ((turnTargets as TurnTargets).headHalfWidth !== undefined) {\n throw new AutoRigInputError(\n \"turnTargets.headHalfWidth is measured off the layers, not accepted as input\",\n );\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 // Measures each layer while its decoded pixels are live, keeping none of\n // them (see createLayerSetMeasurer). Created once the first layer gives the\n // canvas.\n let measurer: LayerSetMeasurer | undefined;\n const crops: AtlasCrop[] = [];\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 measurer = createLayerSetMeasurer({ width: canvasW, height: 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 // Created at i === 0 above.\n const layer = measurer!.add({ role, fileName, rgba: png.rgba });\n if (layer === null) {\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": layer is empty after alpha threshold`,\n );\n }\n const { bbox } = layer;\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\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 crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n // `layers` is non-empty (checked above), so the loop created the measurer.\n const measurement = measurer!.finish();\n const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;\n const { headEdges, strandEdges } = turnOptions;\n\n // The nose layer's own denseCore, for the result — undefined without a\n // `nose` layer, or when the measurer's denseCoreOf found no pixel at\n // ALPHA_OPAQUE or a speck of the crop.\n const noseCore = measurement.layers.find(\n (l) => l.role === \"nose\",\n )?.denseCore;\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 for the generator's two input errors, each a fact about the\n // request, not a bug: the turn solve, the one part of it that reads CALLER\n // input, throws TurnTargetError (a field that is not a number, a target\n // this layer set cannot reach); and art geometry the rig cannot build on\n // (a body's hips with no room under its pivots, an arm too short for its\n // pivots, a lip set whose mouth_inner has no opaque pixel) throws\n // LayerGeometryError.\n let turn: TurnSolveReport | undefined;\n let model: IkiModel;\n try {\n // The caller's fields cross as passed (a headHalfWidth was refused\n // above), so the generator refuses a misspelt one; the measured\n // headHalfWidth, when applied, is merged in after them.\n model = generateIkiFromLayerSet(\n measurement.layers,\n { width: canvasW, height: canvasH },\n {\n turnTargets: {\n ...input.turnTargets,\n ...turnOptions.turnTargets,\n },\n onTurnSolved: (report) => {\n turn = report;\n },\n ...(input.style === undefined ? {} : { style: input.style }),\n ...(headEdges === undefined ? {} : { headEdges }),\n ...(strandEdges === undefined ? {} : { strandEdges }),\n },\n );\n } catch (e) {\n if (!(e instanceof TurnTargetError || e instanceof LayerGeometryError)) {\n throw e;\n }\n throw new AutoRigInputError(e.message);\n }\n const doc = new EditorDocument(model);\n\n // Under quantizeColors the nose is page 1, alone and lossless (see\n // LOSSLESS_PAGE_ROLE), and page 0 every other crop; otherwise one page.\n const losslessCrop =\n quantizeColors === undefined\n ? undefined\n : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);\n const pages =\n losslessCrop === undefined\n ? [await renderAtlasPage(crops, quantizeColors)]\n : [\n await renderAtlasPage(\n crops.filter((c) => c !== losslessCrop),\n quantizeColors,\n ),\n await renderAtlasPage([losslessCrop], undefined),\n ];\n const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);\n if (atlasBytes > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n // Each crop's uv is on its own page, normalised to that page's size.\n const partTextureAssignments: AtlasAssignment[] = pages.flatMap(\n ({ crops: pageCrops, layout }) =>\n pageCrops.flatMap((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 const uv = uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n });\n // Every part of a role samples its crop: a forearm shares its arm's.\n return partIdsOfRole(crop.id).map((partId) => ({ partId, uv }));\n }),\n );\n\n // applyAtlas takes a single page: it sets every part's index to 0 and\n // remaps each mesh's uvs into its rect, which for the nose is already in\n // page 1's space — so the nose only needs its index, set on a clone\n // because getModel() hands back the document's live model, read-only.\n doc.applyAtlas({\n textures: [{ source: pages[0].dataUri }],\n partTextureAssignments,\n });\n let patched = doc.getModel();\n if (losslessCrop !== undefined) {\n patched = structuredClone(patched);\n patched.textures = pages.map((p) => ({ source: p.dataUri }));\n for (const partId of partIdsOfRole(losslessCrop.id)) {\n patched.parts.find((p) => p.id === partId)!.texture!.index = 1;\n }\n }\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(patched);\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,\n ...(headHalfWidth === undefined ? {} : { headHalfWidth }),\n headHalfWidthApplied,\n ...(headEdges === undefined ? {} : { headEdges }),\n ...(strandEdges === undefined ? {} : { strandEdges }),\n ...(noseCore === undefined ? {} : { noseCore }),\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 * 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. Soft\n * alpha is where it fails: a shaded nose's feather rims in borrowed palette\n * entries, so the auto-rig renders the nose on its own page without it.\n * Splitting it off also changes how page 0 re-quantizes, so the size effect\n * is content-dependent — on the playground hero the split model came to\n * 1.28MB, about the same as the all-quantized 1.29MB and well under the\n * 3.18MB lossless model.\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 per-side length (px) of each packed atlas page. WebGL2 guarantees only\n * 2048, but 4096 or more is near-universal; the engine refuses a texture over\n * the device's own limit on either side and leaves its parts untextured. Both\n * sides within it also bound a page's area at 4096². */\nexport const MAX_ATLAS_SIDE = 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. Layers\n * decode one at a time, so it bounds the request's total work, not its peak\n * memory. A full body's 21 layers at 1100 × 3650 decode 84.3 M px. */\nexport const MAX_TOTAL_PIXELS = 128 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model,\n * summed over its pages. Sized for the loop's lossless re-rig of a full body:\n * measured on bob's layers, a lossless atlas costs 1.56 data-URI bytes per\n * crop px (1,677,898 B over 1,075,888 px), and a full body on a canvas up to\n * 4096 tall crops to at most ~5 M px, about 8 MB. */\nexport const MAX_OUTPUT_BYTES = 12 * 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","/**\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, CANVAS wide and\n * `canvasHeight` tall (CANVAS unless a full body sets it) — the nose by its\n * dense core, the drawing inside a soft nose's feather.\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 { ALPHA_OPAQUE, detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { cropToBuffer, decodePng } from \"./node-images\";\nimport { measureDir, type MeasureReport, type NoseSpeck } from \"./measure\";\nimport { denseCoreOf, isSpeckCore } from \"./measure-turn\";\nimport {\n ARM_WIDTH,\n armPlacement,\n forearmPosePlacement,\n forearmPoseWidth,\n} from \"./compose-arms\";\nimport {\n AutoRigInputError,\n MAX_CANVAS_DIM,\n resolveInputDir,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n/**\n * The layer canvas's width, and its default height, in px. The width is NOT an\n * input: the layout defaults below place parts against it (hair_front alone is\n * 660px wide, and sharp rejects a composite input larger than its\n * destination), so a different width would need its own layout. The height is\n * `canvasHeight`: the canvas grows downward from this square, so every default\n * keeps its place. The tuning surface is `layout` overrides.\n */\nexport const CANVAS = 1100;\n\n/** The layer canvas, in px: CANVAS wide and `canvasHeight` tall. */\ninterface Canvas {\n width: number;\n height: number;\n}\n\n/**\n * The canvas as error messages name it: \"1100\" when square, as every message\n * did before the height could grow, and \"1100x3650\" when tall.\n */\nfunction canvasName(canvas: Canvas): string {\n return canvas.width === canvas.height\n ? `${canvas.width}`\n : `${canvas.width}x${canvas.height}`;\n}\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; the defaults below are the hero bob's, 50px in a\n// 98px opening (0.51). A caller retunes eye size through\n// `layout.eye_L/eye_R.w` and MUST move `layout.iris_L/iris_R.w` with it to keep\n// that ratio.\nconst EYE_W = 98;\nconst IRIS_W = 50;\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, those in the TOP this-fraction are the upper lash,\n// an arc that folds DOWN over the eye on blink instead of a full ring that\n// shrinks in place; those below it are the lower lid's line and lashes.\nconst LASH_KEEP_FRACTION = 0.5;\n\n/** The alpha a part's trim cuts at: what it keeps is over this. */\nconst TRIM_THRESHOLD = 12;\n/** Of a part's kept pixels, the share under which a faint detached set is a stray speck. */\nconst STRAY_SPECK_FRACTION = 0.01;\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/**\n * The nose's layout. Its `w`, `h` and `cx` size and place its dense core\n * (`denseCoreOf`), not its whole trimmed part: a soft nose is mostly feather,\n * and sized by its extent it renders as a dot. A part with no core, or whose\n * core is a speck of it (`isSpeckCore`: a lone nostril mark or highlight,\n * which sized to `w` would blow the whole nose up), is sized and placed whole\n * instead, and the speck is warned about. Unlike every other role's, its `cy`\n * is optional. Set, it is the core's centre row; absent, the core's bottom row\n * — the tip — lands NOSE_TIP_AT of the way from the eye row down to the\n * mouth's.\n */\ninterface NoseLayout extends Omit<RoleLayout, \"cy\"> {\n cy?: number;\n}\n\n/**\n * An arm's layout. Its `cx`, `cy` and `w` are optional, each derived from the\n * placed body when unset (compose-arms.ts): `w` is ARM_WIDTH of the body's\n * width, and an unset `cx` or `cy` hangs the arm's shoulder pivot, the one\n * the rig turns it about, on the body box's shoulder corner on that axis. A\n * set one keeps every other role's meaning. The pose forearms share its shape\n * with their own derivation (compose-arms.ts): an unset `w` scales the\n * forearm's elbow end to the placed arm's elbow run, and an unset `cx` or\n * `cy` pins its elbow-end pivot on the arm's elbow.\n */\nexport interface ArmLayout extends Omit<RoleLayout, \"cx\" | \"cy\" | \"w\"> {\n cx?: number;\n cy?: number;\n w?: number;\n}\n\n/** A box in a part's own px, origin top-left. */\ninterface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Where a nose with no `cy` puts its tip, as a fraction of the way from the\n * eye row down to the mouth's. Bob's: tip row 554 between eye row 475 and\n * mouth row 594 (79/119 ≈ 0.66), so the default rows land bob's nose where his\n * own layout placed it.\n */\nconst NOSE_TIP_AT = 0.66;\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 centred across the canvas, in its top CANVAS rows).\n// They are canvas px from the top-left, so a taller canvas only adds room\n// below them. The face, eyes, irises,\n// lashes, brows, nose and mouth are the hero bob's own tuning; bob wears his\n// blush at its default placement, picked on his face (below). The features'\n// defaults are proportions of the face: resolveLayout carries them with the\n// face's cx, cy and w. The hair and\n// the torso depend on the hairstyle and on how the torso is framed, so they are\n// older defaults every character retunes from the report. If the rendered model is misaligned, tune cx/cy/w through the\n// `layout` override and re-run — composing is cheap and the parts do not need\n// regenerating.\n//\n// eyeSide reminder: eye_L = character's LEFT eye = screen RIGHT (larger cx).\n// Which way a source faces is fixed by the mirror flags below, and \"left eye\"\n// cannot say it — it reads as the viewer's left or the character's. So in\n// image terms: eyewhite.png is the eye on the SCREEN LEFT, its lash wing (outer\n// corner) at the image's left end and its lash-free tear duct at the right;\n// brow.png is the brow on the SCREEN RIGHT, its thick head at the image's left\n// end and its tail at the right; blush.png is the blush on the SCREEN LEFT,\n// its outer end (toward the face's edge) at the image's left end and its\n// inner end (toward the nose) at the right; arm.png is the arm on the SCREEN\n// LEFT (the character's right), hanging, its shoulder at the image's top and\n// its hand at the bottom; forearm_pose.png is that arm's forearm raised, on\n// the SCREEN LEFT too: standing up from its elbow, the open hand at the\n// image's top with the thumb at its right (toward the body), a rounded\n// closed elbow end at the bottom. A part drawn the other way round is\n// flipped for free with `mirrorParts`.\n// eye_* = the WHITE sclera (upper lashes recolored white) = the blink clip mask + fold.\n// iris_* = colored disc on top, clipped to the sclera, drives gaze.\n// lash_lower_* = the lower lid's dark line and lashes, ABOVE the iris (it\n// covers the iris's bottom edge, as the drawing does) and folding\n// with the white. Placed on the eye's frame, so it has no layout key.\n// lash_* = the dark upper lashes, a separate layer ABOVE the iris that folds\n// down to cover the closed-eye seam. eye_*, lash_lower_* and lash_* are\n// split from a single `eyewhite.png` (white almond + dark lashes) by\n// 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 bust's torso, cut off by a square canvas's bottom, so the character is\n // not a floating head; a full body on a tall canvas sets `layout.body`\n // itself. It rides the rig's `bodyWarp`, which the head hangs from.\n body: { src: \"body.png\", cx: 550, cy: 1017, w: 840, optional: true },\n // The arms, one part for both: arm_R (screen left) takes arm.png as drawn\n // and arm_L mirrors it, like the blush. They draw over the body and under\n // the face. They have no cx/cy/w defaults: each is derived from the placed\n // body (ArmLayout). OPTIONAL and opt-in: a parts dir without arm.png\n // composes as a bust does, and `skipped` never lists them.\n arm_L: { src: \"arm.png\", optional: true, mirror: true },\n arm_R: { src: \"arm.png\", optional: true, mirror: false },\n // The face is drawn without a neck, so its box is the skull and centres\n // above the eye row (bob's skull at 437 against his eyes' 475).\n face: { src: \"face.png\", cx: 550, cy: 437, w: 400 },\n // The cheek blush, one part for both cheeks: blush_R (screen left) takes it\n // as drawn and blush_L mirrors it, like the eyewhite. It draws over the face\n // and under the nose. Its box sits below each eye, centred 5 px outside the\n // eye's centre and 55 px under its row, above the nose tip: on bob's face,\n // which narrows fast below the eye row, a 2:1 blush there stays on the\n // cheek through the turn, where one 26 px further out reached the ears.\n // OPTIONAL: a parts dir without it composes, and nothing reports it missing.\n blush_L: { src: \"blush.png\", cx: 641, cy: 530, w: 56, optional: true, mirror: true }, // prettier-ignore\n blush_R: { src: \"blush.png\", cx: 459, cy: 530, w: 56, optional: true, mirror: false }, // prettier-ignore\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. `w` is the\n // width of its dense core, and it has no `cy`: its row comes from the tip\n // rule (NOSE_TIP_AT), between the eyes and the mouth, so it follows them\n // when they are retuned. OPTIONAL: a parts dir without it composes.\n nose: { src: \"nose.png\", cx: 550, w: 20, optional: true },\n mouth: { src: \"mouth.png\", cx: 550, cy: 594, w: 76 },\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: 596,\n w: 76,\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: 636, cy: 475, w: EYE_W, mirror: true, noTrim: true }, // prettier-ignore\n eye_R: { src: \"eyewhite_sclera.png\", cx: 464, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n // A little under the white's centre and toward the nose, as bob's sits.\n iris_L: { src: \"iris.png\", cx: 631, cy: 480, w: IRIS_W, mirror: false },\n iris_R: { src: \"iris.png\", cx: 469, cy: 480, w: IRIS_W, mirror: false },\n lash_L: {\n src: \"eyewhite_lash.png\",\n cx: 636,\n cy: 475,\n w: EYE_W,\n mirror: true,\n noTrim: true,\n },\n lash_R: { src: \"eyewhite_lash.png\", cx: 464, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n brow_L: { src: \"brow.png\", cx: 645, cy: 405, w: 105, mirror: false },\n brow_R: { src: \"brow.png\", cx: 455, cy: 405, w: 105, mirror: true },\n hair_front: { src: \"hair_front.png\", cx: 550, cy: 425, w: 660 },\n // The pose forearms, one drawing for both: forearm_pose_R (screen left)\n // takes forearm_pose.png as drawn and forearm_pose_L mirrors it, like the\n // arms. The rig draws them above the face and the hair, so they come last.\n // No cx/cy/w defaults: an unset `w` scales the forearm's elbow end to the\n // placed arm's elbow run, an unset `cx` or `cy` pins its elbow-end pivot\n // on the arm's elbow (ArmLayout). OPTIONAL and opt-in, like the arms.\n forearm_pose_L: { src: \"forearm_pose.png\", optional: true, mirror: true },\n forearm_pose_R: { src: \"forearm_pose.png\", optional: true, mirror: false },\n} satisfies Record<string, RoleLayout | NoseLayout | ArmLayout>;\n\nexport type Role = keyof typeof DEFAULT_LAYOUT;\n\n/** The lower lash of each eye, and the eye whose placement it takes. */\nconst LOWER_LASH = { lash_lower_L: \"eye_L\", lash_lower_R: \"eye_R\" } as const;\n/** The eyewhite's lower lid, split in memory like the sclera and lash. */\nconst LOWER_LASH_SRC = \"eyewhite_lash_lower.png\";\n\n/** A role the composer writes a layer for. */\nexport type LayerRole = Role | keyof typeof LOWER_LASH;\n\n/** The arm roles, placed off the body (ArmLayout). */\ntype ArmRole = \"arm_L\" | \"arm_R\";\n/** The pose forearm roles, placed off their arm's elbow (ArmLayout). */\ntype PoseRole = \"forearm_pose_L\" | \"forearm_pose_R\";\n\n/**\n * The merged layout, typed so a default other than the nose's, the arms' and\n * the pose forearms' that drops its `cy` fails to compile: `resolveLayout` builds it from\n * DEFAULT_LAYOUT.\n */\ntype ResolvedLayout = Record<\n Exclude<Role, \"nose\" | ArmRole | PoseRole>,\n RoleLayout\n> & {\n nose: NoseLayout;\n} & Record<ArmRole | PoseRole, ArmLayout>;\n\n/**\n * Draw order (back -> front): the roles of @ikijs/editor ROLE_TABLE the\n * composer writes, in its order — a test holds it to that subsequence.\n */\nexport const ORDER: LayerRole[] = [\n \"hair_back\",\n \"body\",\n \"arm_L\",\n \"arm_R\",\n \"face\",\n \"blush_L\",\n \"blush_R\",\n \"nose\",\n \"mouth\",\n \"mouth_open\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"lash_lower_L\",\n \"lash_lower_R\",\n \"lash_L\",\n \"lash_R\",\n \"brow_L\",\n \"brow_R\",\n \"hair_front\",\n \"forearm_pose_L\",\n \"forearm_pose_R\",\n];\n\n/**\n * The part files a parts dir holds: every source the layout reads from disk,\n * and the eyewhite the eye pair is split from in memory.\n */\nconst PART_FILES = [\n ...new Set(\n Object.values(DEFAULT_LAYOUT)\n .map((cfg) => cfg.src)\n .filter((src) => !src.startsWith(\"eyewhite_\")),\n ),\n EYEWHITE_SRC,\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: the layer an earlier run wrote for any role\n * this run does not write — a skipped role, or an arm once arm.png is gone\n * — is removed rather than left for the next tool to pick up.\n */\n outDir: string;\n layout?: LayoutOverride;\n /**\n * Part files to flip left-right as they are read, e.g. `[\"eyewhite.png\"]`\n * for an eye drawn facing the other way. It flips the SOURCE, so every role\n * cut from it flips together — the eye pair's sclera and lash stay in one\n * frame, which a per-role flag would leave to the caller to keep in sync.\n */\n mirrorParts?: string[];\n /**\n * The canvas's height in px: an even integer in CANVAS..MAX_CANVAS_DIM,\n * CANVAS (a square bust canvas) when omitted, and every output at CANVAS is\n * byte-identical to an omitted one. The width stays CANVAS. The canvas grows\n * downward: every default and every override keeps its canvas px from the\n * top-left, so the head lands where it does on a bust and a full body gets\n * room below. Model space is centred on the canvas, so an odd height, which\n * would put the head on a half pixel, is refused.\n */\n canvasHeight?: number;\n}\n\nexport interface ComposedLayer {\n role: LayerRole;\n path: string;\n /** Size of the placed part itself (the file is always CANVAS x the canvas\n * height). */\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 /**\n * Roles whose optional part was absent from the parts dir, and the lower\n * lashes when the eyewhite draws no dark lower lid. The arms and the\n * pose forearms are opt-in and never listed: a parts dir without\n * arm.png composes as a bust does, though an earlier compose's arm\n * layers are still removed.\n */\n skipped: LayerRole[];\n /** The rest pose, flattened: a pose forearm is invisible there, so it\n * never shows in this one. */\n preview: string;\n /** Written only with a pose forearm: the switch at 1 as the rig draws\n * it — each arm with a pose forearm cropped to the rows above its\n * elbow (the hanging forearm hidden), the pose forearms over\n * everything. */\n previewPose?: string;\n measure: MeasureReport;\n }\n | { ok: false; error: string };\n\n/**\n * The roles drawn on the face, but the nose (resolveLayout places it on its\n * own). Their defaults are placed relative to the face's: a layout that moves\n * or scales the face carries them with it.\n */\nconst FACE_FEATURES = [\n \"blush_L\",\n \"blush_R\",\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] as const satisfies readonly Exclude<Role, \"nose\">[];\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 or height fails fast,\n * path-qualified, before any decode. `w` is capped at the canvas's width and\n * `h` at its height, so a part sized whole can never exceed the canvas width\n * (a nose, sized by its core, is checked in partBuffer); `cx`/`cy` are\n * unbounded here because a part may legitimately hang off an edge —\n * assertOnCanvas() rejects the one that lands nowhere on it.\n *\n * The face's override applies first. Each feature's default is then moved\n * with the face's centre and scaled by its width against the default face's,\n * so the defaults are proportions of the face; a feature's own override still\n * names canvas px.\n */\nfunction resolveLayout(\n overrides: LayoutOverride | undefined,\n canvas: Canvas,\n): ResolvedLayout {\n const resolved: ResolvedLayout = { ...DEFAULT_LAYOUT };\n if (overrides === undefined) return resolved;\n const sets = new Map<\n Role,\n { cx?: number; cy?: number; w?: number; h?: number }\n >();\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 // Only the fields the override sets: spread over the entry, an explicit\n // undefined would erase the default it leaves alone.\n const set: { cx?: number; cy?: number; w?: number; h?: number } = {};\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 set[field] = value;\n }\n for (const field of [\"w\", \"h\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n const max = field === \"w\" ? canvas.width : canvas.height;\n if (!Number.isInteger(value) || value < 1 || value > max) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be an integer in 1..${max}, got ${String(value)}`,\n );\n }\n set[field] = value;\n }\n sets.set(role as Role, set);\n }\n const face = { ...resolved.face, ...sets.get(\"face\") };\n resolved.face = face;\n const base = DEFAULT_LAYOUT.face;\n const scale = face.w / base.w;\n const x = (cx: number) => face.cx + (cx - base.cx) * scale;\n const w = (width: number) => Math.max(1, Math.round(width * scale));\n for (const role of FACE_FEATURES) {\n const d = DEFAULT_LAYOUT[role];\n const cy = face.cy + (d.cy - base.cy) * scale;\n resolved[role] = { ...d, cx: x(d.cx), cy, w: w(d.w), ...sets.get(role) };\n }\n // The nose has no default cy (the tip rule places it, off the eye and\n // mouth rows above), so it merges on its own.\n const nose = DEFAULT_LAYOUT.nose;\n resolved.nose = {\n ...nose,\n cx: x(nose.cx),\n w: w(nose.w),\n ...sets.get(\"nose\"),\n };\n for (const [role, set] of sets) {\n if (role === \"face\" || role === \"nose\") continue;\n if ((FACE_FEATURES as readonly Role[]).includes(role)) continue;\n mergeRole(resolved, role, set);\n }\n return resolved;\n}\n\n/**\n * Merge an override's set fields onto a role's resolved entry. Generic over\n * the role so one statement types for every kind of entry, the arms' among\n * them, whose cx/cy/w may stay unset.\n */\nfunction mergeRole<R extends Role>(\n resolved: ResolvedLayout,\n role: R,\n set: { cx?: number; cy?: number; w?: number; h?: number },\n): void {\n resolved[role] = { ...resolved[role], ...set };\n}\n\n/**\n * Input boundary for `canvasHeight`: an even integer in CANVAS..MAX_CANVAS_DIM,\n * CANVAS when omitted. Model space is centred on the canvas, so an odd height\n * would put the head on a half pixel.\n */\nfunction resolveCanvasHeight(value: number | undefined): number {\n if (value === undefined) return CANVAS;\n if (\n !Number.isInteger(value) ||\n value % 2 !== 0 ||\n value < CANVAS ||\n value > MAX_CANVAS_DIM\n ) {\n throw new AutoRigInputError(\n `canvasHeight must be an even integer in ${CANVAS}..${MAX_CANVAS_DIM}, got ${String(value)}`,\n );\n }\n return value;\n}\n\n/**\n * Input boundary for `mirrorParts`: a name that is not a part file (a typo, or\n * a role such as `eye_L`) would otherwise flip nothing and read as success.\n */\nfunction resolveMirrorParts(names: string[] | undefined): Set<string> {\n const mirrored = new Set<string>();\n for (const [i, name] of (names ?? []).entries()) {\n if (!PART_FILES.includes(name)) {\n throw new AutoRigInputError(\n `mirrorParts[${i}]: unknown part ${JSON.stringify(name)} — expected one of ${PART_FILES.join(\", \")}`,\n );\n }\n mirrored.add(name);\n }\n return mirrored;\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/** A PNG part's dense core (`null` when no pixel reaches the core's alpha)\n * and its own bounds, both in its own px. */\nasync function coreAndBoundsOf(\n png: Buffer,\n): Promise<{ core: Box | null; bounds: Box }> {\n const { data, info } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return {\n core: denseCoreOf(data, info.width, info.height),\n bounds: { x: 0, y: 0, w: info.width, h: info.height },\n };\n}\n\n/** Whether a part keeps a pixel the auto-rig counts as coverage. */\nasync function hasCoverage(png: Buffer): Promise<boolean> {\n const { data, info } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return scanAlphaBbox(data, info.width, info.height) !== null;\n}\n\n/** What a nose part's layout sizes, decided on the trimmed source part. */\ninterface NoseSizing {\n /** The box layout `w`/`h` size, in the trimmed source part's px (not the\n * resized part's). */\n box: Box;\n /** The whole part stood in for the core: it has none, or it is a speck. */\n whole: boolean;\n /** The core's and the part's sizes when a speck was the reason. */\n speck?: NoseSpeck;\n}\n\n/**\n * What a nose part's layout sizes: its dense core, in its own px — or its own\n * bounds, so it is sized and placed whole, when no pixel reaches the core's\n * alpha (a nose painted wholly translucent) or the core is a speck of those\n * bounds (`isSpeckCore`).\n */\nasync function noseSizingOf(png: Buffer): Promise<NoseSizing> {\n const { core, bounds } = await coreAndBoundsOf(png);\n if (core === null) return { box: bounds, whole: true };\n if (isSpeckCore(core, bounds)) {\n return {\n box: bounds,\n whole: true,\n speck: {\n core: { w: core.w, h: core.h },\n part: { w: bounds.w, h: bounds.h },\n },\n };\n }\n return { box: core, whole: false };\n}\n\n/** A part trimmed and flipped, not yet resized: a PNG and its size. */\ninterface Trimmed {\n data: Buffer;\n w: number;\n h: number;\n}\n\n/**\n * Trim/mirror a part, ready to be resized (`sizedPart`). `inMemory` carries\n * the eye pair's two split buffers; every other role is read from the parts\n * dir. `flipSource` is a `mirrorParts` entry for the file the role is cut\n * from. A pose forearm is measured between this and the resize, to learn the\n * width that fits it to its arm.\n * Missing optional part -> null; missing required part -> AutoRigInputError.\n */\nasync function trimmedPart(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\" | \"w\">,\n partsDir: string,\n inMemory: Buffer | undefined,\n flipSource: boolean,\n): Promise<Trimmed | 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 // An optional role's part may be absent from the parts dir; the\n // 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\n // bbox, less any stray speck beside the drawing.\n if (!cfg.noTrim) {\n // The rest of the pipeline reads this trimmed raw, so the source is\n // decoded and trimmed once. Only file sources are trimmed, and they are\n // raw already, so a part with no stray speck composes byte-identically.\n const kept = await img\n .trim({ threshold: TRIM_THRESHOLD })\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const { width: keptW, height: keptH } = kept.info;\n img = sharp(kept.data, {\n raw: { width: keptW, height: keptH, channels: 4 },\n });\n const box = boxWithoutStraySpecks(kept.data, keptW, keptH);\n if (box !== null) img = img.extract(box);\n }\n // A flipped source under a mirrored role cancels out. sharp's flop() sets a\n // flag rather than toggling it, so the two cannot simply be applied in turn.\n if ((cfg.mirror ?? false) !== flipSource) img = img.flop();\n // Materialise the trimmed part BEFORE resizing: its size is bounded by the\n // source decode limit, so the size 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 return {\n data: trimmed.data,\n w: trimmed.info.width,\n h: trimmed.info.height,\n };\n}\n\n/**\n * Resize a trimmed part to its layout width. The nose is resized so its dense\n * core, not its whole part, comes out `w` wide (and `h` tall when set),\n * unless its whole part stood in for the core. Either way the nose's sizing\n * decision (`noseSizingOf`) always comes back as `nose`, and no other role\n * has one.\n */\nasync function sizedPart(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\">,\n trimmed: Trimmed,\n canvas: Canvas,\n): Promise<{ buf: Buffer; w: number; h: number; nose?: NoseSizing }> {\n const { w: trimmedW, h: trimmedH } = trimmed;\n // What `w`/`h` size: the nose's dense core, measured on the trimmed, flipped\n // part — the whole part scales with it, feather and all — or that whole\n // part when it has no core or the core is a speck, and every other role's\n // whole part.\n const nose = role === \"nose\" ? await noseSizingOf(trimmed.data) : undefined;\n const sized = nose?.box ?? { x: 0, y: 0, w: trimmedW, h: trimmedH };\n const width = Math.round((trimmedW * cfg.w) / sized.w);\n const height =\n cfg.h === undefined\n ? Math.round((trimmedH * width) / trimmedW)\n : Math.round((trimmedH * cfg.h) / sized.h);\n // resolveLayout bounds w and an explicit h, so for a part sized whole only\n // the aspect-derived height can run past the canvas; a nose sized by its\n // core can overrun either dimension.\n if (width > canvas.width || height > canvas.height) {\n const field = width > canvas.width || cfg.h === undefined ? \"w\" : \"h\";\n throw new AutoRigInputError(\n `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${canvasName(canvas)} canvas`,\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(cfg.h === undefined ? { width } : { width, height, fit: \"fill\" })\n .png()\n .toBuffer({ resolveWithObject: true });\n return {\n buf: resized.data,\n w: resized.info.width,\n h: resized.info.height,\n nose,\n };\n}\n\n/**\n * Trim/mirror a part and resize it to its layout width: `trimmedPart` then\n * `sizedPart`. Missing optional part -> null; missing required part ->\n * AutoRigInputError.\n */\nasync function partBuffer(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\">,\n partsDir: string,\n inMemory: Buffer | undefined,\n flipSource: boolean,\n canvas: Canvas,\n): Promise<{ buf: Buffer; w: number; h: number; nose?: NoseSizing } | null> {\n const trimmed = await trimmedPart(role, cfg, partsDir, inMemory, flipSource);\n return trimmed === null ? null : sizedPart(role, cfg, trimmed, canvas);\n}\n\n/**\n * Refuse a placed part that lands nowhere on the canvas. Running off an edge is\n * legitimate — a bust's `body` is meant to be cut off by the canvas bottom — so\n * the test is INTERSECTION, not containment. A part that misses the canvas\n * entirely 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 assertOnCanvas(\n source: string,\n w: number,\n h: number,\n left: number,\n top: number,\n canvas: Canvas,\n): void {\n if (\n left + w <= 0 ||\n top + h <= 0 ||\n left >= canvas.width ||\n top >= canvas.height\n ) {\n throw new AutoRigInputError(\n `${source}: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${canvasName(canvas)} canvas`,\n );\n }\n}\n\n/** Where a part lands, centred on its layout cx/cy. The nose has its own. */\nfunction placement(\n role: Exclude<Role, \"nose\" | ArmRole | PoseRole>,\n cfg: RoleLayout,\n w: number,\n h: number,\n canvas: Canvas,\n) {\n const left = Math.round(cfg.cx - w / 2);\n const top = Math.round(cfg.cy - h / 2);\n assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);\n return { left, top };\n}\n\n/**\n * Where the nose lands: by the box it was sized by (`noseSizingOf`), in the\n * resized part's px — its dense core, or its whole bounds when those stood in.\n * `cx` centres the box's columns. A set `cy` centres its rows; absent, its\n * bottom row — the tip, the last row index at alpha ≥ 128 — lands on\n * round(E + NOSE_TIP_AT·(M − E)), E the eyes' mean row and M the mouth's. A\n * box's centre is `x + w/2`, as placement() takes it: pixel x covers\n * [x, x + 1).\n */\nfunction nosePlacement(\n layout: ResolvedLayout,\n box: Box,\n w: number,\n h: number,\n canvas: Canvas,\n) {\n const { cx, cy } = layout.nose;\n const left = Math.round(cx - (box.x + box.w / 2));\n let top: number;\n if (cy !== undefined) {\n top = Math.round(cy - (box.y + box.h / 2));\n } else {\n const eyeRow = (layout.eye_L.cy + layout.eye_R.cy) / 2;\n const tipRow = Math.round(\n eyeRow + NOSE_TIP_AT * (layout.mouth.cy - eyeRow),\n );\n top = tipRow - (box.y + box.h - 1);\n }\n assertOnCanvas(\n cy !== undefined\n ? \"layout.nose.cx/cy\"\n : \"layout.nose.cx/cy (cy unset: its tip row comes from layout.eye_L/eye_R/mouth.cy)\",\n w,\n h,\n left,\n top,\n canvas,\n );\n return { left, top };\n}\n\nfunction blankCanvas(canvas: Canvas) {\n return sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n });\n}\n\n/** Luma (0..255) of the RGBA pixel at byte offset `i`. */\nfunction luma(rgba: Buffer, i: number): number {\n return 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];\n}\n\n/**\n * The box of a trimmed part without its stray specks, or null when no stray\n * speck lies outside its drawing. The part's kept pixels (alpha over\n * TRIM_THRESHOLD, the trim's own cut) form 8-connected sets; a stray speck is\n * a set that never reaches ALPHA_OPAQUE and holds under STRAY_SPECK_FRACTION of\n * them, the residue a background removal leaves beside a drawing. Kept, one\n * such speck widened a generated body's box by 70 px on one side and placed\n * the body 32 px off its centre. A drawn stroke reaches ALPHA_OPAQUE, so a\n * detached wisp or strand is never dropped, and a part painted wholly under\n * it (a soft blush) drops nothing.\n */\nfunction boxWithoutStraySpecks(\n rgba: Buffer,\n W: number,\n H: number,\n): { left: number; top: number; width: number; height: number } | null {\n const n = W * H;\n // The share is of the whole part, so count it before any set is judged.\n let kept = 0;\n for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] > TRIM_THRESHOLD) kept++;\n // Each set is judged as its fill ends and only its box is kept, so memory\n // is a byte per pixel plus a stack grown to the deepest fill, not a label\n // per pixel and a record per set. A pixel is marked as it is pushed, so the\n // stack never outgrows the image.\n const visited = new Uint8Array(n);\n let stack = new Int32Array(1024);\n // [left, top, right, bottom] of the drawing's sets and of the stray ones.\n const drawing = [W, H, -1, -1];\n const strays = [W, H, -1, -1];\n let anyOpaque = false;\n for (let start = 0; start < n; start++) {\n if (visited[start] || rgba[start * 4 + 3] <= TRIM_THRESHOLD) continue;\n let setLeft = W;\n let setTop = H;\n let setRight = -1;\n let setBottom = -1;\n let size = 0;\n let opaque = false;\n let depth = 0;\n visited[start] = 1;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n if (rgba[p * 4 + 3] >= ALPHA_OPAQUE) opaque = true;\n const px = p % W;\n const py = (p - px) / W;\n setLeft = Math.min(setLeft, px);\n setTop = Math.min(setTop, py);\n setRight = Math.max(setRight, px);\n setBottom = Math.max(setBottom, py);\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n const q = y * W + x;\n if (!visited[q] && rgba[q * 4 + 3] > TRIM_THRESHOLD) {\n visited[q] = 1;\n if (depth === stack.length) {\n const grown = new Int32Array(Math.min(n, stack.length * 2));\n grown.set(stack);\n stack = grown;\n }\n stack[depth++] = q;\n }\n }\n }\n }\n anyOpaque ||= opaque;\n const into =\n !opaque && size < kept * STRAY_SPECK_FRACTION ? strays : drawing;\n into[0] = Math.min(into[0], setLeft);\n into[1] = Math.min(into[1], setTop);\n into[2] = Math.max(into[2], setRight);\n into[3] = Math.max(into[3], setBottom);\n }\n if (!anyOpaque || strays[2] < 0) return null;\n const [left, top, right, bottom] = drawing;\n // A set's box reaches past the drawing's only where one of its pixels does,\n // and a speck inside the drawing's box moves nothing, so it is left be.\n if (\n strays[0] >= left &&\n strays[1] >= top &&\n strays[2] <= right &&\n strays[3] <= bottom\n )\n return null;\n return { left, top, width: right - left + 1, height: bottom - top + 1 };\n}\n\n/**\n * The eyewhite's light ink drawn detached above its white, as a row-major\n * mask (1 = detached). Light ink is non-transparent at luma EYE_LASH_LUMA or\n * over. Its sets are 8-connected through visibly painted pixels only (alpha\n * ALPHA_OPAQUE or over), so a faint antialiased pixel between a crease and\n * the white does not join them. Each fainter pixel is fringe of the nearest\n * painted set it reaches through faint pixels whose alpha never rises on the\n * way (ties go to the set met first in row-major order, the higher one).\n * Antialiasing fades away from what it edges, so a translucent stroke past a\n * fainter halo does not become the fringe of the set the halo edges. Faint\n * ink that no painted set reaches this way forms sets of its own. So does a\n * noisy faint pixel brighter than every claimed neighbour and touching no\n * painted pixel: above the white's top, it is dropped. The white is the\n * largest painted set. Another set is detached above it when each of its own\n * pixels, fringe aside, lies above the white's topmost painted pixel in its\n * column, or, past either end of the white, above the top of that end's\n * column; it goes with its fringe. A crease often runs on past the eye's\n * corners, and judged only over the white, one pixel out there would keep\n * the whole crease. A shade painted on the white touches it, so it is part\n * of the white; a mark below the white, or beside an end and level with it,\n * is left.\n */\nfunction detachedAboveWhite(rgba: Buffer, W: number, H: number): Uint8Array {\n const n = W * H;\n // 2 = painted light ink, 1 = fainter light ink, 0 = neither.\n const ink = new Uint8Array(n);\n for (let p = 0; p < n; p++) {\n const alpha = rgba[p * 4 + 3];\n if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)\n ink[p] = alpha >= ALPHA_OPAQUE ? 2 : 1;\n }\n const label = new Int32Array(n).fill(-1);\n // A pixel is labelled as it is pushed, so it is pushed once and neither the\n // flood fill's stack nor the fringe's queue outgrows the image.\n const stack = new Int32Array(n);\n const near = (p: number, visit: (q: number) => void) => {\n const px = p % W;\n const py = (p - px) / W;\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n visit(y * W + x);\n }\n }\n };\n const sizes: number[] = [];\n const fill = (start: number) => {\n const id = sizes.length;\n let size = 0;\n let depth = 0;\n label[start] = id;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n near(p, (q) => {\n if (ink[q] === ink[start] && label[q] === -1) {\n label[q] = id;\n stack[depth++] = q;\n }\n });\n }\n sizes.push(size);\n };\n for (let p = 0; p < n; p++) if (ink[p] === 2 && label[p] === -1) fill(p);\n const paintedSets = sizes.length;\n // The fringe: breadth-first from every painted pixel at once, each faint\n // pixel no more opaque than the one before taking the set that reaches it\n // first.\n let head = 0;\n let tail = 0;\n for (let p = 0; p < n; p++) if (ink[p] === 2) stack[tail++] = p;\n while (head < tail) {\n const p = stack[head++];\n near(p, (q) => {\n if (\n ink[q] === 1 &&\n label[q] === -1 &&\n rgba[q * 4 + 3] <= rgba[p * 4 + 3]\n ) {\n label[q] = label[p];\n stack[tail++] = q;\n }\n });\n }\n for (let p = 0; p < n; p++) if (ink[p] === 1 && label[p] === -1) fill(p);\n\n const detached = new Uint8Array(n);\n if (paintedSets === 0 || sizes.length < 2) return detached;\n let white = 0;\n for (let id = 1; id < paintedSets; id++) {\n if (sizes[id] > sizes[white]) white = id;\n }\n // A set's own pixels: a painted set's painted ones, a faint set's all.\n const own = (p: number) => ink[p] === 2 || label[p] >= paintedSets;\n // The white's topmost painted row per column (the scan is row-major, so\n // the first pixel met is the top).\n const whiteTop = new Int32Array(W).fill(-1);\n for (let p = 0; p < n; p++) {\n const x = p % W;\n if (label[p] === white && own(p) && whiteTop[x] === -1)\n whiteTop[x] = (p - x) / W;\n }\n // An 8-connected set covers one unbroken run of columns, so every column\n // the white misses lies past one of its ends and takes that end's top.\n let first = 0;\n while (whiteTop[first] === -1) first++;\n let last = W - 1;\n while (whiteTop[last] === -1) last--;\n whiteTop.fill(whiteTop[first], 0, first);\n whiteTop.fill(whiteTop[last], last + 1);\n const above = new Uint8Array(sizes.length).fill(1);\n for (let p = 0; p < n; p++) {\n const id = label[p];\n if (id === -1 || id === white || !own(p)) continue;\n const x = p % W;\n if ((p - x) / W >= whiteTop[x]) above[id] = 0;\n }\n for (let p = 0; p < n; p++) {\n const id = label[p];\n if (id !== -1 && id !== white && above[id]) detached[p] = 1;\n }\n return detached;\n}\n\n/**\n * Split eyewhite.png (white almond + dark lashes) into a sclera (the upper\n * lash recolored to white; the whole drawing's alpha = the blink clip-mask\n * shape), a dark UPPER-lash layer and a dark LOWER-lid layer. All are cropped\n * to the SAME eye bbox so they stay aligned (consumed with noTrim): the lash\n * arc keeps its position at the top of the sclera, so on blink it folds DOWN\n * over the eye rather than the eye shrinking in place.\n *\n * The lower lid's dark line and lashes stay in the sclera as drawn and are\n * copied into their own layer, which draws over the iris. Recolored white they\n * would show as white flicks wherever a lash hangs below the white, and left\n * in the sclera alone the iris would paint over the line. The sclera keeps\n * them so its alpha, which the rig measures the eye by, is the drawing's.\n * `lashLower` is null when the eyewhite draws no dark pixel below the upper\n * lash's fraction.\n *\n * A light mark drawn detached above the white, such as a double-eyelid crease,\n * is dropped from the sclera (`detachedAboveWhite`). The sclera is the iris's\n * clip, and at half blink the fold carries such a mark down into the iris's\n * path. The frame is still the source's alpha bbox, crease and all, so the\n * layout places the pair where it did before.\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; lashLower: Buffer | null }> {\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 // Dark pixels above this row are the upper lash; below it, the lower lid.\n const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);\n const detached = detachedAboveWhite(data, W, H);\n\n const sclera = Buffer.from(data);\n const lash = Buffer.from(data);\n const lashLower = Buffer.from(data);\n let lowerInk = false;\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 isDark = data[i + 3] > 0 && luma(data, i) < EYE_LASH_LUMA;\n const upper = y <= lashCutoffY;\n if (isDark && upper) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255; // dark -> white\n if (detached[y * W + x]) sclera[i + 3] = 0;\n if (!(isDark && upper)) lash[i + 3] = 0;\n if (isDark && !upper) lowerInk = true;\n else lashLower[i + 3] = 0;\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 lashLower: lowerInk ? await cropToBuffer(lashLower, W, H, region) : null,\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 // Before anything decodes, like every other input check.\n const canvas: Canvas = {\n width: CANVAS,\n height: resolveCanvasHeight(input.canvasHeight),\n };\n const layout = resolveLayout(input.layout, canvas);\n const mirrored = resolveMirrorParts(input.mirrorParts);\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 if (split.lashLower !== null) {\n splitSources.set(LOWER_LASH_SRC, split.lashLower);\n }\n\n // Place every role before writing any: a rejected placement must leave\n // outDir as the last compose left it, not half overwritten.\n const placed: {\n role: LayerRole;\n part: { buf: Buffer; w: number; h: number };\n left: number;\n top: number;\n /** An arm's, for a pose forearm to hang from: the rig's elbow pivot on\n * the canvas and the elbow seam's run, px. */\n elbow?: { x: number; y: number };\n elbowRun?: number;\n }[] = [];\n const skipped: LayerRole[] = [];\n // Compose's verdict on the nose's source part when its core was a speck,\n // for the report; otherwise the report judges the composed nose layer.\n let noseSpeck: NoseSpeck | undefined;\n for (const role of ORDER) {\n // A lower lash is placed by its eye's layout, on the sclera's frame.\n const lower = role === \"lash_lower_L\" || role === \"lash_lower_R\";\n const key: Role = lower ? LOWER_LASH[role] : role;\n if (lower && split.lashLower === null) {\n skipped.push(role);\n continue;\n }\n if (key === \"arm_L\" || key === \"arm_R\") {\n const arm = layout[key];\n // Arms are opt-in: a parts dir without arm.png composes as a bust\n // does, the arms neither placed nor listed in `skipped`.\n if (!fs.existsSync(path.join(partsDir, arm.src))) continue;\n const body = placed.find((p) => p.role === \"body\");\n if (body === undefined) {\n throw new AutoRigInputError(\n \"arm.png: an arm needs body.png — the composer hangs each arm on the body's shoulder, and auto_rig_from_layers hangs it from the body\",\n );\n }\n const w = arm.w ?? Math.max(1, Math.round(ARM_WIDTH * body.part.w));\n // Never null: the part is there, checked above.\n const part = (await partBuffer(\n role,\n { ...arm, w },\n partsDir,\n undefined,\n mirrored.has(arm.src),\n canvas,\n ))!;\n const { left, top, elbow, elbowRun } = await armPlacement(\n key,\n arm,\n part,\n {\n left: body.left,\n top: body.top,\n w: body.part.w,\n h: body.part.h,\n },\n );\n const unset = ([\"cx\", \"cy\"] as const).filter(\n (field) => arm[field] === undefined,\n );\n assertOnCanvas(\n unset.length === 0\n ? `layout.${key}.cx/cy`\n : `layout.${key}.cx/cy (${unset.join(\"/\")} unset: its shoulder pivot hangs on the shoulder corner of layout.body's box)`,\n part.w,\n part.h,\n left,\n top,\n canvas,\n );\n placed.push({ role, part, left, top, elbow, elbowRun });\n continue;\n }\n if (key === \"forearm_pose_L\" || key === \"forearm_pose_R\") {\n const pose = layout[key];\n // Opt-in like the arms: neither placed nor listed in `skipped`.\n if (!fs.existsSync(path.join(partsDir, pose.src))) continue;\n const armRole = key === \"forearm_pose_L\" ? \"arm_L\" : \"arm_R\";\n const arm = placed.find((p) => p.role === armRole);\n if (arm?.elbow === undefined || arm.elbowRun === undefined) {\n throw new AutoRigInputError(\n \"forearm_pose.png: a pose forearm needs arm.png — the composer pins it on the arm's elbow, and auto_rig_from_layers hangs it from the arm\",\n );\n }\n // Never null: the part is there, checked above.\n const trimmed = (await trimmedPart(\n role,\n pose,\n partsDir,\n undefined,\n mirrored.has(pose.src),\n ))!;\n const w =\n pose.w ?? (await forearmPoseWidth(key, trimmed, arm.elbowRun));\n let part;\n try {\n part = await sizedPart(role, { ...pose, w }, trimmed, canvas);\n } catch (err) {\n // A derived w the user never set is not blamed on the layout key.\n if (pose.w === undefined && err instanceof AutoRigInputError) {\n throw new AutoRigInputError(\n err.message.replace(\n `layout.${role}.w:`,\n `layout.${role}.w (unset: scaled to ${armRole}'s elbow run):`,\n ),\n );\n }\n throw err;\n }\n const { left, top } = await forearmPosePlacement(\n key,\n pose,\n part,\n arm.elbow,\n );\n const unset = ([\"cx\", \"cy\"] as const).filter(\n (field) => pose[field] === undefined,\n );\n assertOnCanvas(\n unset.length === 0\n ? `layout.${key}.cx/cy`\n : `layout.${key}.cx/cy (${unset.join(\"/\")} unset: its elbow-end pivot hangs on the elbow of layout.${armRole}'s placed arm)`,\n part.w,\n part.h,\n left,\n top,\n canvas,\n );\n placed.push({ role, part, left, top });\n continue;\n }\n const cfg = lower ? { ...layout[key], src: LOWER_LASH_SRC } : layout[key];\n const inMemory = splitSources.get(cfg.src);\n const part = await partBuffer(\n role,\n cfg,\n partsDir,\n inMemory,\n // The split halves are cut from eyewhite.png, the file a caller names.\n mirrored.has(inMemory === undefined ? cfg.src : EYEWHITE_SRC),\n canvas,\n );\n // A lower lid too faint for the alpha the rig reads coverage at, or\n // that the resize erased, would be a layer it refuses as empty.\n if (part === null || (lower && !(await hasCoverage(part.buf)))) {\n skipped.push(role);\n continue;\n }\n // The nose is placed by the box it was sized by. A whole part that stood\n // in is placed by the resized part's own bounds. A core is measured\n // again on the resized part rather than scaled, since resampling moves\n // its edges and the tip rule lands its exact bottom row — and is not\n // judged again here: the source part's verdict decided how it was sized.\n let left: number;\n let top: number;\n if (key === \"nose\") {\n noseSpeck = part.nose?.speck;\n const { core, bounds } = await coreAndBoundsOf(part.buf);\n const box = part.nose?.whole ? bounds : (core ?? bounds);\n ({ left, top } = nosePlacement(layout, box, part.w, part.h, canvas));\n } else {\n ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));\n }\n // The eye pair's halves are cut from one eyewhite into one frame. Set\n // apart, the blink fold tears — and a lash narrowed inside its sclera\n // still lies on it and inks its top row, so nothing in the composed\n // layers would show it. Compared as placed, not as set: an h equal to\n // the one the aspect gives lands on the same frame as leaving it unset.\n if (role === \"lash_L\" || role === \"lash_R\") {\n const eyeRole = role === \"lash_L\" ? \"eye_L\" : \"eye_R\";\n const eye = placed.find((p) => p.role === eyeRole);\n if (\n eye !== undefined &&\n (eye.left !== left ||\n eye.top !== top ||\n eye.part.w !== part.w ||\n eye.part.h !== part.h)\n ) {\n throw new AutoRigInputError(\n `layout.${role} places the lash at ${part.w}x${part.h} (${left},${top}), but layout.${eyeRole} ` +\n `places its sclera at ${eye.part.w}x${eye.part.h} (${eye.left},${eye.top}) — they are cut from one ` +\n `eyewhite into one frame, and the blink fold tears where they part. Set cx/cy/w/h the same on both.`,\n );\n }\n }\n placed.push({ role, part, left, top });\n }\n\n // Drop the layer an earlier compose into the same dir wrote for each role\n // this run does not write — a skipped one, or an arm once arm.png is\n // gone: left behind it would contradict the result, since measureDir\n // globs the 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 for (const role of ORDER) {\n if (placed.some((p) => p.role === role)) continue;\n fs.rmSync(path.join(outDir, `${role}.png`), { force: true });\n }\n // The pose preview exists only with a pose forearm, so it is swept with\n // the layers: left behind it would show a forearm the layers no longer\n // hold.\n const posed = (role: LayerRole) =>\n role === \"forearm_pose_L\" || role === \"forearm_pose_R\";\n if (!placed.some((p) => posed(p.role))) {\n fs.rmSync(path.join(outDir, \"preview-pose.png\"), { force: true });\n }\n const layers: ComposedLayer[] = [];\n const preview: { input: Buffer; left: number; top: number }[] = [];\n for (const { role, part, left, top } of placed) {\n // role layer: this part alone on a full canvas at its position.\n const layer = await blankCanvas(canvas)\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 if (!posed(role)) 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.width,\n height: canvas.height,\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 // The switch at 1, as the rig draws it: an arm whose side has a pose\n // forearm keeps the rows above its elbow (the upper arm and the sleeve;\n // the hanging forearm hides), and the pose forearms, last in `placed`,\n // draw over everything.\n let previewPosePath: string | undefined;\n if (placed.some((p) => posed(p.role))) {\n const pose: { input: Buffer; left: number; top: number }[] = [];\n for (const { role, part, left, top, elbow } of placed) {\n const armPosed =\n elbow !== undefined &&\n placed.some(\n (p) =>\n p.role ===\n (role === \"arm_L\" ? \"forearm_pose_L\" : \"forearm_pose_R\"),\n );\n if (!armPosed) {\n pose.push({ input: part.buf, left, top });\n continue;\n }\n const rows = Math.min(part.h, Math.max(1, Math.round(elbow.y - top)));\n pose.push({\n input: await sharp(part.buf)\n .extract({ left: 0, top: 0, width: part.w, height: rows })\n .png()\n .toBuffer(),\n left,\n top,\n });\n }\n const posePng = await sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 245, g: 245, b: 248, alpha: 1 },\n },\n })\n .composite(pose)\n .png()\n .toBuffer();\n previewPosePath = path.join(outDir, \"preview-pose.png\");\n writeFileAtomic(previewPosePath, posePng);\n }\n\n return {\n ok: true,\n outDir,\n layers,\n skipped,\n preview: previewPath,\n ...(previewPosePath === undefined\n ? {}\n : { previewPose: previewPosePath }),\n measure: await measureDir(outDir, noseSpeck),\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, detectAlphaBbox } from \"./node-images\";\nimport { AutoRigInputError, MAX_LAYERS, resolveInputDir } from \"./limits\";\nimport { ARM_ROLES, armWarnings } from \"./measure-arms\";\nimport { POSE_ROLES, forearmPoseWarnings } from \"./measure-forearm-pose\";\nimport { SPECK_CORE_FRACTION, denseCoreOf, isSpeckCore } from \"./measure-turn\";\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/** Share of a lash's opaque pixels tolerated off its sclera. In sync there\n * are none — the sclera was recoloured from those very pixels. A real eye\n * measured 0 of 934 in sync, then 6-12 at a 1 px drift, 45-50 at 2 px and\n * 104-110 at 4 px, whichever way it drifted. */\nconst LASH_STRAY_TOL_FRAC = 0.02;\n/** How much further short of the outer corner than of the nose side an eye's\n * lash may stop, as a fraction of the eye width, before the eye reads as\n * drawn facing the other way. Three real eyewhites drawn reversed stopped\n * 4.0-6.1% further short there; one drawn the right way stops short at the\n * nose side instead, and one with a wing at each end at neither. */\nconst EYE_FACING_TOL_FRAC = 0.02;\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/** An arm's seams show once it raises, every other part's on the head turn. A\n * pose forearm raises with its arm, and shows only once the switch is on. */\nconst isArm = (role: string) =>\n (ARM_ROLES as readonly string[]).includes(role) ||\n (POSE_ROLES as readonly string[]).includes(role);\n\n/** A nose's dense core that `isSpeckCore` judged a speck of its part, as sizes\n * in px: compose's verdict on the trimmed source part, or the composed\n * layer's against its crop. */\nexport interface NoseSpeck {\n core: { w: number; h: number };\n part: { w: number; h: number };\n}\n\n/**\n * The nose-speck warning. Each source says only what its own reader did:\n * `\"compose\"` judged the trimmed source part, before resampling, and composed\n * it whole; `\"layer\"` judged the layer file against its crop, which is what\n * `auto_rig_from_layers` reads. The remedy is the same either way.\n */\nfunction noseSpeckWarning(\n { core, part }: NoseSpeck,\n source: \"compose\" | \"layer\",\n): string {\n const [found, consequence] =\n source === \"compose\"\n ? [\n `the source part's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} trimmed part`,\n `compose_layers_from_parts sized and placed the whole part instead — layout.nose's w and h now size it, feather included`,\n ]\n : [\n `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,\n `auto_rig_from_layers turns and tilts the nose about its whole crop instead`,\n ];\n return (\n `nose: ${found} — under ${SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril ` +\n `mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with ` +\n `its shading painted denser, so the drawing itself reaches alpha 128. Billed.`\n );\n}\n\n/**\n * Count the lash's opaque pixels, and those of them that land where its\n * sclera is transparent. Both are canvas-sized layers, so a pixel's position\n * is the same canvas point in each.\n */\nasync function lashOffSclera(\n eyePath: string,\n lashPath: string,\n): Promise<{ opaque: number; off: number }> {\n const eye = await decodePng(eyePath);\n const lash = await decodePng(lashPath);\n let opaque = 0;\n let off = 0;\n for (let y = 0; y < lash.height; y++) {\n for (let x = 0; x < lash.width; x++) {\n if (lash.rgba[(y * lash.width + x) * 4 + 3] < 128) continue;\n opaque++;\n const onEye = x < eye.width && y < eye.height;\n if (!onEye || eye.rgba[(y * eye.width + x) * 4 + 3] <= 8) off++;\n }\n }\n return { opaque, off };\n}\n\n/**\n * Measure every `*.png` in an already-resolved layers directory but the\n * `preview*.png` ones (`preview.png` is the composer's contact sheet, and a\n * caller's own previews sit beside it; none is a role) and run the geometry\n * checks.\n * `noseSpeck` is compose's own verdict on the nose's source part when that\n * part's core was a speck, and the nose check reports it as given. Left out —\n * compose found no speck, or `measure_layers` — that check judges the `nose`\n * layer file against its crop instead, as `auto_rig_from_layers` does.\n */\nexport async function measureDir(\n absDir: string,\n noseSpeck?: NoseSpeck,\n): Promise<MeasureReport> {\n const files = fs\n .readdirSync(absDir)\n .filter((f) => f.endsWith(\".png\") && !f.startsWith(\"preview\"))\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 bust's torso is meant to run off the bottom of a square canvas. A\n // full body stands on a taller one with its soles inside it, where two\n // soles' flat bottoms could trip the generic check, so a check of its own\n // replaces it: paint on the canvas's last row is feet cut off.\n if (role !== \"body\") {\n edges.push([\"bottom\", m.edgeBottom, m.w, m.marginBottom]);\n } else if (m.canvasH > m.canvasW && m.marginBottom === 0) {\n warnings.push(\n `body: its bottom row is the canvas's last — on a tall canvas that cuts the feet off. ` +\n `Free fix: raise canvasHeight (the canvas grows downward, nothing else moves) and ` +\n `remeasure; regenerate body.png only if the drawing itself stops short of the soles.`,\n );\n }\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 ${isArm(role) ? \"once the arm raises\" : \"once the head turns\"}. ` +\n `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` bends as one drawing, so no pose opens a cut in it; its top is\n // deliberately cut flat where the jaw covers it, and stays under the jaw\n // because the head rides the body.\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 (isArm(role)\n ? `It hides at rest and opens into a seam once the arm raises. `\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 // 1c. The arms: each needs a body, and its shoulder cap the torso under it.\n warnings.push(...(await armWarnings(absDir, layers)));\n\n // 1d. The pose forearms: each needs its arm, and its elbow end the arm's elbow.\n warnings.push(...(await forearmPoseWarnings(absDir, layers)));\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). In sync, the lash is ink the sclera was recoloured from, so\n // every opaque lash pixel lies on the sclera, and both ink the same top\n // row; a drift moves pixels off it, and a lash scaled down inside it (a w\n // or h out of sync) drops its top row — the seam the fold rides — either\n // way tearing the fold. Neither the ink centres nor the frame's sides can\n // stand in for that: a lash stops short of the tear duct (5b), so a\n // correctly composed eye's ink sits 3-5% of its width off the sclera's\n // centre, while a lash drifting in toward that bare end stays inside the\n // frame.\n //\n // 5b. Which way the eye was drawn. A lash runs out to the outer corner,\n // wing and all, and stops short of the tear duct at the inner one, so in\n // the frame it shares with the sclera it is the nose end that the lash\n // leaves bare. A lash that stops short of the OUTER end instead is an\n // eyewhite drawn facing the other way: the wings point in, and \"left eye\"\n // in a prompt cannot prevent it, since it reads as the viewer's left or\n // the character's. The ends are read, not the ink's centroid: a thin wing\n // widens the frame far more than it moves the centroid, which reads a\n // correctly drawn eye as reversed. Only a lash in sync is read — a drift\n // moves the ends too, and is check 5's to report, not the drawing's.\n if (lash) {\n const { opaque, off } = await lashOffSclera(\n path.join(absDir, `eye_${side}.png`),\n path.join(absDir, `lash_${side}.png`),\n );\n const dTop = lash.marginTop - eye.marginTop;\n const faults = [\n ...(off > opaque * LASH_STRAY_TOL_FRAC\n ? [`${off} of its ${opaque} opaque px lie off eye_${side}'s sclera`]\n : []),\n ...(Math.abs(dTop) > 0.5\n ? [`its top edge is ${dTop.toFixed(1)} px off the sclera's`]\n : []),\n ];\n if (faults.length > 0) {\n warnings.push(\n `lash_${side}: ${faults.join(\" and \")} — they are split from one source and MUST share ` +\n `cx/cy/w/h in layout, or the blink fold tears. Retune to match.`,\n );\n } else {\n // How far short of each side of the frame the lash stops.\n const bareLeft = lash.marginLeft - eye.marginLeft;\n const bareRight = lash.marginRight - eye.marginRight;\n // eye_R is the screen-left eye: its outer corner is its left end.\n const [bareOuter, bareInner] =\n side === \"R\" ? [bareLeft, bareRight] : [bareRight, bareLeft];\n if ((bareOuter - bareInner) / eye.w > EYE_FACING_TOL_FRAC) {\n warnings.push(\n `eye_${side}: its lash stops ${pct(bareOuter / eye.w)} of the eye width short of the outer corner ` +\n `and ${pct(bareInner / eye.w)} short of the nose side — the eyewhite is drawn facing the other way, ` +\n `lash wing at the inner corner. The composer reads eyewhite.png as the eye on the screen LEFT: lash ` +\n `wing at the image's left end, lash-free tear duct at its right. Free fix: compose again with ` +\n `mirrorParts: [\"eyewhite.png\"] — no regeneration.`,\n );\n }\n }\n }\n }\n\n // 6. A nose whose dense core is a speck of its part (`isSpeckCore`). A\n // speck compose found in the source part, before resampling, is reported\n // as given: a dot blurred under alpha 128 no longer shows in the file.\n // Otherwise the file is judged against its crop — what the rig reads —\n // which also catches a core that only resampling made a speck.\n if (noseSpeck !== undefined) {\n warnings.push(noseSpeckWarning(noseSpeck, \"compose\"));\n } else if (layers.nose !== undefined) {\n const nose = await decodePng(path.join(absDir, \"nose.png\"));\n const core = denseCoreOf(nose.rgba, nose.width, nose.height);\n if (core !== null) {\n const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);\n if (isSpeckCore(core, crop))\n warnings.push(noseSpeckWarning({ core, part: crop }, \"layer\"));\n }\n }\n\n // 7. 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 the head still turns on the default profile, but there is no nose to lead it, and no turn fit to the art (`turnTargets` is inert, no `turn` report)\",\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 * The measure's arm checks. An arm hangs from the body's shoulder, and raising\n * it turns its shoulder cap about the rig's shoulder pivot, so the torso has\n * to reach under that cap or a gap opens beside the shoulder. The pivot is\n * the rig's own: `armGeometry`, run on the layer as `auto_rig_from_layers`\n * runs it, so the cap measured here is the one the rig turns.\n */\n\nimport path from \"node:path\";\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n type ArmGeometry,\n type LayerInput,\n type LayerSetMeasurer,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { decodePng } from \"./node-images\";\n\n/** The arm roles, screen right (`arm_L`) then screen left (`arm_R`). */\nexport const ARM_ROLES = [\"arm_L\", \"arm_R\"] as const;\n\n/** How far an arm's shoulder cap must reach under the torso's edge on the\n * shoulder pivot's row, as a share of its radius r_u. Our own value: a\n * raised arm turns its cap about the pivot, so a cap that barely meets the\n * torso's edge swings clear of it and bares the gap beside the shoulder. */\nexport const CAP_OVERLAP = 0.5;\n\n/** A px figure as the report prints it: pivots sit on half px. */\nexport const px = (v: number) => `${Number(v.toFixed(1))}`;\n\n/** Decode a role's layer in `absDir` and measure it on `measurer`. */\nexport async function measured(\n measurer: LayerSetMeasurer,\n absDir: string,\n role: string,\n): Promise<LayerInput> {\n const fileName = `${role}.png`;\n const { rgba } = await decodePng(path.join(absDir, fileName));\n // layerStats counts alpha > 8 and the measurer alpha >= 8, so a layer\n // measured non-empty is never empty here.\n return measurer.add({ role, fileName, rgba })!;\n}\n\n/**\n * Warn of an arm layer the rig refuses or would hang with a gap at the\n * shoulder: one without a body, one on another canvas than the body's, one\n * too short to place an elbow under its shoulder, and one whose shoulder cap\n * does not reach `CAP_OVERLAP` of its radius under the torso's edge.\n * `layers` holds the measured, non-empty layers of `absDir` by role.\n */\nexport async function armWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n): Promise<string[]> {\n const warnings: string[] = [];\n const body = layers.body;\n // Opened for the first arm that reaches the overlap, so the body decodes once.\n let set: { measurer: LayerSetMeasurer; body: LayerInput } | undefined;\n\n for (const arm of ARM_ROLES) {\n const stats = layers[arm];\n if (stats === undefined) continue;\n if (body === undefined) {\n warnings.push(\n `${arm}: no body layer — an arm hangs from the body's shoulder, and auto_rig_from_layers refuses it.`,\n );\n continue;\n }\n // One measurer reads every buffer at one size, and a buffer of another\n // shape but the same area would pass its length check and be read with\n // the wrong stride.\n if (stats.canvasW !== body.canvasW || stats.canvasH !== body.canvasH) {\n warnings.push(\n `${arm}: its canvas ${stats.canvasW}x${stats.canvasH} differs from body's ` +\n `${body.canvasW}x${body.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n continue;\n }\n if (set === undefined) {\n const measurer = createLayerSetMeasurer({\n width: body.canvasW,\n height: body.canvasH,\n });\n set = { measurer, body: await measured(measurer, absDir, \"body\") };\n }\n\n let g: ArmGeometry;\n try {\n // The body box's centre, model x: the axis the rig reads an arm's side\n // off.\n g = armGeometry(\n await measured(set.measurer, absDir, arm),\n set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2,\n );\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n warnings.push(\n `${arm}: ${err.message} — auto_rig_from_layers refuses it. Regenerate arm.png drawn ` +\n `hanging, shoulder at the top. Billed.`,\n );\n continue;\n }\n throw err;\n }\n const cap = capWarning(arm, g, set.body);\n if (cap !== undefined) warnings.push(cap);\n }\n return warnings;\n}\n\n/**\n * The shoulder cap against the torso's edge on the arm's side, on the canvas\n * row holding the shoulder pivot: the cap reaches r_u past the pivot, so it\n * overlaps the torso by r_u less the pivot's distance outside that edge.\n */\nfunction capWarning(\n arm: (typeof ARM_ROLES)[number],\n g: ArmGeometry,\n body: LayerInput,\n): string | undefined {\n // Model space is centred on the canvas, y up.\n const pivotX = g.shoulder.x + body.canvasW / 2;\n const row = Math.floor(body.canvasH / 2 - g.shoulder.y);\n const runs = body.rowRuns?.[row - body.bbox.y] ?? [];\n if (runs.length === 0) {\n return (\n `${arm}: the body has no paint on its shoulder pivot's row (y=${row}) — the torso shows a ` +\n `gap beside the shoulder once the arm raises. Retune layout.${arm}.cy onto the shoulder (free).`\n );\n }\n // The outermost run's end on the arm's side; a run's end column is exclusive.\n const edge = g.side === 1 ? runs[runs.length - 1] : runs[0];\n const overlap = g.shoulderRadius - g.side * (pivotX - edge);\n const need = CAP_OVERLAP * g.shoulderRadius;\n if (overlap >= need) return undefined;\n return (\n `${arm}: its shoulder cap reaches ${px(overlap)} px under the torso's edge on its pivot row ` +\n `(y=${row}), under half its radius (${px(need)} px) — a gap opens beside the shoulder once ` +\n `the arm raises. Move layout.${arm}.cx ${Math.ceil(need - overlap)} px toward the body (free).`\n );\n}\n","/**\n * The measure's pose forearm checks. A pose forearm hangs from its arm's\n * elbow and is swapped in for the hanging forearm, so it has to meet the arm\n * where the rig turns it: the rig puts its pivot on the arm's elbow and\n * `forearm_pose.png` is composed so that its elbow end lands there, at the\n * arm's elbow width. The geometry is the rig's own: `armGeometry` on the arm\n * and `forearmPoseGeometry` on the pose forearm, run on one measurer as\n * `auto_rig_from_layers` runs them. A pose forearm too far off in any of\n * pivot, width or length shows a broken joint once the switch is on; the\n * canvas-edge check is the generic one in `measureDir`.\n */\n\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n forearmPoseGeometry,\n type ArmGeometry,\n type ForearmPoseGeometry,\n type LayerInput,\n type LayerSetMeasurer,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { measured, px } from \"./measure-arms\";\n\n/** The pose forearm roles, each with the arm it hangs from. */\nexport const POSE_ROLES = [\"forearm_pose_L\", \"forearm_pose_R\"] as const;\nconst ARM_OF: Record<(typeof POSE_ROLES)[number], \"arm_L\" | \"arm_R\"> = {\n forearm_pose_L: \"arm_L\",\n forearm_pose_R: \"arm_R\",\n};\n\n/** How far off the arm's elbow the pose forearm's pivot may be, px. Our own\n * value: the composer pins it to within a pixel, so more is a layout `cx` /\n * `cy` that moved it. */\nexport const POSE_PIVOT_TOLERANCE = 2;\n/** How far the pose forearm's elbow end may differ from the arm's elbow run,\n * as a share of the run. Our own value: past it the joint shows a step in\n * the sleeve. */\nexport const POSE_WIDTH_TOLERANCE = 0.1;\n/** How far the pose forearm's length (pivot to its top painted row) may\n * differ from the hanging arm's (elbow to its last painted row), as a\n * share of it. Our own value, looser than the width's: a raised hand is\n * not a hanging one, but one twice as long is another arm. */\nexport const POSE_LENGTH_TOLERANCE = 0.15;\n\n/** Model y of the last painted row of a layer, y up. */\nfunction bottomRowY(layer: LayerInput): number {\n const painted =\n layer.rowRuns?.flatMap((runs, k) => (runs.length > 0 ? [k] : [])) ?? [];\n const k = painted.at(-1) ?? layer.bbox.h - 1;\n return layer.canvasH / 2 - (layer.bbox.y + k + 0.5);\n}\n\n/**\n * Warn of a pose forearm the rig refuses or would hang off its arm's elbow:\n * one without its arm, one on another canvas than its arm's, and one whose\n * pivot, elbow-end width or length is off the arm's. Each names its free\n * retune (`layout.forearm_pose_*`) or, where only a new drawing helps, the\n * regeneration. `layers` holds the measured, non-empty layers of `absDir` by\n * role.\n */\nexport async function forearmPoseWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n): Promise<string[]> {\n const warnings: string[] = [];\n for (const pose of POSE_ROLES) {\n const stats = layers[pose];\n if (stats === undefined) continue;\n const arm = ARM_OF[pose];\n const armStats = layers[arm];\n if (armStats === undefined) {\n warnings.push(\n `${pose}: no ${arm} layer — a pose forearm hangs from its arm's elbow, and auto_rig_from_layers refuses it.`,\n );\n continue;\n }\n if (\n stats.canvasW !== armStats.canvasW ||\n stats.canvasH !== armStats.canvasH\n ) {\n warnings.push(\n `${pose}: its canvas ${stats.canvasW}x${stats.canvasH} differs from ${arm}'s ` +\n `${armStats.canvasW}x${armStats.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n continue;\n }\n // Without a body the arm is already warned of (armWarnings).\n if (layers.body === undefined) continue;\n\n const measurer: LayerSetMeasurer = createLayerSetMeasurer({\n width: stats.canvasW,\n height: stats.canvasH,\n });\n let a: ArmGeometry;\n let armLayer: LayerInput;\n try {\n armLayer = await measured(measurer, absDir, arm);\n // Only the elbow and the seam run are read, none of which depends on\n // the side, so the body is not decoded: the axis is the role's own, as\n // the composer passes it.\n a = armGeometry(armLayer, arm === \"arm_R\" ? Infinity : -Infinity);\n } catch (err) {\n // The arm's own warning says it.\n if (err instanceof LayerGeometryError) continue;\n throw err;\n }\n const b = forearmPoseGeometry(await measured(measurer, absDir, pose));\n warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));\n }\n return warnings;\n}\n\nfunction jointWarnings(\n pose: (typeof POSE_ROLES)[number],\n arm: string,\n stats: LayerStats,\n a: ArmGeometry,\n armLayer: LayerInput,\n b: ForearmPoseGeometry,\n): string[] {\n const warnings: string[] = [];\n const key = `layout.${pose}`;\n\n // Pivot: model x grows right, y up; the layout's cy grows down. A layout\n // centre is the box's: the bbox's pixel centre (bboxCx) plus half a pixel.\n const dx = a.elbow.x - b.pivot.x;\n const dy = a.elbow.y - b.pivot.y;\n const off = Math.hypot(dx, dy);\n if (off > POSE_PIVOT_TOLERANCE) {\n warnings.push(\n `${pose}: its elbow end is ${px(off)} px off ${arm}'s elbow — the raised forearm detaches ` +\n `from the arm at the joint once it swaps in. Remove ${key}.cx/cy from the layout so it stays ` +\n `pinned on the elbow through later arm retunes (free), or set ${key}.cx to ` +\n `${Math.round(stats.bboxCx + 0.5 + dx)} and ${key}.cy to ${Math.round(stats.bboxCy + 0.5 - dy)} (free).`,\n );\n }\n\n // Width: B's elbow end against A's elbow run, by the w to set.\n const armRun = a.seamRun[1] - a.seamRun[0];\n const poseRun = 2 * b.radius;\n const widthRatio = poseRun / armRun;\n const widthBad = Math.abs(widthRatio - 1) > POSE_WIDTH_TOLERANCE;\n if (widthBad) {\n warnings.push(\n `${pose}: its elbow end is ${px(poseRun)} px wide, ${Math.round(Math.abs(widthRatio - 1) * 100)}% off ` +\n `${arm}'s elbow run (${px(armRun)} px) — the sleeve steps at the joint once it swaps in. ` +\n `Set ${key}.w to ${Math.round(stats.w / widthRatio)} (free).`,\n );\n }\n\n // Length: B from its pivot up to its hand, A from its elbow down to its\n // hand. A new w scales the width with it, so it only mends the length when\n // the width fits after.\n const armLen = a.elbow.y - bottomRowY(armLayer);\n const poseLen = b.top - b.pivot.y;\n const lengthRatio = poseLen / armLen;\n if (Math.abs(lengthRatio - 1) > POSE_LENGTH_TOLERANCE) {\n const fix = 1 / lengthRatio;\n const freeFix = Math.abs(widthRatio * fix - 1) <= POSE_WIDTH_TOLERANCE;\n warnings.push(\n `${pose}: its length from the elbow end to the hand is ${px(poseLen)} px against ${arm}'s ` +\n `${px(armLen)} px from its elbow to its hand — ` +\n (freeFix\n ? `the raised hand reaches the wrong height. Set ${key}.w to ${Math.round(stats.w * fix)} (free)` +\n (widthBad ? `, which fixes the width too.` : `.`)\n : `the raised hand reaches the wrong height, and no single w fits both its length and its width. ` +\n `Regenerate forearm_pose.png with the forearm and hand as long as the hanging arm's below its elbow. Billed.`),\n );\n }\n return warnings;\n}\n","/**\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 {\n ALPHA_OPAQUE,\n HEAD_BAND,\n foregroundSpan,\n headHalfOf,\n} from \"@ikijs/editor\";\nimport { decodePng, encodeOverlayPng } from \"./node-images\";\nimport {\n AutoRigInputError,\n resolveInputPath,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n// Re-exported so compose.ts, measure.ts and the tests keep their imports.\nexport {\n SPECK_CORE_FRACTION,\n denseCoreOf,\n headHalfOf,\n isSpeckCore,\n} from \"@ikijs/editor\";\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\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.\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/** 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 * Where the composer hangs an arm. One arm.png is the arm on the screen LEFT:\n * `arm_R` takes it as drawn and `arm_L` mirrored. Each of an arm's `cx` / `cy`\n * that the layout leaves unset is derived from the placed body's box: the\n * arm's shoulder pivot lands on the box's shoulder corner on that axis — the\n * box's left edge for `arm_R`, its right edge for `arm_L`, SHOULDER_DROP of\n * its height under its top. On a torso widest at its shoulders, the cap's\n * centre then sits on the torso's edge, overlapping it by the cap's radius.\n * An unset `w` is ARM_WIDTH of the body's width.\n *\n * The pivot is the rig's own: `armGeometry`, run on the resized part as\n * `auto_rig_from_layers` runs it on the composed layer, so the rig turns the\n * composed arm about the target to the pixel, with no second copy of its\n * shoulder rule here to keep in step.\n *\n * A pose forearm (`forearm_pose.png`: the screen-left forearm raised,\n * `forearm_pose_R` as drawn and `forearm_pose_L` mirrored) hangs from its\n * arm's elbow, so the composer puts its elbow end where the rig turns it. An\n * unset `w` scales it so its elbow-end width (2 r_e, measured on the trimmed\n * source) equals the placed arm's seam run, and an unset `cx` or `cy` pins\n * its elbow-end pivot (`forearmPoseGeometry`, measured on the resized part as\n * the shoulder is) on the arm's placed elbow. Both read the rig's geometry,\n * none of it copied here.\n */\n\nimport sharp from \"sharp\";\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n forearmPoseGeometry,\n type ArmGeometry,\n type ForearmPoseGeometry,\n} from \"@ikijs/editor\";\nimport type { ArmLayout } from \"./compose\";\nimport { AutoRigInputError } from \"./limits\";\n\n/** An arm's default width, as a share of the placed body's width. Our own\n * value, provisional: to be picked by eye on the first full-body character. */\nexport const ARM_WIDTH = 0.4;\n/** How far under the body box's top its shoulder corners lie, as a share of\n * its height. Our own value, provisional: to be picked by eye on the first\n * full-body character. */\nexport const SHOULDER_DROP = 0.12;\n\n/** A placed part's box on the canvas, px. */\ninterface PlacedBox {\n left: number;\n top: number;\n w: number;\n h: number;\n}\n\n/**\n * Where an arm's resized part lands: by its rig shoulder pivot on the body\n * box's shoulder corner for each of `cx` / `cy` left unset, centred on a set\n * one as every other role's part is. An arm the rig would refuse as too short\n * is refused here, path-qualified.\n */\nexport async function armPlacement(\n role: \"arm_L\" | \"arm_R\",\n cfg: Pick<ArmLayout, \"cx\" | \"cy\">,\n part: { buf: Buffer; w: number; h: number },\n body: PlacedBox,\n): Promise<{\n left: number;\n top: number;\n /** The rig's elbow pivot on the canvas, px. */\n elbow: { x: number; y: number };\n /** The elbow seam's widest run, px: what a pose forearm's elbow end fits. */\n elbowRun: number;\n}> {\n const { data } = await sharp(part.buf)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const layer = createLayerSetMeasurer({ width: part.w, height: part.h }).add({\n role,\n fileName: \"arm.png\",\n rgba: data,\n });\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.${role}: arm.png is empty after alpha threshold once resized`,\n );\n }\n let g: ArmGeometry;\n try {\n // The axis keeps `side` the role's own all the same: arm_R on the screen\n // left, arm_L on the right.\n g = armGeometry(layer, role === \"arm_R\" ? Infinity : -Infinity);\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n throw new AutoRigInputError(`layout.${role}: ${err.message}`);\n }\n throw err;\n }\n // Model space is centred on the measured canvas, here the part itself.\n const pivotX = g.shoulder.x + part.w / 2;\n const pivotY = part.h / 2 - g.shoulder.y;\n const cornerX = role === \"arm_R\" ? body.left : body.left + body.w;\n const cornerY = body.top + SHOULDER_DROP * body.h;\n const left = Math.round(\n cfg.cx === undefined ? cornerX - pivotX : cfg.cx - part.w / 2,\n );\n const top = Math.round(\n cfg.cy === undefined ? cornerY - pivotY : cfg.cy - part.h / 2,\n );\n return {\n left,\n top,\n elbow: {\n x: left + g.elbow.x + part.w / 2,\n y: top + part.h / 2 - g.elbow.y,\n },\n elbowRun: g.seamRun[1] - g.seamRun[0],\n };\n}\n\ntype PoseRole = \"forearm_pose_L\" | \"forearm_pose_R\";\n\n/** A pose forearm's geometry on a PNG of the given size, read as the rig\n * reads a layer; an empty one is refused path-qualified. */\nasync function poseGeometryOf(\n role: PoseRole,\n png: Buffer,\n size: { w: number; h: number },\n when: string,\n): Promise<ForearmPoseGeometry> {\n const { data } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const layer = createLayerSetMeasurer({\n width: size.w,\n height: size.h,\n }).add({ role, fileName: \"forearm_pose.png\", rgba: data });\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`,\n );\n }\n return forearmPoseGeometry(layer);\n}\n\n/**\n * The width that fits a pose forearm to its arm: the trimmed source scaled\n * so its elbow end's width (2 r_e) equals the arm's elbow run, at least 1.\n */\nexport async function forearmPoseWidth(\n role: PoseRole,\n trimmed: { data: Buffer; w: number; h: number },\n elbowRun: number,\n): Promise<number> {\n const g = await poseGeometryOf(role, trimmed.data, trimmed, \"\");\n return Math.max(1, Math.round((trimmed.w * elbowRun) / (2 * g.radius)));\n}\n\n/**\n * Where a pose forearm's resized part lands: its elbow-end pivot on the\n * arm's placed elbow for each of `cx` / `cy` left unset, centred on a set one\n * as every other role's part is.\n */\nexport async function forearmPosePlacement(\n role: PoseRole,\n cfg: Pick<ArmLayout, \"cx\" | \"cy\">,\n part: { buf: Buffer; w: number; h: number },\n elbow: { x: number; y: number },\n): Promise<{ left: number; top: number }> {\n const { pivot } = await poseGeometryOf(role, part.buf, part, \" once resized\");\n // Model space is centred on the canvas, here the part itself.\n const pivotX = pivot.x + part.w / 2;\n const pivotY = part.h / 2 - pivot.y;\n return {\n left: Math.round(\n cfg.cx === undefined ? elbow.x - pivotX : cfg.cx - part.w / 2,\n ),\n top: Math.round(\n cfg.cy === undefined ? elbow.y - pivotY : cfg.cy - part.h / 2,\n ),\n };\n}\n","#!/usr/bin/env node\nimport { createIkiMcpServer } from \"./server\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\n\nasync function main() {\n const server = createIkiMcpServer();\n await server.connect(new StdioServerTransport());\n}\n\nmain().catch((err) => {\n console.error(err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iBAA0B;AAC1B,iBAAkB;;;ACDlB,IAAAA,oBAAiB;AACjB,oBAOO;AACP,IAAAC,iBAiBO;;;ACZP,mBAAkB;AAElB,oBAAiD;;;ACJjD,qBAAe;AACf,uBAAiB;AAGV,IAAM,aAAa;AAEnB,IAAM,gBAAgB;AAEtB,IAAM,iBAAiB;AAKvB,IAAM,iBAAiB;AAEvB,IAAM,mBAAmB,OAAO;AAIhC,IAAM,mBAAmB,MAAM,OAAO;A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Q,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["import_node_path","import_editor","path","fs","sharp","scanAlphaBbox","placement","path","placement","import_node_fs","import_node_path","import_sharp","import_editor","import_node_fs","import_node_path","import_node_path","import_editor","path","import_editor","k","import_node_path","import_editor","import_editor","path","fs","path","import_sharp","import_editor","sharp","sharp","scanAlphaBbox","path","fs","px","part","left","top"]}
|