@ikijs/mcp 0.11.3 → 0.12.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 +3 -2
- package/dist/{chunk-CFP3KTDY.mjs → chunk-RMB5YVBU.mjs} +29 -13
- package/dist/chunk-RMB5YVBU.mjs.map +1 -0
- package/dist/cli.js +28 -12
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +4 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +28 -12
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-CFP3KTDY.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -22,8 +22,9 @@ Turns a set of role-named, full-canvas transparent PNG layers into a renderable,
|
|
|
22
22
|
|
|
23
23
|
- **`layers`** — array of `{ path, fileName? }`. `path` is a PNG file path (resolved against the server's working directory); the role is derived from `fileName ?? basename(path)`. Required roles: `face`, `eye_L`, `eye_R`, `mouth`. Optional roles include `iris_L`/`iris_R`, `brow_L`/`brow_R`, `hair_front`/`hair_back`, `lash_L`/`lash_R`, etc. All layers must share the same canvas size (taken from the first layer).
|
|
24
24
|
- **`outputPath`** — optional `.iki` output path (resolved against the working directory; the parent directory must already exist, and the path must end in `.iki`). Defaults to `auto-rigged-model.iki`.
|
|
25
|
-
- **`turnTargets`** — optional head-turn cues to fit the rig to, in the units `measure_turn_reference` reports off a front/turned reference pair: `eyeShift` (plus `noseShift` and `mouthShift
|
|
26
|
-
-
|
|
25
|
+
- **`turnTargets`** — optional head-turn cues to fit the rig to, in the units `measure_turn_reference` reports off a front/turned reference pair: `eyeShift` (plus `noseShift` and `mouthShift`) is how far that feature slides across the head at full turn, as a fraction of the head's half-width — a **magnitude**, since the rig turns both ways and the sign is the turn's own business; `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. An omitted field leaves that part of the turn at the Live2D profile the rig defaults to. An `eyeShift` you pass is fitted by the turn's amount and _clamped_ when it runs past the room the art leaves the far eye — the face plate's edge, or the bangs' side strand over the far iris — since that room is a fact about these layers, not about the reference. Any other target you **do** pass that it cannot reach is refused, because that number is a measurement rather than a preference. A layer set without a `nose` still turns its head, on the profile, but fits no target: `turnTargets` is then inert and the result carries no `turn`.
|
|
26
|
+
- **`style`** — optional per-character tuning from the Live2D profile, only where the Live2D samples themselves disagree: `turn` (the whole head turn, the eyes' foreshortening with it, 0..3, 1 = the profile; ignored when `turnTargets.eyeShift` is given), `featureLead` (how far the features lead the face plate, 0..3), `hairFollow` (the front hair's share of the face's turn, 0..2, profile 1.1), `outlineFollow` (its outer edge's share where it 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.58) and `sway` (the hair sway amplitude, 0..5). A value out of range, or a knob not named here, is refused.
|
|
27
|
+
- **Result** — on success the result text is the written file path and `structuredContent` carries `{ ok: true, path, canvas, partCount, atlasBytes, headHalfWidth?, headHalfWidthApplied, headEdges?, strandEdges?, noseCore?, turn? }`. `atlasBytes` is the embedded atlas's data-URI length, summed over both pages when the nose has one of its own. `headHalfWidth` is the head measured here rather than asked for: the layers' own opaque union at the eye row, under the same `alpha >= 128` rule and ±10-row band `measure_turn_reference` spans a render with, so the rig's own rest render measures that span back; it is **absent** when that union has no span there at all (translucent art painted below alpha 128 — still a valid layer set, just with nothing to measure). `headHalfWidthApplied` is `false` when the measured value is absent, or no wider than the face plate (a hairless set, or one widest at the plate itself) — the generator will not take such a head, so the plate stands in for it and the rig is still produced either way. `headEdges` is a companion to a measured, applied `headHalfWidth` (absent otherwise): every role with an opaque pixel in that same eye-row band, per side, each with its own rest x there — passed straight to the generator's own `options.headEdges` so it can tell which part's own deformation actually carries the union's outermost pixel through the turn. `strandEdges` is each side's iris and the `hair_front` run it would slide under on the turn, measured whenever the layers include `hair_front`, `iris_L` and `iris_R`: the iris's opaque span and the run's outer and face-side ends as pixel edges on the row holding the iris's centre (a run that reaches the other iris's centre, a fringe spanning the face, has `runFace: null`; a run narrower than half the iris's painted width on that row is hair detail the iris may cross, and is skipped as if clear) — passed straight to the generator's own `options.strandEdges`, which keeps the far iris from sliding under the bangs any further than it is painted. `turn` is what the solve settled on — `{ radius, holdBase, depths, achieved: { eyeShift, farEyeRatio, silhouetteRatio }, clamped, strandOverlap? }`, where `achieved` is what the rig does reach and `clamped` names every target the rig cut down: the turn (`eyeShift`, passed or the profile's own) where the face plate's edge or the strand cut it short, and a profile `noseShift` / `mouthShift` past its room. `strandOverlap` gives, per side whose far iris the bangs still cover at some far stop, the covered width — how much of the iris's painted row the run covers where that is largest (`deg`, `px`, and `hh` in head half-widths), how much it covers at rest (`restPx`), and whether the bound held (`held`: `true` means the iris is kept no deeper under the run than it is painted; `false` means the art left no room to — always so for a fringe spanning the face — and `px` is what stays covered); it is absent when nothing is covered. `noseCore` is the nose's dense core in canvas px — its pixels at alpha >= 128, not grown, the box handed to the generator as the nose layer's `denseCore` and its turn landmark — absent without a `nose` layer, when it has no pixel at that threshold (painted wholly translucent), or when that core is a speck of the nose's crop (under a quarter of its width or height, such as a lone nostril mark), and in both of the last two cases the crop stands in for it. `turn` is absent without a `nose` layer. The (potentially multi-MB) model is written to disk, not inlined. Invalid input (unknown/missing role, empty layer, mismatched sizes, bad path, oversized atlas, a `turnTargets` field that is unknown or that this layer set cannot reach — any passed field other than an `eyeShift` past the art's room; a `style` knob out of range or unknown; the message names the field and the attainable range) returns `{ ok: false, error }` with a `INVALID: …` text — not a protocol error. An argument the tool's input schema refuses — a `turnTargets` or `style` that is not an object, or one of their named fields that is not a number — never reaches the tool: the MCP SDK answers with an `isError` result whose text is `MCP error -32602: Input validation error: …`, and no `structuredContent`.
|
|
27
28
|
|
|
28
29
|
The decode/atlas pipeline runs in Node via `sharp` (a native dependency confined to this package); it mirrors the browser editor app's import flow and reuses the pure `@ikijs/editor` model + atlas math, so both paths produce the same rig.
|
|
29
30
|
|
|
@@ -392,6 +392,17 @@ async function autoRigFromLayers(input) {
|
|
|
392
392
|
`quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`
|
|
393
393
|
);
|
|
394
394
|
}
|
|
395
|
+
const turnTargets = input.turnTargets;
|
|
396
|
+
if (turnTargets !== void 0) {
|
|
397
|
+
if (typeof turnTargets !== "object" || turnTargets === null || Array.isArray(turnTargets)) {
|
|
398
|
+
throw new AutoRigInputError("turnTargets must be a plain object");
|
|
399
|
+
}
|
|
400
|
+
if (turnTargets.headHalfWidth !== void 0) {
|
|
401
|
+
throw new AutoRigInputError(
|
|
402
|
+
"turnTargets.headHalfWidth is measured off the layers, not accepted as input"
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
395
406
|
const resolvedLayers = layers.map((layer) => {
|
|
396
407
|
const resolved = resolveInputPath(layer.path);
|
|
397
408
|
return { resolved, fileName: layer.fileName ?? path2.basename(resolved) };
|
|
@@ -457,22 +468,18 @@ async function autoRigFromLayers(input) {
|
|
|
457
468
|
let turn;
|
|
458
469
|
let model;
|
|
459
470
|
try {
|
|
460
|
-
const { eyeShift, farEyeRatio, silhouetteRatio, noseShift, mouthShift } = input.turnTargets ?? {};
|
|
461
471
|
model = generateIkiFromLayerSet(
|
|
462
472
|
measurement.layers,
|
|
463
473
|
{ width: canvasW, height: canvasH },
|
|
464
474
|
{
|
|
465
475
|
turnTargets: {
|
|
466
|
-
|
|
467
|
-
farEyeRatio,
|
|
468
|
-
silhouetteRatio,
|
|
469
|
-
noseShift,
|
|
470
|
-
mouthShift,
|
|
476
|
+
...input.turnTargets,
|
|
471
477
|
...turnOptions.turnTargets
|
|
472
478
|
},
|
|
473
479
|
onTurnSolved: (report) => {
|
|
474
480
|
turn = report;
|
|
475
481
|
},
|
|
482
|
+
...input.style === void 0 ? {} : { style: input.style },
|
|
476
483
|
...headEdges === void 0 ? {} : { headEdges },
|
|
477
484
|
...strandEdges === void 0 ? {} : { strandEdges }
|
|
478
485
|
}
|
|
@@ -1206,9 +1213,8 @@ var DEFAULT_LAYOUT = {
|
|
|
1206
1213
|
// Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
|
|
1207
1214
|
// without them still composes (head-only character).
|
|
1208
1215
|
hair_back: { src: "hair_back.png", cx: 550, cy: 523, w: 800, optional: true },
|
|
1209
|
-
// The torso, cut off by the canvas bottom
|
|
1210
|
-
//
|
|
1211
|
-
// not a floating head.
|
|
1216
|
+
// The torso, cut off by the canvas bottom, so the character is not a
|
|
1217
|
+
// floating head. It rides its own `bodyDeformer`, which only breathes.
|
|
1212
1218
|
body: { src: "body.png", cx: 550, cy: 1017, w: 840, optional: true },
|
|
1213
1219
|
face: { src: "face.png", cx: 550, cy: 475, w: 400 },
|
|
1214
1220
|
// The nose, drawn on its own (the face is drawn without one): the auto-rig
|
|
@@ -1591,7 +1597,7 @@ async function composeLayersFromParts(input) {
|
|
|
1591
1597
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
1592
1598
|
import { z } from "zod";
|
|
1593
1599
|
function createIkiMcpServer() {
|
|
1594
|
-
const server = new McpServer({ name: "iki", version: "0.
|
|
1600
|
+
const server = new McpServer({ name: "iki", version: "0.12.0" });
|
|
1595
1601
|
server.registerTool(
|
|
1596
1602
|
"validate_iki",
|
|
1597
1603
|
{
|
|
@@ -1678,8 +1684,18 @@ function createIkiMcpServer() {
|
|
|
1678
1684
|
silhouetteRatio: z.number().optional(),
|
|
1679
1685
|
noseShift: z.number().optional(),
|
|
1680
1686
|
mouthShift: z.number().optional()
|
|
1681
|
-
}).optional().describe(
|
|
1682
|
-
"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
|
|
1687
|
+
}).passthrough().optional().describe(
|
|
1688
|
+
"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 \u2014 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 Live2D 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 \u2014 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). Any other passed target this layer set cannot reach comes back as `INVALID: \u2026` 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."
|
|
1689
|
+
),
|
|
1690
|
+
style: z.object({
|
|
1691
|
+
turn: z.number().optional(),
|
|
1692
|
+
featureLead: z.number().optional(),
|
|
1693
|
+
hairFollow: z.number().optional(),
|
|
1694
|
+
outlineFollow: z.number().optional(),
|
|
1695
|
+
blink: z.number().optional(),
|
|
1696
|
+
sway: z.number().optional()
|
|
1697
|
+
}).passthrough().optional().describe(
|
|
1698
|
+
"Per-character tuning from the Live2D profile the rig defaults to \u2014 only what the Live2D samples themselves disagree on: `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.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.58), `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: \u2026`."
|
|
1683
1699
|
)
|
|
1684
1700
|
}
|
|
1685
1701
|
},
|
|
@@ -1823,4 +1839,4 @@ export {
|
|
|
1823
1839
|
composeLayersFromParts,
|
|
1824
1840
|
createIkiMcpServer
|
|
1825
1841
|
};
|
|
1826
|
-
//# sourceMappingURL=chunk-
|
|
1842
|
+
//# sourceMappingURL=chunk-RMB5YVBU.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tools.ts","../src/node-images.ts","../src/limits.ts","../src/measure-turn.ts","../src/measure.ts","../src/compose.ts","../src/server.ts"],"sourcesContent":["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 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_AREA,\n MAX_TOTAL_PIXELS,\n MAX_OUTPUT_BYTES,\n resolveInputPath,\n resolveOutputPath,\n writeFileAtomic,\n} from \"./limits\";\n\nexport type ValidateResult = { ok: true } | { ok: false; error: string };\n\nexport interface IkiSummary {\n name: string;\n canvas: { width: number; height: number };\n parameters: { id: string; min: number; max: number; default: number }[];\n parts: { id: string; order: number; deformer?: string }[];\n deformers: DeformerSummary[];\n}\n\nexport interface DeformerSummary {\n id: string;\n kind: \"matrix\" | \"warp\";\n parent?: string;\n warp?:\n | { mode: \"1d\"; parameters: string[] }\n | {\n mode: \"2d\";\n parameterX: string;\n parameterY: string;\n gridX: number;\n gridY: number;\n };\n}\n\nexport type DescribeResult =\n | { ok: true; summary: IkiSummary }\n | { ok: false; error: string };\n\nexport interface StandardParameterInfo {\n id: string;\n description: string;\n}\n\nfunction coerceModel(\n model: unknown,\n): { ok: true; model: IkiModel } | { ok: false; error: string } {\n try {\n const parsed =\n typeof model === \"string\" ? loadIkiModel(model) : parseIkiModel(model);\n return { ok: true, model: parsed };\n } catch (e) {\n if (e instanceof IkiFormatError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\nexport function validateIki(model: unknown): ValidateResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n return { ok: true };\n}\n\nexport function describeIki(model: unknown): DescribeResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n\n const m = result.model;\n\n const parameters = m.parameters.map((p) => ({\n id: p.id,\n min: p.min,\n max: p.max,\n default: p.default,\n }));\n\n const parts = m.parts.map((p) => {\n const entry: { id: string; order: number; deformer?: string } = {\n id: p.id,\n order: p.order,\n };\n if (p.deformer !== undefined) entry.deformer = p.deformer;\n return entry;\n });\n\n const deformers = (m.deformers ?? []).map(\n (d: IkiDeformer): DeformerSummary => {\n const kind = d.kind === \"warp\" ? \"warp\" : \"matrix\";\n const entry: DeformerSummary = { id: d.id, kind };\n if (d.parent !== undefined) entry.parent = d.parent;\n\n if (d.kind === \"warp\") {\n if (d.warp2d !== undefined) {\n entry.warp = {\n mode: \"2d\",\n parameterX: d.warp2d.parameter,\n parameterY: d.warp2d.parameterY,\n gridX: d.grid.cols,\n gridY: d.grid.rows,\n };\n } else if (d.warps !== undefined && d.warps.length > 0) {\n entry.warp = {\n mode: \"1d\",\n parameters: d.warps.map((w) => w.parameter),\n };\n }\n }\n\n return entry;\n },\n );\n\n const summary: IkiSummary = {\n name: m.name,\n canvas: { width: m.canvas.width, height: m.canvas.height },\n parameters,\n parts,\n deformers,\n };\n\n return { ok: true, summary };\n}\n\n// Static map of standard parameter ids to human-readable descriptions,\n// sourced from JSDoc comments in parameters.ts (including range hints).\nconst STANDARD_PARAMETER_INFO: StandardParameterInfo[] = [\n {\n id: StandardParameter.MouthOpen,\n description: \"Mouth open amount for lip-sync (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.MouthForm,\n description: \"Mouth form / smile (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeOpenLeft,\n description:\n \"Left eye open (0 closed .. 1 open). Drive with the right eye for a blink.\",\n },\n {\n id: StandardParameter.EyeOpenRight,\n description: \"Right eye open (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.EyeballX,\n description: \"Eyeball gaze, horizontal (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeballY,\n description: \"Eyeball gaze, vertical (-1 .. 1).\",\n },\n {\n id: StandardParameter.AngleX,\n description: \"Head angle, horizontal degrees.\",\n },\n {\n id: StandardParameter.AngleY,\n description: \"Head angle, vertical degrees.\",\n },\n {\n id: StandardParameter.AngleZ,\n description:\n \"Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D.\",\n },\n {\n id: StandardParameter.Breath,\n description: \"Idle breath (0 .. 1), cycled by the host.\",\n },\n {\n id: StandardParameter.BrowLeftY,\n description: \"Left brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightY,\n description: \"Right brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowLeftAngle,\n description: \"Left brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightAngle,\n description: \"Right brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.HairSwayX,\n description:\n \"Horizontal hair-sway driver. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.HairSwayZ,\n description:\n \"Hair-sway driver behind a head tilt. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n];\n\nexport function listStandardParameters(): StandardParameterInfo[] {\n return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));\n}\n\n// ── auto_rig_from_layers ──────────────────────────────────────────────────────\n\n/** One role-named PNG layer; role is derived from `fileName ?? basename(path)`. */\nexport interface AutoRigLayerInput {\n fileName?: string;\n path: string;\n}\n\nexport interface AutoRigInput {\n layers: AutoRigLayerInput[];\n /** Output `.iki` path (relative paths resolve against the process cwd). */\n outputPath?: string;\n /** Palette-quantize the atlas PNG to this many colours (integer, 2..256).\n * Omitted = lossless. See renderAtlasToDataUri for the size/quality trade.\n * 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 Live2D 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, refused over MAX_ATLAS_AREA, and render\n * it — palette-quantized to `quantizeColors` when that is set. */\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 if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`,\n );\n }\n 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` and the\n * nose's dense core, returned as `noseCore`); what the solve settled on comes\n * back in `turn`. Under `quantizeColors` the nose is atlased alone on a\n * second, lossless page, which the palette would otherwise rim; `atlasBytes`\n * 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 from the turn solve, the one part of the generator that reads\n // CALLER input. It marks those with TurnTargetError (a field that is not a\n // number, a target this layer set cannot reach), which is a fact about the\n // request, not a bug.\n let turn: TurnSolveReport | undefined;\n let model: IkiModel;\n try {\n // 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)) throw e;\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.map((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n return {\n partId: crop.id,\n uv: uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n }),\n };\n }),\n );\n\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 patched.parts.find((p) => p.id === losslessCrop.id)!.texture!.index = 1;\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 area (px²) of each packed atlas page. */\nexport const MAX_ATLAS_AREA = 4096 * 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request, so a set of\n * many large PNGs cannot exhaust memory even though each passes MAX_LAYER_DIM. */\nexport const MAX_TOTAL_PIXELS = 64 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model,\n * summed over its pages. */\nexport const MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Reject an empty/whitespace or URL-looking caller-supplied path, shared by\n * {@link resolveInputPath} and {@link resolveInputDir}. `noun` and `kind`\n * shape the thrown message so each caller reports in its own vocabulary\n * (e.g. a directory input was never supposed to look like \"a file path\").\n */\nfunction rejectEmptyOrUrl(inputPath: string, noun: string, kind: string): void {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(`${noun} is empty`);\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `${noun} must be a ${kind}, not a URL: ${inputPath}`,\n );\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which reads its part PNGs\n * from wherever the image generator dropped them (a downloads folder, a scratch\n * dir) while everything it writes — the composed layers, the model — stays\n * under the working directory. Revisit only if this server ever runs with wider\n * privileges than the person driving it. The same reasoning covers\n * {@link resolveInputDir}, its directory counterpart.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string): string {\n rejectEmptyOrUrl(inputPath, \"layer path\", \"file path\");\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layer file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `layer path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/** Directory counterpart to {@link resolveInputPath} — see its doc comment. */\nexport function resolveInputDir(dirPath: string): string {\n rejectEmptyOrUrl(dirPath, \"layers dir\", \"directory path\");\n const resolved = path.resolve(process.cwd(), dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layers dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`layers path is not a directory: ${resolved}`);\n }\n return resolved;\n}\n\n/**\n * Confine an already-verified-to-exist directory to the MCP process working\n * directory, comparing REAL paths (statSync/writeFileSync follow symlinks, so\n * a lexical startsWith check can be bypassed by a symlinked dir under cwd).\n * Shared by {@link resolveOutputPath} and {@link resolveOutputDir} — both are\n * write-side boundaries where an unrestricted target is an\n * arbitrary-file-overwrite surface. `label` and `original` shape the thrown\n * message (path-qualified with the caller's original, unresolved string).\n */\nfunction confineToWorkingDirectory(\n root: string,\n dir: string,\n label: string,\n original: string,\n): string {\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `${label} escapes the working directory: ${original}`,\n );\n }\n return realDir;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `.iki` AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(outputPath: string): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(\".iki\")) {\n throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n const realDir = confineToWorkingDirectory(\n root,\n dir,\n \"output path\",\n outputPath,\n );\n return path.join(realDir, path.basename(resolved));\n}\n\n/**\n * Resolve a caller-supplied output DIRECTORY against the MCP process cwd.\n * Unlike {@link resolveOutputPath}, no filename is appended — the directory\n * itself must already exist (the tool never creates directories, fail-fast) —\n * and is confined via {@link confineToWorkingDirectory}. Returns the\n * realpath'd directory.\n */\nexport function resolveOutputDir(dirPath: string): string {\n if (typeof dirPath !== \"string\" || dirPath.trim() === \"\") {\n throw new AutoRigInputError(\"output dir is empty\");\n }\n const root = process.cwd();\n const resolved = path.resolve(root, dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`output dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output dir is not a directory: ${resolved}`);\n }\n return confineToWorkingDirectory(root, resolved, \"output dir\", dirPath);\n}\n\n/**\n * Write `data` to `outPath` atomically: write to a fresh temp file in the\n * same directory, then `renameSync` over the target. `rename` REPLACES the\n * destination directory entry rather than following it, so an existing\n * symlink at `outPath` cannot redirect the write outside the working tree.\n * Throws AutoRigInputError(\"write: …\") on failure.\n */\nexport function writeFileAtomic(\n outPath: string,\n data: string | Uint8Array,\n): void {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(tmp, data);\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n } catch (e) {\n throw new AutoRigInputError(\n `write: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n","/**\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 * 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 { 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/** 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 (`preview.png`\n * is the composer's contact sheet, not a role) and run the geometry 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 !== \"preview.png\")\n .sort();\n if (files.length === 0) {\n throw new AutoRigInputError(`no role layers in ${absDir}`);\n }\n // Same agent-supplied-input surface autoRigFromLayers bounds: a `layersDir`\n // pointed at an asset folder would decode every PNG in it before reporting.\n if (files.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers in ${absDir}: ${files.length} > ${MAX_LAYERS}`,\n );\n }\n\n const layers: Record<string, LayerStats> = {};\n const empty: string[] = [];\n for (const f of files) {\n const role = path.basename(f, \".png\");\n const m = await layerStats(path.join(absDir, f));\n if (!m) {\n empty.push(role);\n continue;\n }\n layers[role] = m;\n }\n\n const warnings: string[] = [];\n\n // 1. Art running to its own edge → a straight seam appears on head turn.\n // Two very different faults look identical in the flattened layer, and the\n // remedies cost differently, so tell them apart before prescribing one: a\n // part the CANVAS clipped has no margin left on that side (retune, free),\n // while a part placed with room whose own drawing runs to its frame does\n // (regenerate, billed). A real run lost a regeneration to this: the source\n // kept 44 px of margin and the default layout pushed it 70 px off-canvas,\n // so redrawing it reproduced the clip exactly.\n for (const [role, m] of Object.entries(layers)) {\n const edges: [string, number, number, number][] = [\n [\"top\", m.edgeTop, m.w, m.marginTop],\n [\"left\", m.edgeLeft, m.h, m.marginLeft],\n [\"right\", m.edgeRight, m.h, m.marginRight],\n ];\n // A torso is meant to run off the bottom of the canvas.\n if (role !== \"body\")\n edges.push([\"bottom\", m.edgeBottom, m.w, m.marginBottom]);\n for (const [side, v, span, margin] of edges) {\n if (v > EDGE_SOLID_MAX && v * span >= EDGE_RUN_MIN_PX) {\n const remedy =\n margin === 0\n ? // margin 0 is consistent with a clipped placement AND with art\n // already cropped flush that happens to sit on the boundary, and\n // the flattened layer cannot separate them — so name the free\n // move rather than the cause. If moving it inward leaves the\n // edge opaque, the drawing is the one at fault.\n `it sits flush against the canvas ${side}, which a clipped placement and already-cropped ` +\n `art both produce. Move it inward first — retune layout.${role}.cx/cy/w, free — and ` +\n `remeasure; regenerate only if the edge is still opaque with margin to spare.`\n : `its own drawing runs to the frame ${margin} px inside the canvas — regenerate that part ` +\n `with empty margin on that side. Billed.`;\n warnings.push(\n `${role}: ${pct(v)} of its ${side} edge is opaque — the art is cut off there, ` +\n `which shows as a straight seam once the head turns. Cause: ${remedy}`,\n );\n }\n }\n }\n\n // 1b. A straight cut through the drawing, wherever it falls in the bbox.\n for (const [role, m] of Object.entries(layers)) {\n // `body` moves only as a rigid whole, and only on the breath, so no pose\n // can uncover a cut in it; its top is deliberately cut flat where the jaw\n // covers it.\n if (role === \"body\") continue;\n if (\n m.flatCutRun > FLAT_CUT_MAX_FRAC * m.w &&\n m.flatCutRun >= FLAT_CUT_MIN_PX\n ) {\n warnings.push(\n `${role}: ${m.flatCutRun}px of straight flat edge at y=${m.flatCutY} ` +\n `(${pct(m.flatCutRun / m.w)} of its width) — the source art is cut through there. ` +\n `It hides while the head faces front and opens into a seam on turn. ` +\n `Regenerate this part with the whole subject inside the frame.`,\n );\n }\n }\n\n // 2/3/4. Eye stack geometry, per side.\n for (const side of [\"L\", \"R\"]) {\n const eye: LayerStats | undefined = layers[`eye_${side}`];\n const iris: LayerStats | undefined = layers[`iris_${side}`];\n const lash: LayerStats | undefined = layers[`lash_${side}`];\n if (!eye) continue;\n\n const aspect = eye.h / eye.w;\n if (aspect < EYE_ASPECT_MIN) {\n warnings.push(\n `eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} — ` +\n `a round iris cannot sit inside it. Free fix first: set layout.eye_${side}.h and ` +\n `layout.lash_${side}.h to ${Math.ceil(eye.w * EYE_ASPECT_MIN)} (both, or the fold tears) — ` +\n `stretching a flat white lens is invisible. Regenerate the eyewhite taller only if that ` +\n `distorts the lash.`,\n );\n }\n\n if (iris) {\n const ratio = iris.w / eye.w;\n if (ratio < IRIS_RATIO_MIN || ratio > IRIS_RATIO_MAX) {\n warnings.push(\n `iris_${side}: width is ${pct(ratio)} of the sclera (target ${IRIS_RATIO_MIN}-${IRIS_RATIO_MAX}) — ` +\n `retune layout.iris_${side}.w (keep it a fraction of the eye width), no regeneration needed.`,\n );\n }\n const dx = iris.bboxCx - eye.massCx;\n const dy = iris.bboxCy - eye.massCy;\n if (\n Math.abs(dx) > IRIS_OFFSET_MAX_X ||\n Math.abs(dy) > IRIS_OFFSET_MAX_Y\n ) {\n warnings.push(\n `iris_${side}: sits (${dx.toFixed(1)}, ${dy.toFixed(1)}) px from the white's centre of mass — ` +\n `retune layout.iris_${side}.cx/cy. The sclera's bbox centre is NOT its visual centre when the ` +\n `lash flick stretches the box.`,\n );\n }\n }\n\n // 5. The lash and the white are split from ONE source and pasted with the\n // same cx/cy/w, so their frames coincide even though the lash only inks the\n // upper part of it (its content sits higher — that is the fold working, not\n // a fault). 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 nothing on the face slides on the head turn — the features stay on the plate\",\n ],\n ]) {\n if (layers[role] === undefined) warnings.push(`${role}: missing — ${why}.`);\n }\n\n return { layers, empty, warnings };\n}\n\n/**\n * Measure a caller-supplied layers directory.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function measureLayers(\n input: MeasureInput,\n): Promise<MeasureResult> {\n try {\n const layersDir = resolveInputDir(input.layersDir);\n const report = await measureDir(layersDir);\n return {\n ok: true,\n layersDir,\n ...report,\n passed: report.warnings.length === 0,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n\n/**\n * Render a measurement as plain text: the per-layer table first (numbers to\n * argue with), then the checks that fired. Takes the report itself rather than\n * a MeasureResult so a caller holding one inline (no `ok` to unwrap) can print\n * it too; a failed measurement has no report to render.\n */\nexport function formatMeasureReport(\n result: MeasureReport & { layersDir: string },\n): string {\n const lines = [\n `# layers (${result.layersDir})`,\n \"\",\n \"role size bbox-centre mass-centre margins t/b/l/r\",\n ];\n // Roles come off a sorted file listing, so sorting the two groups back\n // together restores that order.\n for (const role of [...Object.keys(result.layers), ...result.empty].sort()) {\n const m = result.layers[role];\n if (m === undefined) {\n lines.push(`${role.padEnd(13)} EMPTY (fully transparent)`);\n continue;\n }\n lines.push(\n `${role.padEnd(13)} ${`${m.w}x${m.h}`.padEnd(11)} ` +\n `${`${m.bboxCx.toFixed(0)},${m.bboxCy.toFixed(0)}`.padEnd(14)} ` +\n `${`${m.massCx.toFixed(0)},${m.massCy.toFixed(0)}`.padEnd(13)} ` +\n `${m.marginTop}/${m.marginBottom}/${m.marginLeft}/${m.marginRight}`,\n );\n }\n\n lines.push(\"\", \"# checks\", \"\");\n if (result.warnings.length === 0) {\n lines.push(\"all geometry checks passed\");\n } else {\n for (const w of result.warnings) lines.push(`- ${w}`);\n }\n return lines.join(\"\\n\");\n}\n","/**\n * Compose AI-generated part PNGs into canvas-aligned, role-named layers for the\n * Iki auto-rig (`auto_rig_from_layers` / `@ikijs/editor` generateIkiFromLayerSet).\n * Each part is alpha-trimmed, resized to a target width, optionally mirrored,\n * and pasted at a chosen center on a shared transparent CANVAS x CANVAS canvas\n * — the nose by its 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 { cropToBuffer, decodePng } from \"./node-images\";\nimport { measureDir, type MeasureReport, type NoseSpeck } from \"./measure\";\nimport { denseCoreOf, isSpeckCore } from \"./measure-turn\";\nimport {\n AutoRigInputError,\n resolveInputDir,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n/**\n * Side of the square layer canvas, in px. NOT an input: the layout defaults\n * below place parts against this size (hair_front alone is 660px wide, and\n * sharp rejects a composite input larger than its destination), so a different\n * canvas would need its own layout. The tuning surface is `layout` overrides.\n */\nexport const CANVAS = 1100;\n\n// Iris width as a fraction of the sclera width. Anime irises fill most of the\n// eye opening and are clipped by the lids — the auto-rig clips iris->sclera at\n// runtime, so a large iris cannot spill. The first sample's 32% iris read as a\n// bead floating in white, so the defaults below use 56.25% (72px in a 128px\n// opening) to reduce excess white below the iris. A caller retunes eye size\n// through `layout.eye_L/eye_R.w` and MUST move `layout.iris_L/iris_R.w` with it\n// to keep that ratio.\nconst EYE_W = 128;\nconst IRIS_W = Math.round(EYE_W * 0.5625);\n\n/** The eyewhite source that prepEyeSplit() splits into sclera + lash. */\nconst EYEWHITE_SRC = \"eyewhite.png\";\n/** Luminance below this (0..255) = a dark lash/outline pixel in the eyewhite. */\nconst EYE_LASH_LUMA = 120;\n// Of the eye's dark pixels, keep only those in the TOP this-fraction as the lash\n// (drops the lower almond rim/outline) so the lash reads as an upper arc that\n// folds DOWN over the eye on blink, instead of a full ring that shrinks in place.\nconst LASH_KEEP_FRACTION = 0.5;\n\ninterface RoleLayout {\n /** Part file name in the parts dir (the eye pair's two are split in memory). */\n src: string;\n /** Center in canvas px, origin top-left, y down. */\n cx: number;\n cy: number;\n /** Target width in px. */\n w: number;\n /**\n * Target height in px. Omitted, the height follows the part's own aspect\n * ratio — which is the right default for every role whose drawing already has\n * the proportions it should. It exists for the one that does not: an eyewhite\n * comes back flatter than the reference often enough that three generations\n * asking for \"taller\" landed at 0.47, while stretching a flat white lens ~15%\n * is invisible and free. Set it on the sclera and its lash together or the\n * fold tears — they share one frame.\n */\n h?: number;\n optional?: boolean;\n mirror?: boolean;\n noTrim?: boolean;\n}\n\n/**\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/** 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. Tuned on the hero's medium nose: tip row 611\n * between eye row 475 and mouth row 633 (136/158 ≈ 0.86). Centring that nose\n * on the old default row 586 put its tip into the mouth.\n */\nconst NOSE_TIP_AT = 0.86;\n\n// ── DEFAULT LAYOUT (tune per character through `layout`) ──────────────────────\n// These defaults assume the standard framing the character skill prompts for\n// (a front-facing face centered on the canvas). If the rendered model is\n// misaligned, tune cx/cy/w through the `layout` override and re-run — composing\n// is cheap and the parts do not need regenerating.\n//\n// eyeSide reminder: eye_L = character's LEFT eye = screen RIGHT (larger cx).\n// 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. A part drawn the other way round is flipped\n// for free with `mirrorParts`.\n// eye_* = clean WHITE sclera (lashes recolored white) = the blink clip mask + fold.\n// iris_* = colored disc on top, clipped to the sclera, drives gaze.\n// lash_* = the dark lashes, a separate layer ABOVE the iris that folds down to\n// cover the closed-eye seam. eye_* and lash_* are split from a single\n// `eyewhite.png` (white almond + dark lashes) by prepEyeSplit().\nconst DEFAULT_LAYOUT = {\n // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir\n // without them still composes (head-only character).\n hair_back: { src: \"hair_back.png\", cx: 550, cy: 523, w: 800, optional: true },\n // The torso, cut off by the canvas bottom, so the character is not a\n // floating head. It rides its own `bodyDeformer`, which only breathes.\n body: { src: \"body.png\", cx: 550, cy: 1017, w: 840, optional: true },\n face: { src: \"face.png\", cx: 550, cy: 475, w: 400 },\n // The nose, drawn on its own (the face is drawn without one): the auto-rig\n // leads the head turn with it and keys the other features' slide on its\n // presence, so without it the features stay on the face plate. `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: 40, optional: true },\n mouth: { src: \"mouth.png\", cx: 550, cy: 619, w: 68 },\n // Cross-fades with `mouth` on ParamMouthOpenY (opacity, not scaleY) once the\n // auto-rig sees both roles. Same cx/w as `mouth` so the lip width matches;\n // its top edge (not center) lines up with the closed mouth's top edge since\n // the mouth opens downward from a fixed upper lip — hence the +2 cy nudge\n // rather than sharing cy outright. Optional: composes fine without it.\n mouth_open: {\n src: \"mouth_open.png\",\n cx: 550,\n cy: 621,\n w: 68,\n optional: true,\n },\n // eye_* (sclera) and lash_* share the eyewhite's cropped frame via noTrim (so\n // they are NOT re-bboxed independently): the upper lash stays anchored ABOVE\n // the sclera center, so on blink it folds DOWN over the eye like the sample\n // model instead of the whole eye shrinking in place. Same cx/cy/w.\n eye_L: { src: \"eyewhite_sclera.png\", cx: 657, cy: 475, w: EYE_W, mirror: true, noTrim: true }, // prettier-ignore\n eye_R: { src: \"eyewhite_sclera.png\", cx: 443, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n iris_L: { src: \"iris.png\", cx: 653, cy: 475, w: IRIS_W, mirror: false },\n iris_R: { src: \"iris.png\", cx: 447, cy: 475, w: IRIS_W, mirror: false },\n lash_L: {\n src: \"eyewhite_lash.png\",\n cx: 657,\n cy: 475,\n w: EYE_W,\n mirror: true,\n noTrim: true,\n },\n lash_R: { src: \"eyewhite_lash.png\", cx: 443, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n brow_L: { src: \"brow.png\", cx: 645, cy: 405, w: 135, mirror: false },\n brow_R: { src: \"brow.png\", cx: 455, cy: 405, w: 135, mirror: true },\n hair_front: { src: \"hair_front.png\", cx: 550, cy: 425, w: 660 },\n} satisfies Record<string, RoleLayout | NoseLayout>;\n\nexport type Role = keyof typeof DEFAULT_LAYOUT;\n\n/**\n * The merged layout, typed so a non-nose default that drops its `cy` fails to\n * compile: `resolveLayout` builds it from DEFAULT_LAYOUT.\n */\ntype ResolvedLayout = Record<Exclude<Role, \"nose\">, RoleLayout> & {\n nose: NoseLayout;\n};\n\n/** Draw order (back -> front), mirrors @ikijs/editor ROLE_TABLE order. */\nconst ORDER: Role[] = [\n \"hair_back\",\n \"body\",\n \"face\",\n \"nose\",\n \"mouth\",\n \"mouth_open\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"lash_L\",\n \"lash_R\",\n \"brow_L\",\n \"brow_R\",\n \"hair_front\",\n];\n\n/**\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: a skipped role's layer from an earlier run is\n * removed rather than left for the next tool to pick up.\n */\n outDir: string;\n layout?: LayoutOverride;\n /**\n * 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\nexport interface ComposedLayer {\n role: Role;\n path: string;\n /** Size of the placed part itself (the file is always CANVAS x CANVAS). */\n width: number;\n height: number;\n left: number;\n top: number;\n}\n\nexport type ComposeResult =\n | {\n ok: true;\n outDir: string;\n layers: ComposedLayer[];\n /** Roles whose optional part was absent from the parts dir. */\n skipped: Role[];\n preview: string;\n measure: MeasureReport;\n }\n | { ok: false; error: string };\n\n/**\n * Merge caller overrides onto the defaults. Input boundary: an unknown role, a\n * non-finite centre or an out-of-range width fails fast, path-qualified, before\n * any decode. `w` is capped at CANVAS so a part sized whole can never exceed\n * the canvas width (a nose, sized by its core, is checked in partBuffer);\n * `cx`/`cy` are unbounded here because a part may legitimately hang off an\n * edge — assertOnCanvas() rejects the one that lands nowhere on it.\n */\nfunction resolveLayout(overrides: LayoutOverride | undefined): ResolvedLayout {\n const resolved: ResolvedLayout = { ...DEFAULT_LAYOUT };\n if (overrides === undefined) return resolved;\n for (const [role, override] of Object.entries(overrides)) {\n if (!Object.prototype.hasOwnProperty.call(DEFAULT_LAYOUT, role)) {\n throw new AutoRigInputError(\n `layout.${role}: unknown role — expected one of ${Object.keys(DEFAULT_LAYOUT).join(\", \")}`,\n );\n }\n if (override === undefined) continue;\n // 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 if (!Number.isInteger(value) || value < 1 || value > CANVAS) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be an integer in 1..${CANVAS}, got ${String(value)}`,\n );\n }\n set[field] = value;\n }\n // The nose's entry may lack a cy, so it merges on its own; every other\n // role's stays a RoleLayout.\n const key = role as Role;\n if (key === \"nose\") resolved.nose = { ...resolved.nose, ...set };\n else resolved[key] = { ...resolved[key], ...set };\n }\n return resolved;\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/** 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: Role,\n cfg: Omit<RoleLayout, \"cy\">,\n partsDir: string,\n inMemory: Buffer | undefined,\n flipSource: boolean,\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 // Optional roles (hair_back, body, mouth_open) are absent from a\n // head-only parts dir; the auto-rig only requires face/eye_L/eye_R/mouth.\n if (cfg.optional) return null;\n // Name the role, not just the file: one source feeds two roles\n // (brow.png -> brow_L/brow_R), so the path alone does not say what broke.\n throw new AutoRigInputError(\n `missing part source for role \"${role}\": ${srcPath}`,\n );\n }\n const png = await decodePng(srcPath);\n // decodePng is the package's decode boundary: it caps the source at\n // MAX_INPUT_PIXELS and reports a bad/corrupt file as a path-qualified\n // AutoRigInputError, so the raw re-wrap below is already bounded.\n img = sharp(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {\n raw: { width: png.width, height: png.height, channels: 4 },\n });\n }\n // noTrim parts (the eye and lash pairs) keep their shared pre-cropped frame so\n // sclera and lash stay aligned; everything else is alpha-trimmed to its own bbox.\n if (!cfg.noTrim) img = img.trim({ threshold: 12 });\n // 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 || height > CANVAS) {\n const field = width > CANVAS || cfg.h === undefined ? \"w\" : \"h\";\n throw new AutoRigInputError(\n `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${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 — `body` is meant to be cut off by the canvas bottom — so the test\n * is INTERSECTION, not containment. A part that misses the canvas entirely\n * composes to a fully transparent layer that nothing downstream flags\n * (measureDir warns per measured layer, and an empty one has no geometry), so a\n * sign-flipped centre would otherwise read as success.\n */\nfunction assertOnCanvas(\n source: string,\n w: number,\n h: number,\n left: number,\n top: number,\n): void {\n if (left + w <= 0 || top + h <= 0 || left >= CANVAS || top >= CANVAS) {\n throw new AutoRigInputError(\n `${source}: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${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\">,\n cfg: RoleLayout,\n w: number,\n h: number,\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);\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(layout: ResolvedLayout, box: Box, w: number, h: number) {\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 );\n return { left, top };\n}\n\nfunction blankCanvas() {\n return sharp({\n create: {\n width: CANVAS,\n height: CANVAS,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n });\n}\n\n/**\n * Split eyewhite.png (white almond + dark lashes) into a clean white sclera\n * (the dark outline/lash recolored to white = the blink clip-mask shape) and a\n * dark UPPER-lash-only layer. Both are cropped to the SAME eye bbox so they stay\n * aligned (consumed with noTrim): the lash arc keeps its position at the top of\n * the sclera, so on blink it folds DOWN over the eye rather than the eye shrinking\n * in place.\n *\n * Both come back as PNG buffers. The script this ports wrote them back into the\n * parts dir, but that dir is an INPUT here (reads are deliberately unconfined),\n * so the tool never writes there — only under the confined outDir.\n */\nasync function prepEyeSplit(\n partsDir: string,\n): Promise<{ sclera: Buffer; lash: Buffer }> {\n const srcPath = path.join(partsDir, EYEWHITE_SRC);\n if (!fs.existsSync(srcPath)) {\n throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);\n }\n const { width: W, height: H, rgba: data } = await decodePng(srcPath);\n\n // Eye content bbox (alpha) → the shared cropped frame for both outputs.\n let minX = W;\n let minY = H;\n let maxX = -1;\n let maxY = -1;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (data[(y * W + x) * 4 + 3] > 8) {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n }\n }\n if (maxX < 0) {\n throw new AutoRigInputError(`eyewhite is fully transparent: ${srcPath}`);\n }\n // Keep only the upper lash: dark pixels above this row become the lash layer.\n const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);\n\n const sclera = Buffer.from(data);\n const lash = Buffer.from(data);\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n const i = (y * W + x) * 4;\n const lum = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];\n const isDark = data[i + 3] > 0 && lum < EYE_LASH_LUMA;\n if (isDark) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255; // dark -> white\n if (!(isDark && y <= lashCutoffY)) lash[i + 3] = 0; // keep upper dark only\n }\n }\n const region = {\n x: minX,\n y: minY,\n w: maxX - minX + 1,\n h: maxY - minY + 1,\n };\n return {\n sclera: await cropToBuffer(sclera, W, H, region),\n lash: await cropToBuffer(lash, W, H, region),\n };\n}\n\n/**\n * Compose a parts directory into role-named layers plus a flattened preview,\n * then measure the result so the caller sees the geometry checks inline.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function composeLayersFromParts(\n input: ComposeInput,\n): Promise<ComposeResult> {\n try {\n // Resolve the output dir FIRST (fail-fast): reject a missing or escaping\n // target before spending the decode budget on a run that cannot be written.\n const outDir = resolveOutputDir(input.outDir);\n const partsDir = resolveInputDir(input.partsDir);\n // resolveOutputDir already realpath's outDir; resolveInputDir does not (its\n // reads are deliberately unconfined), so realpath partsDir here too before\n // comparing — otherwise a symlink alias of the same directory would slip\n // past a lexical check. Composing a parts dir into itself would overwrite\n // originals like face.png/hair_front.png with resized, cropped layers, and\n // skipped-role cleanup would delete sources with no surviving part.\n if (fs.realpathSync(partsDir) === outDir) {\n throw new AutoRigInputError(\n `partsDir and outDir resolve to the same directory (${outDir}): composing would overwrite the source parts`,\n );\n }\n const layout = resolveLayout(input.layout);\n 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\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: Role;\n part: { buf: Buffer; w: number; h: number };\n left: number;\n top: number;\n }[] = [];\n const skipped: Role[] = [];\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 const cfg = layout[role];\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 );\n if (part === null) {\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 (role === \"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));\n } else {\n ({ left, top } = placement(role, layout[role], part.w, part.h));\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 each skipped role's layer from an earlier compose into the same\n // dir: left behind it would contradict `skipped`, since measureDir globs\n // 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 skipped) {\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()\n .composite([{ input: part.buf, left, top }])\n .png()\n .toBuffer();\n const outPath = path.join(outDir, `${role}.png`);\n writeFileAtomic(outPath, layer);\n layers.push({\n role,\n path: outPath,\n width: part.w,\n height: part.h,\n left,\n top,\n });\n preview.push({ input: part.buf, left, top });\n }\n\n // Flattened preview over a light bg so transparency reads clearly.\n const previewPng = await sharp({\n create: {\n width: CANVAS,\n height: CANVAS,\n channels: 4,\n background: { r: 245, g: 245, b: 248, alpha: 1 },\n },\n })\n .composite(preview)\n .png()\n .toBuffer();\n const previewPath = path.join(outDir, \"preview.png\");\n writeFileAtomic(previewPath, previewPng);\n\n return {\n ok: true,\n outDir,\n layers,\n skipped,\n preview: previewPath,\n measure: await measureDir(outDir, noseSpeck),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n validateIki,\n describeIki,\n listStandardParameters,\n autoRigFromLayers,\n} from \"./tools\";\nimport { composeLayersFromParts } from \"./compose\";\nimport { measureLayers, formatMeasureReport } from \"./measure\";\nimport { measureTurnReference, formatTurnReport } from \"./measure-turn\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers; returns an error for an invalid model.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"Auto-rigs role-named PNG layers (face, eye_L/eye_R, mouth required; iris_L/R, brow_L/R, hair_front, etc. optional) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n quantizeColors: z\n .number()\n .int()\n .min(2)\n .max(256)\n .optional()\n .describe(\n \"Palette-quantize the atlas PNG to this many colours (2..256). Flat-shaded art keeps its look at 256 and the model shrinks to about a quarter; omit for lossless. 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 Live2D 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). 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 Live2D profile the rig defaults to — only what the Live2D samples themselves disagree on: `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.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.58), `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, nose are optional — without a nose layer the rig does not slide the features on the head turn. 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.\",\n inputSchema: {\n partsDir: z\n .string()\n .describe(\n \"Directory of the source part PNGs (resolved against cwd).\",\n ),\n outDir: z\n .string()\n .describe(\n \"Existing directory to write the role layer PNGs + preview.png into (resolved against cwd; must already exist; confined to the working directory). Reused across runs: a role this run skips has its stale PNG from an earlier run deleted.\",\n ),\n layout: z\n .record(\n z.string(),\n z\n .object({\n cx: z.number(),\n cy: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .partial(),\n )\n .optional()\n .describe(\n \"Per-role override merged over the built-in defaults, keyed by role — hair_back, body, face, nose, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front — e.g. `{ eye_L: { cx: 660 } }`. `w` and `h` are integers in 1..1100; omit `h` to keep the part's own aspect, set it to stretch. 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.86 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.\",\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) and brow.png as the brow on the screen RIGHT (thick head at the image's left end, tail at its 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 },\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). 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"],"mappings":";AAAA,OAAOA,WAAU;AACjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAQK;;;ACVP,OAAO,WAAW;AAElB,SAAS,mBAAmB,qBAAqB;;;ACJjD,OAAO,QAAQ;AACf,OAAO,UAAU;AAGV,IAAM,aAAa;AAEnB,IAAM,gBAAgB;AAEtB,IAAM,iBAAiB;AAEvB,IAAM,iBAAiB,OAAO;AAE9B,IAAM,mBAAmB,OAAO;AAGhC,IAAM,mBAAmB,KAAK,OAAO;AAGrC,IAAM,mBAAmB,IAAI,OAAO;AAOp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AA,UAC9D,mBAAmB,EAAE,IAAI,OAAO,MAAM;AAAA,UACtC,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["path","placement","path","placement","path","headHalfOf","path","fs","path","fs","path","fs","path","sharp","sharp","path","fs"]}
|