@ikijs/mcp 0.4.0 → 0.5.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 +2 -2
- package/dist/{chunk-F5RUDS6T.mjs → chunk-MDSZNVVK.mjs} +44 -23
- package/dist/chunk-MDSZNVVK.mjs.map +1 -0
- package/dist/cli.js +43 -22
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +43 -22
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-F5RUDS6T.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -31,8 +31,8 @@ Composes a directory of AI-generated part PNGs into canvas-aligned, role-named l
|
|
|
31
31
|
|
|
32
32
|
- **`partsDir`** — directory of the source part PNGs (resolved against the server's working directory). Required sources: `face.png`, `eyewhite.png` (split into the sclera + lash layers), `iris.png`, `mouth.png`, `brow.png`, `hair_front.png`. Optional: `hair_back.png`, `body.png`, `mouth_open.png` — a parts dir without them still composes, minus those roles.
|
|
33
33
|
- **`outDir`** — an existing directory (resolved against the working directory, confined to it exactly like `auto_rig_from_layers`'s `outputPath`; the tool never creates directories) to write the role layer PNGs and a flattened `preview.png` into. Reusing a directory across runs is intentional — a role this run skips (e.g. composing a head-only set that omits `body`) has its stale `<role>.png` from an earlier run deleted, so the directory always holds exactly this run's roles.
|
|
34
|
-
- **`layout`** — optional per-role override merged over the built-in defaults, e.g. `{ "eye_L": { "cx": 660 } }`, so a character can be retuned by re-running compose rather than editing a script. Each of `cx`, `cy`, `w` is optional; `w` must be
|
|
35
|
-
- **Result** — on success the text is the written layer paths (one per line) followed by the same geometry report `measure_layers` returns; `structuredContent` is `{ ok: true, outDir, layers, skipped, preview, measure }`. Invalid input (a missing required part, an unknown `layout` role, an out-of-range `w`, a part that lands entirely off-canvas, a non-existent `outDir`) returns `{ ok: false, error }` with `INVALID: …` text.
|
|
34
|
+
- **`layout`** — optional per-role override merged over the built-in defaults, e.g. `{ "eye_L": { "cx": 660 } }`, so a character can be retuned by re-running compose rather than editing a script. Each of `cx`, `cy`, `w`, `h` is optional; `w` and `h` must be integers in 1..1100 (the canvas size). Omitting `h` keeps the part's own aspect ratio, which is what every role wants until one does not: a generated eyewhite often comes back flatter than its reference, and stretching a flat white lens costs nothing where regenerating it is billed and unreliable. Set `h` on a sclera and its lash together — they share one frame, and the blink fold tears if they diverge.
|
|
35
|
+
- **Result** — on success the text is the written layer paths (one per line) followed by the same geometry report `measure_layers` returns; `structuredContent` is `{ ok: true, outDir, layers, skipped, preview, measure }`. Invalid input (a missing required part, an unknown `layout` role, an out-of-range `w` or `h`, a part that lands entirely off-canvas, a non-existent `outDir`) returns `{ ok: false, error }` with `INVALID: …` text.
|
|
36
36
|
|
|
37
37
|
### `measure_layers`
|
|
38
38
|
|
|
@@ -498,6 +498,7 @@ var EYE_ASPECT_MIN = 0.5;
|
|
|
498
498
|
var IRIS_OFFSET_MAX_X = 3;
|
|
499
499
|
var IRIS_OFFSET_MAX_Y = 10;
|
|
500
500
|
var EDGE_SOLID_MAX = 0.5;
|
|
501
|
+
var LASH_CENTRE_TOL_FRAC = 0.03;
|
|
501
502
|
var EDGE_RUN_MIN_PX = 40;
|
|
502
503
|
var FLAT_CUT_MAX_FRAC = 0.1;
|
|
503
504
|
var FLAT_CUT_MIN_PX = 40;
|
|
@@ -602,15 +603,24 @@ async function measureDir(absDir) {
|
|
|
602
603
|
const warnings = [];
|
|
603
604
|
for (const [role, m] of Object.entries(layers)) {
|
|
604
605
|
const edges = [
|
|
605
|
-
["top", m.edgeTop, m.w],
|
|
606
|
-
["left", m.edgeLeft, m.h],
|
|
607
|
-
["right", m.edgeRight, m.h]
|
|
606
|
+
["top", m.edgeTop, m.w, m.marginTop],
|
|
607
|
+
["left", m.edgeLeft, m.h, m.marginLeft],
|
|
608
|
+
["right", m.edgeRight, m.h, m.marginRight]
|
|
608
609
|
];
|
|
609
|
-
if (role !== "body")
|
|
610
|
-
|
|
610
|
+
if (role !== "body")
|
|
611
|
+
edges.push(["bottom", m.edgeBottom, m.w, m.marginBottom]);
|
|
612
|
+
for (const [side, v, span, margin] of edges) {
|
|
611
613
|
if (v > EDGE_SOLID_MAX && v * span >= EDGE_RUN_MIN_PX) {
|
|
614
|
+
const remedy = margin === 0 ? (
|
|
615
|
+
// margin 0 is consistent with a clipped placement AND with art
|
|
616
|
+
// already cropped flush that happens to sit on the boundary, and
|
|
617
|
+
// the flattened layer cannot separate them — so name the free
|
|
618
|
+
// move rather than the cause. If moving it inward leaves the
|
|
619
|
+
// edge opaque, the drawing is the one at fault.
|
|
620
|
+
`it sits flush against the canvas ${side}, which a clipped placement and already-cropped art both produce. Move it inward first \u2014 retune layout.${role}.cx/cy/w, free \u2014 and remeasure; regenerate only if the edge is still opaque with margin to spare.`
|
|
621
|
+
) : `its own drawing runs to the frame ${margin} px inside the canvas \u2014 regenerate that part with empty margin on that side. Billed.`;
|
|
612
622
|
warnings.push(
|
|
613
|
-
`${role}: ${pct(v)} of its ${side} edge is opaque \u2014 the art is cut off there, which shows as a straight seam once the head turns.
|
|
623
|
+
`${role}: ${pct(v)} of its ${side} edge is opaque \u2014 the art is cut off there, which shows as a straight seam once the head turns. Cause: ${remedy}`
|
|
614
624
|
);
|
|
615
625
|
}
|
|
616
626
|
}
|
|
@@ -631,7 +641,7 @@ async function measureDir(absDir) {
|
|
|
631
641
|
const aspect = eye.h / eye.w;
|
|
632
642
|
if (aspect < EYE_ASPECT_MIN) {
|
|
633
643
|
warnings.push(
|
|
634
|
-
`eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} \u2014 a round iris cannot sit inside it. Regenerate the eyewhite taller
|
|
644
|
+
`eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} \u2014 a round iris cannot sit inside it. Free fix first: set layout.eye_${side}.h and layout.lash_${side}.h to ${Math.ceil(eye.w * EYE_ASPECT_MIN)} (both, or the fold tears) \u2014 stretching a flat white lens is invisible. Regenerate the eyewhite taller only if that distorts the lash.`
|
|
635
645
|
);
|
|
636
646
|
}
|
|
637
647
|
if (iris) {
|
|
@@ -652,7 +662,7 @@ async function measureDir(absDir) {
|
|
|
652
662
|
if (lash) {
|
|
653
663
|
const dx = lash.bboxCx - eye.bboxCx;
|
|
654
664
|
const dTop = lash.marginTop - eye.marginTop;
|
|
655
|
-
if (Math.abs(dx) >
|
|
665
|
+
if (Math.abs(dx) > eye.w * LASH_CENTRE_TOL_FRAC || Math.abs(dTop) > 0.5) {
|
|
656
666
|
warnings.push(
|
|
657
667
|
`lash_${side}: centre is ${dx.toFixed(1)} px and top edge ${dTop.toFixed(1)} px off eye_${side}. They are split from one source and MUST share cx/cy/w in layout, or the blink fold tears. Retune to match.`
|
|
658
668
|
);
|
|
@@ -801,13 +811,15 @@ function resolveLayout(overrides) {
|
|
|
801
811
|
}
|
|
802
812
|
next[field] = value;
|
|
803
813
|
}
|
|
804
|
-
|
|
805
|
-
|
|
814
|
+
for (const field of ["w", "h"]) {
|
|
815
|
+
const value = override[field];
|
|
816
|
+
if (value === void 0) continue;
|
|
817
|
+
if (!Number.isInteger(value) || value < 1 || value > CANVAS) {
|
|
806
818
|
throw new AutoRigInputError(
|
|
807
|
-
`layout.${role}
|
|
819
|
+
`layout.${role}.${field} must be an integer in 1..${CANVAS}, got ${String(value)}`
|
|
808
820
|
);
|
|
809
821
|
}
|
|
810
|
-
next
|
|
822
|
+
next[field] = value;
|
|
811
823
|
}
|
|
812
824
|
resolved[role] = next;
|
|
813
825
|
}
|
|
@@ -842,15 +854,19 @@ async function partBuffer(role, cfg, partsDir, inMemory) {
|
|
|
842
854
|
if (!cfg.noTrim) img = img.trim({ threshold: 12 });
|
|
843
855
|
if (cfg.mirror) img = img.flop();
|
|
844
856
|
const trimmed = await img.png().toBuffer({ resolveWithObject: true });
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
if (scaledH > CANVAS) {
|
|
849
|
-
throw new AutoRigInputError(
|
|
850
|
-
`layout.${role}.w: resized part ${cfg.w}x${scaledH} exceeds the ${CANVAS} canvas`
|
|
857
|
+
if (cfg.h === void 0) {
|
|
858
|
+
const scaledH = Math.round(
|
|
859
|
+
trimmed.info.height * cfg.w / trimmed.info.width
|
|
851
860
|
);
|
|
861
|
+
if (scaledH > CANVAS) {
|
|
862
|
+
throw new AutoRigInputError(
|
|
863
|
+
`layout.${role}.w: resized part ${cfg.w}x${scaledH} exceeds the ${CANVAS} canvas`
|
|
864
|
+
);
|
|
865
|
+
}
|
|
852
866
|
}
|
|
853
|
-
const resized = await sharp2(trimmed.data).resize(
|
|
867
|
+
const resized = await sharp2(trimmed.data).resize(
|
|
868
|
+
cfg.h === void 0 ? { width: cfg.w } : { width: cfg.w, height: cfg.h, fit: "fill" }
|
|
869
|
+
).png().toBuffer({ resolveWithObject: true });
|
|
854
870
|
return {
|
|
855
871
|
buf: resized.data,
|
|
856
872
|
w: resized.info.width,
|
|
@@ -997,7 +1013,7 @@ async function composeLayersFromParts(input) {
|
|
|
997
1013
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
998
1014
|
import { z } from "zod";
|
|
999
1015
|
function createIkiMcpServer() {
|
|
1000
|
-
const server = new McpServer({ name: "iki", version: "0.
|
|
1016
|
+
const server = new McpServer({ name: "iki", version: "0.5.0" });
|
|
1001
1017
|
server.registerTool(
|
|
1002
1018
|
"validate_iki",
|
|
1003
1019
|
{
|
|
@@ -1108,9 +1124,14 @@ function createIkiMcpServer() {
|
|
|
1108
1124
|
),
|
|
1109
1125
|
layout: z.record(
|
|
1110
1126
|
z.string(),
|
|
1111
|
-
z.object({
|
|
1127
|
+
z.object({
|
|
1128
|
+
cx: z.number(),
|
|
1129
|
+
cy: z.number(),
|
|
1130
|
+
w: z.number(),
|
|
1131
|
+
h: z.number()
|
|
1132
|
+
}).partial()
|
|
1112
1133
|
).optional().describe(
|
|
1113
|
-
"Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, face, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front \u2014 e.g. `{ eye_L: { cx: 660 } }
|
|
1134
|
+
"Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, face, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front \u2014 e.g. `{ eye_L: { cx: 660 } }`. `w` and `h` are integers in 1..1100; omit `h` to keep the part's own aspect, set it to stretch (set it on a sclera and its lash together, or the blink fold tears)."
|
|
1114
1135
|
)
|
|
1115
1136
|
}
|
|
1116
1137
|
},
|
|
@@ -1173,4 +1194,4 @@ export {
|
|
|
1173
1194
|
composeLayersFromParts,
|
|
1174
1195
|
createIkiMcpServer
|
|
1175
1196
|
};
|
|
1176
|
-
//# sourceMappingURL=chunk-
|
|
1197
|
+
//# sourceMappingURL=chunk-MDSZNVVK.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tools.ts","../src/node-images.ts","../src/limits.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 generateIkiFromLayerSet,\n parseLayerRoles,\n type LayerInput,\n type AtlasAssignment,\n} from \"@ikijs/editor\";\nimport {\n decodePng,\n detectAlphaBbox,\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 quantizeColors?: number;\n}\n\nexport type AutoRigResult =\n | {\n ok: true;\n path: string;\n canvas: { width: number; height: number };\n partCount: number;\n atlasBytes: number;\n }\n | { ok: false; error: string };\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 * 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 * Re-host of examples/editor/src/store.ts `importLayerSet` with the three DOM\n * pixel functions swapped for the sharp-backed ./node-images helpers; the pure\n * model math is reused from @ikijs/editor.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) → `{ ok:false }`;\n * any other throw (invariant break, programmer bug) propagates to `isError`.\n */\nexport async function autoRigFromLayers(\n input: AutoRigInput,\n): Promise<AutoRigResult> {\n try {\n const layers = input.layers;\n if (!Array.isArray(layers) || layers.length === 0) {\n throw new AutoRigInputError(\"layers must be a non-empty array\");\n }\n if (layers.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers: ${layers.length} > ${MAX_LAYERS}`,\n );\n }\n\n // Resolve the output path FIRST (fail-fast): reject a bad/escaping/non-.iki\n // target before spending the image-decode budget on a request that can't\n // be written anyway.\n const outPath = resolveOutputPath(\n input.outputPath ?? \"auto-rigged-model.iki\",\n );\n const quantizeColors = input.quantizeColors;\n if (\n quantizeColors !== undefined &&\n (!Number.isInteger(quantizeColors) ||\n quantizeColors < 2 ||\n quantizeColors > 256)\n ) {\n throw new AutoRigInputError(\n `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`,\n );\n }\n\n // Resolve paths + role-map up front (input boundary; no decode needed).\n // parseLayerRoles throws on unknown/duplicate/missing-required roles.\n const resolvedLayers = layers.map((layer) => {\n const resolved = resolveInputPath(layer.path);\n return { resolved, fileName: layer.fileName ?? path.basename(resolved) };\n });\n const rolePairs = expectInput(\"role parsing\", () =>\n parseLayerRoles(resolvedLayers.map((r) => r.fileName)),\n );\n const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));\n\n // Decode + alpha-bbox + crop SEQUENTIALLY: only ONE full-canvas RGBA buffer\n // is live at a time (a Promise.all over all layers would hold every decoded\n // buffer at once, allowing a multi-GB spike on inputs that each pass\n // MAX_LAYER_DIM). MAX_TOTAL_PIXELS bounds the aggregate work. Canvas size =\n // the first layer's full PNG dims (parity with buildLayerInputs in\n // examples/editor/src/auto-rig-image.ts); all layers must match it.\n let canvasW = 0;\n let canvasH = 0;\n let totalPixels = 0;\n const layerInputs: LayerInput[] = [];\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 } else if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `layer \"${fileName}\" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n\n const role = roleByFileName.get(fileName);\n if (role === undefined) {\n throw new AutoRigInputError(`no role resolved for \"${fileName}\"`);\n }\n let bbox: { x: number; y: number; w: number; h: number };\n try {\n bbox = detectAlphaBbox(png.rgba, png.width, png.height);\n } catch (e) {\n // Enrich the empty-layer error with role + file context.\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": ${msg}`,\n );\n }\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\n // 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 layerInputs.push({\n role,\n fileName,\n canvasW,\n canvasH,\n bbox,\n cropW: bbox.w,\n cropH: bbox.h,\n });\n crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n\n // Internal pipeline — direct calls. By here roles + bboxes are validated, so\n // a throw is an invariant break / bug and must propagate to `isError`.\n const model = generateIkiFromLayerSet(layerInputs, {\n width: canvasW,\n height: canvasH,\n });\n const doc = new EditorDocument(model);\n\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n );\n if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`,\n );\n }\n\n const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);\n if (dataUri.length > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n const partTextureAssignments: AtlasAssignment[] = crops.map((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n return {\n partId: crop.id,\n uv: uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n }),\n };\n });\n\n doc.applyAtlas({ textures: [{ source: dataUri }], partTextureAssignments });\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(doc.getModel());\n\n // Write to a fresh temp file in the verified directory, then atomically\n // rename over the target — see writeFileAtomic for why an existing `.iki`\n // symlink at outPath cannot redirect the write outside the working tree.\n writeFileAtomic(outPath, JSON.stringify(finalModel));\n\n return {\n ok: true,\n path: outPath,\n canvas: { width: canvasW, height: canvasH },\n partCount: finalModel.parts.length,\n atlasBytes: dataUri.length,\n };\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\nexport interface AtlasCrop {\n id: string;\n buffer: Buffer;\n width: number;\n height: number;\n}\n\n/**\n * Composite packed crops onto a transparent page and return a base64 PNG data\n * URI. Each crop's right + bottom edge pixels are extruded across the padding\n * gutter (replicating renderAtlas's right/bottom/corner drawImage extrudes in\n * examples/editor/src/atlas-image.ts) so LINEAR sampling at the inset UV never\n * reads a transparent neighbor texel. packAtlas reserves padding on the RIGHT\n * and BOTTOM only, so a one-sided `extend` matches its layout exactly.\n *\n * Crops are looked up BY placement.id (packAtlas sorts placements by id).\n * ASSUMES a non-empty layout (the empty case is handled by the caller).\n *\n * `quantizeColors` palette-quantizes the page PNG (libimagequant via sharp).\n * Flat-shaded character art keeps its look at 256 colours while the atlas\n * drops to roughly a quarter of its lossless size — the hero demo went from\n * 3.5MB to 0.9MB at a mean channel delta of 1.5/255 — which is what makes a\n * generated model shippable on a page. Omitted = lossless, as before.\n */\nexport async function renderAtlasToDataUri(\n crops: AtlasCrop[],\n layout: AtlasLayout,\n quantizeColors?: number,\n): Promise<string> {\n const byId = new Map<string, AtlasCrop>();\n for (const crop of crops) byId.set(crop.id, crop);\n\n const pad = layout.padding;\n\n const composites = await Promise.all(\n layout.placements.map(async (placement) => {\n const crop = byId.get(placement.id);\n if (crop === undefined) {\n throw new AutoRigInputError(\n `no crop for atlas placement \"${placement.id}\"`,\n );\n }\n // Replicate the right + bottom (+ corner) edge pixels into the gutter.\n const input =\n pad > 0\n ? await sharp(crop.buffer)\n .extend({ right: pad, bottom: pad, extendWith: \"copy\" })\n .png()\n .toBuffer()\n : crop.buffer;\n return { input, left: placement.x, top: placement.y };\n }),\n );\n\n const page = await sharp({\n create: {\n width: layout.pageWidth,\n height: layout.pageHeight,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite(composites)\n .png(\n quantizeColors === undefined\n ? {}\n : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 },\n )\n .toBuffer();\n\n return `data:image/png;base64,${page.toString(\"base64\")}`;\n}\n","/**\n * Resource guards + fail-fast path resolution and atomic writes for the Node\n * auto-rig tool.\n *\n * These constants bound an agent-supplied layer set so a malformed or oversized\n * request fails fast with a path-qualified message rather than exhausting memory\n * or producing a multi-MB MCP response. All guards REJECT (never downscale).\n *\n * `sharp` must stay confined to @ikijs/mcp — none of @ikijs/engine, @ikijs/editor,\n * or @ikijs/format may take a heavy Node image dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/** Max number of input layers in one request. */\nexport const MAX_LAYERS = 64;\n/** Max per-side dimension (px) of any single input PNG. */\nexport const MAX_LAYER_DIM = 4096;\n/** Max per-side dimension (px) of the derived canvas. */\nexport const MAX_CANVAS_DIM = 4096;\n/** Max area (px²) of the packed atlas page. */\nexport const MAX_ATLAS_AREA = 4096 * 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request, so a set of\n * many large PNGs cannot exhaust memory even though each passes MAX_LAYER_DIM. */\nexport const MAX_TOTAL_PIXELS = 64 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model. */\nexport const MAX_OUTPUT_BYTES = 5 * 1024 * 1024;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Reject an empty/whitespace or URL-looking caller-supplied path, shared by\n * {@link resolveInputPath} and {@link resolveInputDir}. `noun` and `kind`\n * shape the thrown message so each caller reports in its own vocabulary\n * (e.g. a directory input was never supposed to look like \"a file path\").\n */\nfunction rejectEmptyOrUrl(inputPath: string, noun: string, kind: string): void {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(`${noun} is empty`);\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `${noun} must be a ${kind}, not a URL: ${inputPath}`,\n );\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which reads its part PNGs\n * from wherever the image generator dropped them (a downloads folder, a scratch\n * dir) while everything it writes — the composed layers, the model — stays\n * under the working directory. Revisit only if this server ever runs with wider\n * privileges than the person driving it. The same reasoning covers\n * {@link resolveInputDir}, its directory counterpart.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string): string {\n rejectEmptyOrUrl(inputPath, \"layer path\", \"file path\");\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layer file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `layer path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/** Directory counterpart to {@link resolveInputPath} — see its doc comment. */\nexport function resolveInputDir(dirPath: string): string {\n rejectEmptyOrUrl(dirPath, \"layers dir\", \"directory path\");\n const resolved = path.resolve(process.cwd(), dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layers dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`layers path is not a directory: ${resolved}`);\n }\n return resolved;\n}\n\n/**\n * Confine an already-verified-to-exist directory to the MCP process working\n * directory, comparing REAL paths (statSync/writeFileSync follow symlinks, so\n * a lexical startsWith check can be bypassed by a symlinked dir under cwd).\n * Shared by {@link resolveOutputPath} and {@link resolveOutputDir} — both are\n * write-side boundaries where an unrestricted target is an\n * arbitrary-file-overwrite surface. `label` and `original` shape the thrown\n * message (path-qualified with the caller's original, unresolved string).\n */\nfunction confineToWorkingDirectory(\n root: string,\n dir: string,\n label: string,\n original: string,\n): string {\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `${label} escapes the working directory: ${original}`,\n );\n }\n return realDir;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `.iki` AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(outputPath: string): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(\".iki\")) {\n throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n const realDir = confineToWorkingDirectory(\n root,\n dir,\n \"output path\",\n outputPath,\n );\n return path.join(realDir, path.basename(resolved));\n}\n\n/**\n * Resolve a caller-supplied output DIRECTORY against the MCP process cwd.\n * Unlike {@link resolveOutputPath}, no filename is appended — the directory\n * itself must already exist (the tool never creates directories, fail-fast) —\n * and is confined via {@link confineToWorkingDirectory}. Returns the\n * realpath'd directory.\n */\nexport function resolveOutputDir(dirPath: string): string {\n if (typeof dirPath !== \"string\" || dirPath.trim() === \"\") {\n throw new AutoRigInputError(\"output dir is empty\");\n }\n const root = process.cwd();\n const resolved = path.resolve(root, dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`output dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output dir is not a directory: ${resolved}`);\n }\n return confineToWorkingDirectory(root, resolved, \"output dir\", dirPath);\n}\n\n/**\n * Write `data` to `outPath` atomically: write to a fresh temp file in the\n * same directory, then `renameSync` over the target. `rename` REPLACES the\n * destination directory entry rather than following it, so an existing\n * symlink at `outPath` cannot redirect the write outside the working tree.\n * Throws AutoRigInputError(\"write: …\") on failure.\n */\nexport function writeFileAtomic(\n outPath: string,\n data: string | Uint8Array,\n): void {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(tmp, data);\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n } catch (e) {\n throw new AutoRigInputError(\n `write: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n","/**\n * Measure composed Iki role layers and flag the failure modes that have\n * actually shipped broken characters. Read-only: it never edits anything.\n *\n * Ports the geometry checks that shipped as a script in the Claude Code plugin,\n * so a plugin user gets them from the MCP server instead of an ad-hoc `sharp`\n * install. They exist because \"the eyes look too big\" is not actionable but\n * \"the iris is 33% of the sclera width, target 0.45-0.72\" is. Every check below\n * is one that cost a real regeneration or re-tune round to find by eye.\n *\n * `sharp` must stay confined to @ikijs/mcp; the decode goes through\n * ./node-images, this package's single image-decode boundary.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { decodePng } from \"./node-images\";\nimport { AutoRigInputError, MAX_LAYERS, resolveInputDir } from \"./limits\";\n\n// Iris width as a fraction of sclera width. Below the floor the eye reads as a\n// bead floating in white — that is the failure this check was written for, and\n// it caught a model that shipped at 0.33. The ceiling was a guess and it was\n// too tight: measured on a real anime reference the iris runs about 0.70 of the\n// eye, with the white reduced to corner crescents, so 0.6 flagged the correct\n// value as a fault three rounds running.\nconst IRIS_RATIO_MIN = 0.45;\nconst IRIS_RATIO_MAX = 0.72;\n// A sclera flatter than this cannot hold a round iris: the iris overflows the\n// lids no matter how narrow it is.\nconst EYE_ASPECT_MIN = 0.5;\n// How far the iris centre may sit from the white's centre of mass. The two axes\n// are not the same problem. Sideways drift is always a fault — that is the bug\n// this check was written for, a lash that fell out of sync with its sclera by\n// 14px. Vertically the reference itself rides its iris HIGH, tucked under the\n// lash with roughly a sixth of the aperture showing as white below it, so a\n// deliberate lift of that order is correct and a 3px ceiling flagged it.\nconst IRIS_OFFSET_MAX_X = 3;\nconst IRIS_OFFSET_MAX_Y = 10;\n// A cropped part shows a long, nearly-continuous opaque run along one bbox edge,\n// and that straight seam appears the moment the head turns. A round part's edge\n// row is a short tangent run, so a fraction test alone flags every iris; both a\n// high fraction AND real length are required to separate the two. Observed:\n// genuine crops read 60-93%, circle tangents 8-14%.\nconst EDGE_SOLID_MAX = 0.5;\n/** Lash-vs-sclera ink-centre drift tolerated as intrinsic asymmetry, as a\n * fraction of the eye width. See the check for why it is not zero. */\nconst LASH_CENTRE_TOL_FRAC = 0.03;\nconst EDGE_RUN_MIN_PX = 40;\n// Longest straight \"art appears out of nothing\" run tolerated inside a part, as\n// a fraction of its width. A body generated with hair draped over the shoulders\n// had that hair cut flat by its own frame; the cut hid behind the head at rest\n// and opened into a seam on turn. Measured: that part ran 15% of its width,\n// a clean one 5%, so the boundary sits between them.\nconst FLAT_CUT_MAX_FRAC = 0.1;\n// ...and long in absolute terms. A mouth's upper lip is a naturally horizontal\n// run that clears the fraction test on a narrow part while being only ~15px.\nconst FLAT_CUT_MIN_PX = 40;\n// The cut is antialiased, so the transition is a soft cliff rather than\n// transparent-to-opaque; 8/200 finds nothing at all on real art.\nconst FLAT_CUT_ALPHA_ABOVE = 120;\nconst FLAT_CUT_ALPHA_BELOW = 140;\n\n/** Alpha-derived geometry of one layer, in canvas pixels. */\nexport interface LayerStats {\n w: number;\n h: number;\n /** Longest flat cut through the art, and the row it runs along (-1 if none). */\n flatCutRun: number;\n flatCutY: number;\n bboxCx: number;\n bboxCy: number;\n massCx: number;\n massCy: number;\n /** Distance from the layer's content to each canvas edge. */\n marginTop: number;\n marginBottom: number;\n marginLeft: number;\n marginRight: number;\n /** Fraction of each bbox edge that is opaque. */\n edgeTop: number;\n edgeBottom: number;\n edgeLeft: number;\n edgeRight: number;\n canvasW: number;\n canvasH: number;\n}\n\nexport interface MeasureReport {\n /** Measured stats by role (the layer's file name without `.png`). */\n layers: Record<string, LayerStats>;\n /** Roles whose PNG is fully transparent — nothing to measure. */\n empty: string[];\n warnings: string[];\n}\n\nexport type MeasureResult =\n | ({ ok: true; layersDir: string; passed: boolean } & MeasureReport)\n | { ok: false; error: string };\n\nexport interface MeasureInput {\n /** Directory of role-named layer PNGs (relative paths resolve against cwd). */\n layersDir: string;\n}\n\n/**\n * Scan one layer PNG's alpha channel. Returns null for a fully transparent\n * layer. A decode failure surfaces as a path-qualified AutoRigInputError.\n */\nexport async function layerStats(filePath: string): Promise<LayerStats | null> {\n const { width: W, height: H, rgba } = await decodePng(filePath);\n const alpha = (x: number, y: number) => rgba[(y * W + x) * 4 + 3];\n\n let minX = W;\n let minY = H;\n let maxX = -1;\n let maxY = -1;\n let sumX = 0;\n let sumY = 0;\n let n = 0;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (alpha(x, y) > 8) {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n sumX += x;\n sumY += y;\n n++;\n }\n }\n }\n if (maxX < 0) return null; // fully transparent\n\n const edge = (pts: number[]) =>\n pts.filter((v) => v > 200).length / pts.length;\n const top: number[] = [];\n const bottom: number[] = [];\n const left: number[] = [];\n const right: number[] = [];\n for (let x = minX; x <= maxX; x++) {\n top.push(alpha(x, minY));\n bottom.push(alpha(x, maxY));\n }\n for (let y = minY; y <= maxY; y++) {\n left.push(alpha(minX, y));\n right.push(alpha(maxX, y));\n }\n\n // Longest contiguous run of pixels where the art appears out of nothing along\n // one row — transparent above, opaque below. Organic art (hair, cloth) meets\n // its silhouette at an angle, so a long FLAT run like this means the source\n // image was cropped through the drawing. It is often interior to the bbox\n // (a hair strand cut short above a wider shoulder line), which is why the\n // bbox-edge test alone misses it, and it only becomes visible once the head\n // turns and uncovers the cut.\n let flatCutRun = 0;\n let flatCutY = -1;\n for (let y = minY + 1; y <= maxY; y++) {\n let run = 0;\n for (let x = minX; x <= maxX; x++) {\n if (\n alpha(x, y - 1) < FLAT_CUT_ALPHA_ABOVE &&\n alpha(x, y) > FLAT_CUT_ALPHA_BELOW\n ) {\n run++;\n if (run > flatCutRun) {\n flatCutRun = run;\n flatCutY = y;\n }\n } else {\n run = 0;\n }\n }\n }\n\n return {\n w: maxX - minX + 1,\n h: maxY - minY + 1,\n flatCutRun,\n flatCutY,\n bboxCx: (minX + maxX) / 2,\n bboxCy: (minY + maxY) / 2,\n massCx: sumX / n,\n massCy: sumY / n,\n marginTop: minY,\n marginBottom: H - 1 - maxY,\n marginLeft: minX,\n marginRight: W - 1 - maxX,\n edgeTop: edge(top),\n edgeBottom: edge(bottom),\n edgeLeft: edge(left),\n edgeRight: edge(right),\n canvasW: W,\n canvasH: H,\n };\n}\n\nconst pct = (v: number) => `${(v * 100).toFixed(0)}%`;\n\n/**\n * Measure every `*.png` in an already-resolved layers directory (`preview.png`\n * is the composer's contact sheet, not a role) and run the geometry checks.\n */\nexport async function measureDir(absDir: string): Promise<MeasureReport> {\n const files = fs\n .readdirSync(absDir)\n .filter((f) => f.endsWith(\".png\") && f !== \"preview.png\")\n .sort();\n if (files.length === 0) {\n throw new AutoRigInputError(`no role layers in ${absDir}`);\n }\n // Same agent-supplied-input surface autoRigFromLayers bounds: a `layersDir`\n // pointed at an asset folder would decode every PNG in it before reporting.\n if (files.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers in ${absDir}: ${files.length} > ${MAX_LAYERS}`,\n );\n }\n\n const layers: Record<string, LayerStats> = {};\n const empty: string[] = [];\n for (const f of files) {\n const role = path.basename(f, \".png\");\n const m = await layerStats(path.join(absDir, f));\n if (!m) {\n empty.push(role);\n continue;\n }\n layers[role] = m;\n }\n\n const warnings: string[] = [];\n\n // 1. Art running to its own edge → a straight seam appears on head turn.\n // Two very different faults look identical in the flattened layer, and the\n // remedies cost differently, so tell them apart before prescribing one: a\n // part the CANVAS clipped has no margin left on that side (retune, free),\n // while a part placed with room whose own drawing runs to its frame does\n // (regenerate, billed). A real run lost a regeneration to this: the source\n // kept 44 px of margin and the default layout pushed it 70 px off-canvas,\n // so redrawing it reproduced the clip exactly.\n for (const [role, m] of Object.entries(layers)) {\n const edges: [string, number, number, number][] = [\n [\"top\", m.edgeTop, m.w, m.marginTop],\n [\"left\", m.edgeLeft, m.h, m.marginLeft],\n [\"right\", m.edgeRight, m.h, m.marginRight],\n ];\n // A torso is meant to run off the bottom of the canvas.\n if (role !== \"body\")\n edges.push([\"bottom\", m.edgeBottom, m.w, m.marginBottom]);\n for (const [side, v, span, margin] of edges) {\n if (v > EDGE_SOLID_MAX && v * span >= EDGE_RUN_MIN_PX) {\n const remedy =\n margin === 0\n ? // margin 0 is consistent with a clipped placement AND with art\n // already cropped flush that happens to sit on the boundary, and\n // the flattened layer cannot separate them — so name the free\n // move rather than the cause. If moving it inward leaves the\n // edge opaque, the drawing is the one at fault.\n `it sits flush against the canvas ${side}, which a clipped placement and already-cropped ` +\n `art both produce. Move it inward first — retune layout.${role}.cx/cy/w, free — and ` +\n `remeasure; regenerate only if the edge is still opaque with margin to spare.`\n : `its own drawing runs to the frame ${margin} px inside the canvas — regenerate that part ` +\n `with empty margin on that side. Billed.`;\n warnings.push(\n `${role}: ${pct(v)} of its ${side} edge is opaque — the art is cut off there, ` +\n `which shows as a straight seam once the head turns. Cause: ${remedy}`,\n );\n }\n }\n }\n\n // 1b. A straight cut through the drawing, wherever it falls in the bbox.\n for (const [role, m] of Object.entries(layers)) {\n // `body` moves only as a rigid whole (a light share of the head's turn\n // and breath), so no pose can uncover a cut in it; its top is deliberately\n // cut flat where the jaw covers it.\n if (role === \"body\") continue;\n if (\n m.flatCutRun > FLAT_CUT_MAX_FRAC * m.w &&\n m.flatCutRun >= FLAT_CUT_MIN_PX\n ) {\n warnings.push(\n `${role}: ${m.flatCutRun}px of straight flat edge at y=${m.flatCutY} ` +\n `(${pct(m.flatCutRun / m.w)} of its width) — the source art is cut through there. ` +\n `It hides while the head faces front and opens into a seam on turn. ` +\n `Regenerate this part with the whole subject inside the frame.`,\n );\n }\n }\n\n // 2/3/4. Eye stack geometry, per side.\n for (const side of [\"L\", \"R\"]) {\n const eye: LayerStats | undefined = layers[`eye_${side}`];\n const iris: LayerStats | undefined = layers[`iris_${side}`];\n const lash: LayerStats | undefined = layers[`lash_${side}`];\n if (!eye) continue;\n\n const aspect = eye.h / eye.w;\n if (aspect < EYE_ASPECT_MIN) {\n warnings.push(\n `eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} — ` +\n `a round iris cannot sit inside it. Free fix first: set layout.eye_${side}.h and ` +\n `layout.lash_${side}.h to ${Math.ceil(eye.w * EYE_ASPECT_MIN)} (both, or the fold tears) — ` +\n `stretching a flat white lens is invisible. Regenerate the eyewhite taller only if that ` +\n `distorts the lash.`,\n );\n }\n\n if (iris) {\n const ratio = iris.w / eye.w;\n if (ratio < IRIS_RATIO_MIN || ratio > IRIS_RATIO_MAX) {\n warnings.push(\n `iris_${side}: width is ${pct(ratio)} of the sclera (target ${IRIS_RATIO_MIN}-${IRIS_RATIO_MAX}) — ` +\n `retune layout.iris_${side}.w (keep it a fraction of the eye width), no regeneration needed.`,\n );\n }\n const dx = iris.bboxCx - eye.massCx;\n const dy = iris.bboxCy - eye.massCy;\n if (\n Math.abs(dx) > IRIS_OFFSET_MAX_X ||\n Math.abs(dy) > IRIS_OFFSET_MAX_Y\n ) {\n warnings.push(\n `iris_${side}: sits (${dx.toFixed(1)}, ${dy.toFixed(1)}) px from the white's centre of mass — ` +\n `retune layout.iris_${side}.cx/cy. The sclera's bbox centre is NOT its visual centre when the ` +\n `lash flick stretches the box.`,\n );\n }\n }\n\n // 5. The lash and the white are split from ONE source and pasted with the\n // same cx/cy/w, so their frames coincide even though the lash only inks the\n // upper part of it (its content sits higher — that is the fold working, not\n // a fault). What must line up is the horizontal centre and the top edge; a\n // drift there means the two layout entries fell out of sync and the fold\n // will tear.\n if (lash) {\n const dx = lash.bboxCx - eye.bboxCx;\n const dTop = lash.marginTop - eye.marginTop;\n // dx compares INK centres, and the lash's ink is narrower than the frame it\n // shares with the sclera, so a lash whose flick runs one way sits a pixel or\n // two off-centre while its layout entry is perfectly in sync — a real run\n // measured 1.5 px on a 128 px eye and the warning could not be acted on.\n // Scale the tolerance with the eye so the desync this guards (14 px on a\n // real character) still trips it. dTop stays strict: the fold seam rides\n // that edge, and both layers ink the same top row when they are in sync.\n if (Math.abs(dx) > eye.w * LASH_CENTRE_TOL_FRAC || Math.abs(dTop) > 0.5) {\n warnings.push(\n `lash_${side}: centre is ${dx.toFixed(1)} px and top edge ${dTop.toFixed(1)} px off eye_${side}. ` +\n `They are split from one source and MUST share cx/cy/w in layout, or the blink fold tears. Retune to match.`,\n );\n }\n }\n }\n\n // 6. Optional roles that change how finished the character reads.\n for (const [role, why] of [\n [\"body\", \"without it the character reads as a floating head on head-turn\"],\n [\"hair_back\", \"without it the silhouette is flat behind the face\"],\n ]) {\n if (layers[role] === undefined) warnings.push(`${role}: missing — ${why}.`);\n }\n\n return { layers, empty, warnings };\n}\n\n/**\n * Measure a caller-supplied layers directory.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function measureLayers(\n input: MeasureInput,\n): Promise<MeasureResult> {\n try {\n const layersDir = resolveInputDir(input.layersDir);\n const report = await measureDir(layersDir);\n return {\n ok: true,\n layersDir,\n ...report,\n passed: report.warnings.length === 0,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n\n/**\n * Render a measurement as plain text: the per-layer table first (numbers to\n * argue with), then the checks that fired. Takes the report itself rather than\n * a MeasureResult so a caller holding one inline (no `ok` to unwrap) can print\n * it too; a failed measurement has no report to render.\n */\nexport function formatMeasureReport(\n result: MeasureReport & { layersDir: string },\n): string {\n const lines = [\n `# layers (${result.layersDir})`,\n \"\",\n \"role size bbox-centre mass-centre margins t/b/l/r\",\n ];\n // Roles come off a sorted file listing, so sorting the two groups back\n // together restores that order.\n for (const role of [...Object.keys(result.layers), ...result.empty].sort()) {\n const m = result.layers[role];\n if (m === undefined) {\n lines.push(`${role.padEnd(13)} EMPTY (fully transparent)`);\n continue;\n }\n lines.push(\n `${role.padEnd(13)} ${`${m.w}x${m.h}`.padEnd(11)} ` +\n `${`${m.bboxCx.toFixed(0)},${m.bboxCy.toFixed(0)}`.padEnd(14)} ` +\n `${`${m.massCx.toFixed(0)},${m.massCy.toFixed(0)}`.padEnd(13)} ` +\n `${m.marginTop}/${m.marginBottom}/${m.marginLeft}/${m.marginRight}`,\n );\n }\n\n lines.push(\"\", \"# checks\", \"\");\n if (result.warnings.length === 0) {\n lines.push(\"all geometry checks passed\");\n } else {\n for (const w of result.warnings) lines.push(`- ${w}`);\n }\n return lines.join(\"\\n\");\n}\n","/**\n * Compose AI-generated part PNGs into canvas-aligned, role-named layers for the\n * Iki auto-rig (`auto_rig_from_layers` / `@ikijs/editor` generateIkiFromLayerSet).\n * Each part is alpha-trimmed, resized to a target width, optionally mirrored,\n * and pasted at a chosen center on a shared transparent CANVAS x CANVAS canvas.\n *\n * Ports the composer that shipped as a script in the Claude Code plugin, so a\n * plugin user gets it from the MCP server instead of an ad-hoc `sharp` install.\n * Composing is deterministic: same parts -> same layers, so re-run freely after\n * tuning `layout` (no image re-generation needed).\n *\n * `sharp` must stay confined to @ikijs/mcp; part decoding goes through\n * ./node-images, this package's single image-decode boundary.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport sharp from \"sharp\";\nimport { cropToBuffer, decodePng } from \"./node-images\";\nimport { measureDir, type MeasureReport } from \"./measure\";\nimport {\n AutoRigInputError,\n resolveInputDir,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n/**\n * Side of the square layer canvas, in px. NOT an input: the layout defaults\n * below place parts against this size (hair_front alone is 660px wide, and\n * sharp rejects a composite input larger than its destination), so a different\n * canvas would need its own layout. The tuning surface is `layout` overrides.\n */\nexport const CANVAS = 1100;\n\n// Iris width as a fraction of the sclera width. Anime irises fill most of the\n// eye opening and are clipped by the lids — the auto-rig clips iris->sclera at\n// runtime, so a large iris cannot spill. The first sample's 32% iris read as a\n// bead floating in white, so the defaults below use 56.25% (72px in a 128px\n// opening) to reduce excess white below the iris. A caller retunes eye size\n// through `layout.eye_L/eye_R.w` and MUST move `layout.iris_L/iris_R.w` with it\n// to keep that ratio.\nconst EYE_W = 128;\nconst IRIS_W = Math.round(EYE_W * 0.5625);\n\n/** The eyewhite source that prepEyeSplit() splits into sclera + lash. */\nconst EYEWHITE_SRC = \"eyewhite.png\";\n/** Luminance below this (0..255) = a dark lash/outline pixel in the eyewhite. */\nconst EYE_LASH_LUMA = 120;\n// Of the eye's dark pixels, keep only those in the TOP this-fraction as the lash\n// (drops the lower almond rim/outline) so the lash reads as an upper arc that\n// folds DOWN over the eye on blink, instead of a full ring that shrinks in place.\nconst LASH_KEEP_FRACTION = 0.5;\n\ninterface RoleLayout {\n /** Part file name in the parts dir (the eye pair's two are split in memory). */\n src: string;\n /** Center in canvas px, origin top-left, y down. */\n cx: number;\n cy: number;\n /** Target width in px. */\n w: number;\n /**\n * Target height in px. Omitted, the height follows the part's own aspect\n * ratio — which is the right default for every role whose drawing already has\n * the proportions it should. It exists for the one that does not: an eyewhite\n * comes back flatter than the reference often enough that three generations\n * asking for \"taller\" landed at 0.47, while stretching a flat white lens ~15%\n * is invisible and free. Set it on the sclera and its lash together or the\n * fold tears — they share one frame.\n */\n h?: number;\n optional?: boolean;\n mirror?: boolean;\n noTrim?: boolean;\n}\n\n// ── DEFAULT LAYOUT (tune per character through `layout`) ──────────────────────\n// These defaults assume the standard framing the character skill prompts for\n// (a front-facing face centered on the canvas). If the rendered model is\n// misaligned, tune cx/cy/w through the `layout` override and re-run — composing\n// is cheap and the parts do not need regenerating.\n//\n// eyeSide reminder: eye_L = character's LEFT eye = screen RIGHT (larger cx).\n// eye_* = clean WHITE sclera (lashes recolored white) = the blink clip mask + fold.\n// iris_* = colored disc on top, clipped to the sclera, drives gaze.\n// lash_* = the dark lashes, a separate layer ABOVE the iris that folds down to\n// cover the closed-eye seam. eye_* and lash_* are split from a single\n// `eyewhite.png` (white almond + dark lashes) by prepEyeSplit().\nconst DEFAULT_LAYOUT = {\n // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir\n // without them still composes (head-only character).\n hair_back: { src: \"hair_back.png\", cx: 550, cy: 523, w: 800, optional: true },\n // The torso, cut off by the canvas bottom. It rides its own `bodyDeformer`: a\n // light share of the head turn and half its breath bob, so the character is\n // not a floating head.\n body: { src: \"body.png\", cx: 550, cy: 1017, w: 840, optional: true },\n face: { src: \"face.png\", cx: 550, cy: 475, w: 400 },\n mouth: { src: \"mouth.png\", cx: 550, cy: 619, w: 68 },\n // Cross-fades with `mouth` on ParamMouthOpenY (opacity, not scaleY) once the\n // auto-rig sees both roles. Same cx/w as `mouth` so the lip width matches;\n // its top edge (not center) lines up with the closed mouth's top edge since\n // the mouth opens downward from a fixed upper lip — hence the +2 cy nudge\n // rather than sharing cy outright. Optional: composes fine without it.\n mouth_open: {\n src: \"mouth_open.png\",\n cx: 550,\n cy: 621,\n w: 68,\n optional: true,\n },\n // eye_* (sclera) and lash_* share the eyewhite's cropped frame via noTrim (so\n // they are NOT re-bboxed independently): the upper lash stays anchored ABOVE\n // the sclera center, so on blink it folds DOWN over the eye like the sample\n // model instead of the whole eye shrinking in place. Same cx/cy/w.\n eye_L: { src: \"eyewhite_sclera.png\", cx: 657, cy: 475, w: EYE_W, mirror: true, noTrim: true }, // prettier-ignore\n eye_R: { src: \"eyewhite_sclera.png\", cx: 443, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n iris_L: { src: \"iris.png\", cx: 653, cy: 475, w: IRIS_W, mirror: false },\n iris_R: { src: \"iris.png\", cx: 447, cy: 475, w: IRIS_W, mirror: false },\n lash_L: {\n src: \"eyewhite_lash.png\",\n cx: 657,\n cy: 475,\n w: EYE_W,\n mirror: true,\n noTrim: true,\n },\n lash_R: { src: \"eyewhite_lash.png\", cx: 443, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n brow_L: { src: \"brow.png\", cx: 645, cy: 405, w: 135, mirror: false },\n brow_R: { src: \"brow.png\", cx: 455, cy: 405, w: 135, mirror: true },\n hair_front: { src: \"hair_front.png\", cx: 550, cy: 425, w: 660 },\n} satisfies Record<string, RoleLayout>;\n\nexport type Role = keyof typeof DEFAULT_LAYOUT;\n\n/** Draw order (back -> front), mirrors @ikijs/editor ROLE_TABLE order. */\nconst ORDER: Role[] = [\n \"hair_back\",\n \"body\",\n \"face\",\n \"mouth\",\n \"mouth_open\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"lash_L\",\n \"lash_R\",\n \"brow_L\",\n \"brow_R\",\n \"hair_front\",\n];\n\n/** Per-role placement overrides; anything omitted keeps the default above. */\nexport type LayoutOverride = Partial<\n Record<Role, { cx?: number; cy?: number; w?: number; h?: number }>\n>;\n\nexport interface ComposeInput {\n /** Directory of the generated part PNGs (relative paths resolve against cwd). */\n partsDir: string;\n /**\n * Existing directory under cwd to write the role layers into. Callers reuse\n * one across runs (it must pre-exist), so the compose leaves it holding\n * exactly the roles it reports: a skipped role's layer from an earlier run is\n * removed rather than left for the next tool to pick up.\n */\n outDir: string;\n layout?: LayoutOverride;\n}\n\nexport interface ComposedLayer {\n role: Role;\n path: string;\n /** Size of the placed part itself (the file is always CANVAS x CANVAS). */\n width: number;\n height: number;\n left: number;\n top: number;\n}\n\nexport type ComposeResult =\n | {\n ok: true;\n outDir: string;\n layers: ComposedLayer[];\n /** Roles whose optional part was absent from the parts dir. */\n skipped: Role[];\n preview: string;\n measure: MeasureReport;\n }\n | { ok: false; error: string };\n\n/**\n * Merge caller overrides onto the defaults. Input boundary: an unknown role, a\n * non-finite centre or an out-of-range width fails fast, path-qualified, before\n * any decode. `w` is capped at CANVAS so a resized part can never exceed the\n * canvas width; `cx`/`cy` are unbounded here because a part may legitimately\n * hang off an edge — placement() rejects the one that lands nowhere on it.\n */\nfunction resolveLayout(\n overrides: LayoutOverride | undefined,\n): Record<Role, RoleLayout> {\n const resolved: Record<Role, RoleLayout> = { ...DEFAULT_LAYOUT };\n if (overrides === undefined) return resolved;\n for (const [role, override] of Object.entries(overrides)) {\n if (!Object.prototype.hasOwnProperty.call(DEFAULT_LAYOUT, role)) {\n throw new AutoRigInputError(\n `layout.${role}: unknown role — expected one of ${Object.keys(DEFAULT_LAYOUT).join(\", \")}`,\n );\n }\n if (override === undefined) continue;\n const next = { ...resolved[role as Role] };\n for (const field of [\"cx\", \"cy\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n if (!Number.isFinite(value)) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be a finite number, got ${String(value)}`,\n );\n }\n next[field] = value;\n }\n for (const field of [\"w\", \"h\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n if (!Number.isInteger(value) || value < 1 || value > CANVAS) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be an integer in 1..${CANVAS}, got ${String(value)}`,\n );\n }\n next[field] = value;\n }\n resolved[role as Role] = next;\n }\n return resolved;\n}\n\n/**\n * Some generated parts come back opaque on a white background (no alpha).\n * Key near-white pixels to transparent so they can layer cleanly.\n */\nfunction keyWhiteToAlpha(rgba: Buffer): Buffer {\n const keyed = Buffer.from(rgba);\n for (let i = 0; i < keyed.length; i += 4) {\n if (keyed[i] > 238 && keyed[i + 1] > 238 && keyed[i + 2] > 238) {\n keyed[i + 3] = 0;\n }\n }\n return keyed;\n}\n\n/**\n * Trim/mirror a part and resize it to its layout width. `inMemory` carries the\n * eye pair's two split buffers; every other role is read from the parts dir.\n * Missing optional part -> null; missing required part -> AutoRigInputError.\n */\nasync function partBuffer(\n role: Role,\n cfg: RoleLayout,\n partsDir: string,\n inMemory: Buffer | undefined,\n): Promise<{ buf: Buffer; w: number; h: number } | null> {\n let img: sharp.Sharp;\n if (inMemory !== undefined) {\n img = sharp(inMemory);\n } else {\n const srcPath = path.join(partsDir, cfg.src);\n if (!fs.existsSync(srcPath)) {\n // Optional roles (hair_back, body, mouth_open) are absent from a\n // head-only parts dir; the auto-rig only requires face/eye_L/eye_R/mouth.\n if (cfg.optional) return null;\n // Name the role, not just the file: one source feeds two roles\n // (brow.png -> brow_L/brow_R), so the path alone does not say what broke.\n throw new AutoRigInputError(\n `missing part source for role \"${role}\": ${srcPath}`,\n );\n }\n const png = await decodePng(srcPath);\n // decodePng is the package's decode boundary: it caps the source at\n // MAX_INPUT_PIXELS and reports a bad/corrupt file as a path-qualified\n // AutoRigInputError, so the raw re-wrap below is already bounded.\n img = sharp(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {\n raw: { width: png.width, height: png.height, channels: 4 },\n });\n }\n // noTrim parts (the eye and lash pairs) keep their shared pre-cropped frame so\n // sclera and lash stay aligned; everything else is alpha-trimmed to its own bbox.\n if (!cfg.noTrim) img = img.trim({ threshold: 12 });\n if (cfg.mirror) img = img.flop();\n // Materialise the trimmed part BEFORE resizing: its size is bounded by the\n // source decode limit, so the height the resize WOULD produce can be checked\n // against the canvas while only the bounded buffer is allocated.\n const trimmed = await img.png().toBuffer({ resolveWithObject: true });\n // An explicit h is already bounded by resolveLayout; only the aspect-derived\n // height can run past the canvas.\n if (cfg.h === undefined) {\n const scaledH = Math.round(\n (trimmed.info.height * cfg.w) / trimmed.info.width,\n );\n if (scaledH > CANVAS) {\n throw new AutoRigInputError(\n `layout.${role}.w: resized part ${cfg.w}x${scaledH} exceeds the ${CANVAS} canvas`,\n );\n }\n }\n const resized = await sharp(trimmed.data)\n // Width alone keeps the source aspect. With h, fit:\"fill\" is the point —\n // stretch to the given box instead. Both options stay off the width-only\n // path: passing height:undefined alongside fit:\"fill\" makes sharp drop the\n // aspect it would otherwise preserve.\n .resize(\n cfg.h === undefined\n ? { width: cfg.w }\n : { width: cfg.w, height: cfg.h, fit: \"fill\" },\n )\n .png()\n .toBuffer({ resolveWithObject: true });\n return {\n buf: resized.data,\n w: resized.info.width,\n h: resized.info.height,\n };\n}\n\n/**\n * Where the part lands, centred on its layout cx/cy. Running off an edge is\n * legitimate — `body` is meant to be cut off by the canvas bottom — so the test\n * is INTERSECTION, not containment. A part that misses the canvas entirely\n * composes to a fully transparent layer that nothing downstream flags\n * (measureDir warns per measured layer, and an empty one has no geometry), so a\n * sign-flipped centre would otherwise read as success.\n */\nfunction placement(role: Role, cfg: RoleLayout, w: number, h: number) {\n const left = Math.round(cfg.cx - w / 2);\n const top = Math.round(cfg.cy - h / 2);\n if (left + w <= 0 || top + h <= 0 || left >= CANVAS || top >= CANVAS) {\n throw new AutoRigInputError(\n `layout.${role}.cx/cy: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${CANVAS} canvas`,\n );\n }\n return { left, top };\n}\n\nfunction blankCanvas() {\n return sharp({\n create: {\n width: CANVAS,\n height: CANVAS,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n });\n}\n\n/**\n * Split eyewhite.png (white almond + dark lashes) into a clean white sclera\n * (the dark outline/lash recolored to white = the blink clip-mask shape) and a\n * dark UPPER-lash-only layer. Both are cropped to the SAME eye bbox so they stay\n * aligned (consumed with noTrim): the lash arc keeps its position at the top of\n * the sclera, so on blink it folds DOWN over the eye rather than the eye shrinking\n * in place.\n *\n * Both come back as PNG buffers. The script this ports wrote them back into the\n * parts dir, but that dir is an INPUT here (reads are deliberately unconfined),\n * so the tool never writes there — only under the confined outDir.\n */\nasync function prepEyeSplit(\n partsDir: string,\n): Promise<{ sclera: Buffer; lash: Buffer }> {\n const srcPath = path.join(partsDir, EYEWHITE_SRC);\n if (!fs.existsSync(srcPath)) {\n throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);\n }\n const { width: W, height: H, rgba: data } = await decodePng(srcPath);\n\n // Eye content bbox (alpha) → the shared cropped frame for both outputs.\n let minX = W;\n let minY = H;\n let maxX = -1;\n let maxY = -1;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (data[(y * W + x) * 4 + 3] > 8) {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n }\n }\n if (maxX < 0) {\n throw new AutoRigInputError(`eyewhite is fully transparent: ${srcPath}`);\n }\n // Keep only the upper lash: dark pixels above this row become the lash layer.\n const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);\n\n const sclera = Buffer.from(data);\n const lash = Buffer.from(data);\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n const i = (y * W + x) * 4;\n const lum = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];\n const isDark = data[i + 3] > 0 && lum < EYE_LASH_LUMA;\n if (isDark) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255; // dark -> white\n if (!(isDark && y <= lashCutoffY)) lash[i + 3] = 0; // keep upper dark only\n }\n }\n const region = {\n x: minX,\n y: minY,\n w: maxX - minX + 1,\n h: maxY - minY + 1,\n };\n return {\n sclera: await cropToBuffer(sclera, W, H, region),\n lash: await cropToBuffer(lash, W, H, region),\n };\n}\n\n/**\n * Compose a parts directory into role-named layers plus a flattened preview,\n * then measure the result so the caller sees the geometry checks inline.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function composeLayersFromParts(\n input: ComposeInput,\n): Promise<ComposeResult> {\n try {\n // Resolve the output dir FIRST (fail-fast): reject a missing or escaping\n // target before spending the decode budget on a run that cannot be written.\n const outDir = resolveOutputDir(input.outDir);\n const partsDir = resolveInputDir(input.partsDir);\n // resolveOutputDir already realpath's outDir; resolveInputDir does not (its\n // reads are deliberately unconfined), so realpath partsDir here too before\n // comparing — otherwise a symlink alias of the same directory would slip\n // past a lexical check. Composing a parts dir into itself would overwrite\n // originals like face.png/hair_front.png with resized, cropped layers, and\n // skipped-role cleanup would delete sources with no surviving part.\n if (fs.realpathSync(partsDir) === outDir) {\n throw new AutoRigInputError(\n `partsDir and outDir resolve to the same directory (${outDir}): composing would overwrite the source parts`,\n );\n }\n const layout = resolveLayout(input.layout);\n\n const split = await prepEyeSplit(partsDir);\n const splitSources = new Map<string, Buffer>([\n [\"eyewhite_sclera.png\", split.sclera],\n [\"eyewhite_lash.png\", split.lash],\n ]);\n\n const layers: ComposedLayer[] = [];\n const skipped: Role[] = [];\n const preview: { input: Buffer; left: number; top: number }[] = [];\n for (const role of ORDER) {\n const cfg = layout[role];\n const part = await partBuffer(\n role,\n cfg,\n partsDir,\n splitSources.get(cfg.src),\n );\n if (part === null) {\n skipped.push(role);\n // Drop this role's layer from an earlier compose into the same dir:\n // left behind it would contradict `skipped`, since measureDir globs the\n // directory (the report would still show a body) and the next\n // auto_rig_from_layers would rig the stale file into the model. Only the\n // fixed ORDER role names, under the confined outDir, are ever removed.\n fs.rmSync(path.join(outDir, `${role}.png`), { force: true });\n continue;\n }\n const { left, top } = placement(role, cfg, part.w, part.h);\n // role layer: this part alone on a full canvas at its position.\n const layer = await blankCanvas()\n .composite([{ input: part.buf, left, top }])\n .png()\n .toBuffer();\n const outPath = path.join(outDir, `${role}.png`);\n writeFileAtomic(outPath, layer);\n layers.push({\n role,\n path: outPath,\n width: part.w,\n height: part.h,\n left,\n top,\n });\n preview.push({ input: part.buf, left, top });\n }\n\n // Flattened preview over a light bg so transparency reads clearly.\n const previewPng = await sharp({\n create: {\n width: CANVAS,\n height: CANVAS,\n channels: 4,\n background: { r: 245, g: 245, b: 248, alpha: 1 },\n },\n })\n .composite(preview)\n .png()\n .toBuffer();\n const previewPath = path.join(outDir, \"preview.png\");\n writeFileAtomic(previewPath, previewPng);\n\n return {\n ok: true,\n outDir,\n layers,\n skipped,\n preview: previewPath,\n measure: await measureDir(outDir),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n validateIki,\n describeIki,\n listStandardParameters,\n autoRigFromLayers,\n} from \"./tools\";\nimport { composeLayersFromParts } from \"./compose\";\nimport { measureLayers, formatMeasureReport } from \"./measure\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers; returns an error for an invalid model.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"Auto-rigs role-named PNG layers (face, eye_L/eye_R, mouth required; iris_L/R, brow_L/R, hair_front, etc. optional) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n quantizeColors: z\n .number()\n .int()\n .min(2)\n .max(256)\n .optional()\n .describe(\n \"Palette-quantize the atlas PNG to this many colours (2..256). Flat-shaded art keeps its look at 256 and the model shrinks to about a quarter; omit for lossless.\",\n ),\n },\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 are optional.\",\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, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front — e.g. `{ eye_L: { cx: 660 } }`. `w` and `h` are integers in 1..1100; omit `h` to keep the part's own aspect, set it to stretch (set it on a sclera and its lash together, or the blink fold tears).\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await composeLayersFromParts(args);\n const text = r.ok\n ? [\n ...r.layers.map((l) => l.path),\n formatMeasureReport({ ...r.measure, layersDir: r.outDir }),\n ].join(\"\\n\")\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"measure_layers\",\n {\n description:\n \"Reports read-only geometry checks over an already-composed layers directory — the same checks compose_layers_from_parts returns inline (iris ratio/offset, eye aspect, cropped/cut edges, missing optional roles). Use to re-check a layers dir without recomposing.\",\n inputSchema: {\n layersDir: z\n .string()\n .describe(\n \"Directory of role-named layer PNGs (resolved against cwd).\",\n ),\n },\n },\n async ({ layersDir }) => {\n try {\n const r = await measureLayers({ layersDir });\n const text = r.ok ? formatMeasureReport(r) : `INVALID: ${r.error}`;\n // Spread into a fresh object: MeasureResult's ok:true arm is an\n // intersection with the MeasureReport interface, which TS won't accept\n // directly against the SDK's `Record<string, unknown>` structuredContent\n // — spreading drops that nominal interface identity, same value.\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { ...r },\n };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n return server;\n}\n"],"mappings":";AAAA,OAAOA,WAAU;AACjB;AAAA,EACE;AAAA,EACA;AAA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;AAC3C,cAAM,OAAO,EAAE,KAAK,oBAAoB,CAAC,IAAI,YAAY,EAAE,KAAK;AAKhE,eAAO;AAAA,UACL,SAAS,CAAC,EAAE,MAAM,QAAQ,KAAK,CAAC;AAAA,UAChC,mBAAmB,EAAE,GAAG,EAAE;AAAA,QAC5B;AAAA,MACF,SAAS,KAAK;AACZ,cAAM,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC7D,eAAO;AAAA,UACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,qBAAqB,KAAK,GAAG,CAAC;AAAA,UAC9D,mBAAmB,EAAE,IAAI,OAAO,MAAM;AAAA,UACtC,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["path","placement","path","placement","fs","path","fs","path","fs","path","sharp","sharp","path","fs"]}
|
package/dist/cli.js
CHANGED
|
@@ -521,6 +521,7 @@ var EYE_ASPECT_MIN = 0.5;
|
|
|
521
521
|
var IRIS_OFFSET_MAX_X = 3;
|
|
522
522
|
var IRIS_OFFSET_MAX_Y = 10;
|
|
523
523
|
var EDGE_SOLID_MAX = 0.5;
|
|
524
|
+
var LASH_CENTRE_TOL_FRAC = 0.03;
|
|
524
525
|
var EDGE_RUN_MIN_PX = 40;
|
|
525
526
|
var FLAT_CUT_MAX_FRAC = 0.1;
|
|
526
527
|
var FLAT_CUT_MIN_PX = 40;
|
|
@@ -625,15 +626,24 @@ async function measureDir(absDir) {
|
|
|
625
626
|
const warnings = [];
|
|
626
627
|
for (const [role, m] of Object.entries(layers)) {
|
|
627
628
|
const edges = [
|
|
628
|
-
["top", m.edgeTop, m.w],
|
|
629
|
-
["left", m.edgeLeft, m.h],
|
|
630
|
-
["right", m.edgeRight, m.h]
|
|
629
|
+
["top", m.edgeTop, m.w, m.marginTop],
|
|
630
|
+
["left", m.edgeLeft, m.h, m.marginLeft],
|
|
631
|
+
["right", m.edgeRight, m.h, m.marginRight]
|
|
631
632
|
];
|
|
632
|
-
if (role !== "body")
|
|
633
|
-
|
|
633
|
+
if (role !== "body")
|
|
634
|
+
edges.push(["bottom", m.edgeBottom, m.w, m.marginBottom]);
|
|
635
|
+
for (const [side, v, span, margin] of edges) {
|
|
634
636
|
if (v > EDGE_SOLID_MAX && v * span >= EDGE_RUN_MIN_PX) {
|
|
637
|
+
const remedy = margin === 0 ? (
|
|
638
|
+
// margin 0 is consistent with a clipped placement AND with art
|
|
639
|
+
// already cropped flush that happens to sit on the boundary, and
|
|
640
|
+
// the flattened layer cannot separate them — so name the free
|
|
641
|
+
// move rather than the cause. If moving it inward leaves the
|
|
642
|
+
// edge opaque, the drawing is the one at fault.
|
|
643
|
+
`it sits flush against the canvas ${side}, which a clipped placement and already-cropped art both produce. Move it inward first \u2014 retune layout.${role}.cx/cy/w, free \u2014 and remeasure; regenerate only if the edge is still opaque with margin to spare.`
|
|
644
|
+
) : `its own drawing runs to the frame ${margin} px inside the canvas \u2014 regenerate that part with empty margin on that side. Billed.`;
|
|
635
645
|
warnings.push(
|
|
636
|
-
`${role}: ${pct(v)} of its ${side} edge is opaque \u2014 the art is cut off there, which shows as a straight seam once the head turns.
|
|
646
|
+
`${role}: ${pct(v)} of its ${side} edge is opaque \u2014 the art is cut off there, which shows as a straight seam once the head turns. Cause: ${remedy}`
|
|
637
647
|
);
|
|
638
648
|
}
|
|
639
649
|
}
|
|
@@ -654,7 +664,7 @@ async function measureDir(absDir) {
|
|
|
654
664
|
const aspect = eye.h / eye.w;
|
|
655
665
|
if (aspect < EYE_ASPECT_MIN) {
|
|
656
666
|
warnings.push(
|
|
657
|
-
`eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} \u2014 a round iris cannot sit inside it. Regenerate the eyewhite taller
|
|
667
|
+
`eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} \u2014 a round iris cannot sit inside it. Free fix first: set layout.eye_${side}.h and layout.lash_${side}.h to ${Math.ceil(eye.w * EYE_ASPECT_MIN)} (both, or the fold tears) \u2014 stretching a flat white lens is invisible. Regenerate the eyewhite taller only if that distorts the lash.`
|
|
658
668
|
);
|
|
659
669
|
}
|
|
660
670
|
if (iris) {
|
|
@@ -675,7 +685,7 @@ async function measureDir(absDir) {
|
|
|
675
685
|
if (lash) {
|
|
676
686
|
const dx = lash.bboxCx - eye.bboxCx;
|
|
677
687
|
const dTop = lash.marginTop - eye.marginTop;
|
|
678
|
-
if (Math.abs(dx) >
|
|
688
|
+
if (Math.abs(dx) > eye.w * LASH_CENTRE_TOL_FRAC || Math.abs(dTop) > 0.5) {
|
|
679
689
|
warnings.push(
|
|
680
690
|
`lash_${side}: centre is ${dx.toFixed(1)} px and top edge ${dTop.toFixed(1)} px off eye_${side}. They are split from one source and MUST share cx/cy/w in layout, or the blink fold tears. Retune to match.`
|
|
681
691
|
);
|
|
@@ -821,13 +831,15 @@ function resolveLayout(overrides) {
|
|
|
821
831
|
}
|
|
822
832
|
next[field] = value;
|
|
823
833
|
}
|
|
824
|
-
|
|
825
|
-
|
|
834
|
+
for (const field of ["w", "h"]) {
|
|
835
|
+
const value = override[field];
|
|
836
|
+
if (value === void 0) continue;
|
|
837
|
+
if (!Number.isInteger(value) || value < 1 || value > CANVAS) {
|
|
826
838
|
throw new AutoRigInputError(
|
|
827
|
-
`layout.${role}
|
|
839
|
+
`layout.${role}.${field} must be an integer in 1..${CANVAS}, got ${String(value)}`
|
|
828
840
|
);
|
|
829
841
|
}
|
|
830
|
-
next
|
|
842
|
+
next[field] = value;
|
|
831
843
|
}
|
|
832
844
|
resolved[role] = next;
|
|
833
845
|
}
|
|
@@ -862,15 +874,19 @@ async function partBuffer(role, cfg, partsDir, inMemory) {
|
|
|
862
874
|
if (!cfg.noTrim) img = img.trim({ threshold: 12 });
|
|
863
875
|
if (cfg.mirror) img = img.flop();
|
|
864
876
|
const trimmed = await img.png().toBuffer({ resolveWithObject: true });
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
if (scaledH > CANVAS) {
|
|
869
|
-
throw new AutoRigInputError(
|
|
870
|
-
`layout.${role}.w: resized part ${cfg.w}x${scaledH} exceeds the ${CANVAS} canvas`
|
|
877
|
+
if (cfg.h === void 0) {
|
|
878
|
+
const scaledH = Math.round(
|
|
879
|
+
trimmed.info.height * cfg.w / trimmed.info.width
|
|
871
880
|
);
|
|
881
|
+
if (scaledH > CANVAS) {
|
|
882
|
+
throw new AutoRigInputError(
|
|
883
|
+
`layout.${role}.w: resized part ${cfg.w}x${scaledH} exceeds the ${CANVAS} canvas`
|
|
884
|
+
);
|
|
885
|
+
}
|
|
872
886
|
}
|
|
873
|
-
const resized = await (0, import_sharp2.default)(trimmed.data).resize(
|
|
887
|
+
const resized = await (0, import_sharp2.default)(trimmed.data).resize(
|
|
888
|
+
cfg.h === void 0 ? { width: cfg.w } : { width: cfg.w, height: cfg.h, fit: "fill" }
|
|
889
|
+
).png().toBuffer({ resolveWithObject: true });
|
|
874
890
|
return {
|
|
875
891
|
buf: resized.data,
|
|
876
892
|
w: resized.info.width,
|
|
@@ -1015,7 +1031,7 @@ async function composeLayersFromParts(input) {
|
|
|
1015
1031
|
|
|
1016
1032
|
// src/server.ts
|
|
1017
1033
|
function createIkiMcpServer() {
|
|
1018
|
-
const server = new import_mcp.McpServer({ name: "iki", version: "0.
|
|
1034
|
+
const server = new import_mcp.McpServer({ name: "iki", version: "0.5.0" });
|
|
1019
1035
|
server.registerTool(
|
|
1020
1036
|
"validate_iki",
|
|
1021
1037
|
{
|
|
@@ -1126,9 +1142,14 @@ function createIkiMcpServer() {
|
|
|
1126
1142
|
),
|
|
1127
1143
|
layout: import_zod.z.record(
|
|
1128
1144
|
import_zod.z.string(),
|
|
1129
|
-
import_zod.z.object({
|
|
1145
|
+
import_zod.z.object({
|
|
1146
|
+
cx: import_zod.z.number(),
|
|
1147
|
+
cy: import_zod.z.number(),
|
|
1148
|
+
w: import_zod.z.number(),
|
|
1149
|
+
h: import_zod.z.number()
|
|
1150
|
+
}).partial()
|
|
1130
1151
|
).optional().describe(
|
|
1131
|
-
"Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, face, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front \u2014 e.g. `{ eye_L: { cx: 660 } }
|
|
1152
|
+
"Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, face, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front \u2014 e.g. `{ eye_L: { cx: 660 } }`. `w` and `h` are integers in 1..1100; omit `h` to keep the part's own aspect, set it to stretch (set it on a sclera and its lash together, or the blink fold tears)."
|
|
1132
1153
|
)
|
|
1133
1154
|
}
|
|
1134
1155
|
},
|