@ikijs/mcp 0.33.0 → 0.34.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/dist/cli.js CHANGED
@@ -32,10 +32,10 @@ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
32
32
  var import_zod = require("zod");
33
33
 
34
34
  // src/tools.ts
35
- var import_node_fs5 = require("fs");
35
+ var import_node_fs6 = require("fs");
36
36
  var import_node_path5 = __toESM(require("path"));
37
- var import_format9 = require("@ikijs/format");
38
- var import_editor3 = require("@ikijs/editor");
37
+ var import_format11 = require("@ikijs/format");
38
+ var import_editor4 = require("@ikijs/editor");
39
39
 
40
40
  // ../engine/src/math.ts
41
41
  function clamp(value, min, max) {
@@ -1707,58 +1707,6 @@ function affectedParts(model, output) {
1707
1707
  );
1708
1708
  }
1709
1709
 
1710
- // src/fold-report.ts
1711
- var import_editor = require("@ikijs/editor");
1712
- function checkModelFolds(model, extraValues = []) {
1713
- const declared = new Set(model.parameters.map((p) => p.id));
1714
- return checkFolds(model, {
1715
- poses: [...foldPoses(model), ...extraValues.map(foldPose)],
1716
- // The effective value, not the pose's overrides: the auto-rig's mouth
1717
- // rests shut at its default, so `rest` and the other parameters' singles
1718
- // are shut-mouth poses too.
1719
- expected: (target2, _pose, value) => {
1720
- if (target2.kind !== "part") return false;
1721
- const shutBy = import_editor.SHUT_BY.get(target2.id);
1722
- return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
1723
- }
1724
- });
1725
- }
1726
- function formatFoldReport(report, canvas) {
1727
- const lines = report.offenders.length === 0 ? [`FOLDS: none over ${report.poses} poses`] : report.offenders.map((t) => offenderLine(t, t.worst, canvas));
1728
- const closures = report.targets.flatMap((t) => {
1729
- if (t.expected === void 0) return [];
1730
- if (t.expected.ratio >= report.thresholds.collapse) return [];
1731
- const shutBy = import_editor.SHUT_BY.get(t.target.id);
1732
- const at = shutBy === void 0 ? "" : ` at ${shutBy}=0`;
1733
- return [`${t.target.id} ${ratioText(t.expected.ratio)}${at}`];
1734
- });
1735
- if (closures.length > 0) {
1736
- lines.push(
1737
- `FOLDS expected: by-design closures, not findings \u2014 ${closures.join(", ")}`
1738
- );
1739
- }
1740
- return lines;
1741
- }
1742
- function foldPose(values) {
1743
- const ids = Object.keys(values).sort();
1744
- const name = ids.length === 0 ? "rest" : ids.map((id) => `${id}=${values[id]}`).join(" ");
1745
- return { name, values };
1746
- }
1747
- function offenderLine(t, hit, canvas) {
1748
- const where = "triangle" in hit.where ? `triangle ${hit.where.triangle}` : `cell (${hit.where.col},${hit.where.row})`;
1749
- const { x, y } = hit.rest;
1750
- return `FOLD ${t.kind} ${t.target.kind} ${t.target.id} ${where} ratio ${ratioText(hit.ratio)} pose [${hit.pose.name}] rest at (${x.toFixed(1)}, ${y.toFixed(1)}) model space, (${(canvas.width / 2 + x).toFixed(0)}, ${(canvas.height / 2 - y).toFixed(0)}) model px from the top-left`;
1751
- }
1752
- function ratioText(ratio) {
1753
- if (ratio === 0) return "0";
1754
- return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);
1755
- }
1756
-
1757
- // src/render-poses.ts
1758
- var import_node_fs4 = require("fs");
1759
- var import_node_path4 = __toESM(require("path"));
1760
- var import_format8 = require("@ikijs/format");
1761
-
1762
1710
  // src/limits.ts
1763
1711
  var import_node_fs = __toESM(require("fs"));
1764
1712
  var import_node_path = __toESM(require("path"));
@@ -1769,6 +1717,8 @@ var MAX_ATLAS_SIDE = 4096;
1769
1717
  var MAX_INPUT_PIXELS = 4096 * 4096;
1770
1718
  var MAX_TOTAL_PIXELS = 128 * 1024 * 1024;
1771
1719
  var MAX_OUTPUT_BYTES = 12 * 1024 * 1024;
1720
+ var MAX_PROBE_QUERIES = 64;
1721
+ var MAX_PROBE_POINTS = 5e3;
1772
1722
  var AutoRigInputError = class extends Error {
1773
1723
  constructor(message) {
1774
1724
  super(message);
@@ -1825,12 +1775,14 @@ function confineToWorkingDirectory(root, dir, label, original) {
1825
1775
  }
1826
1776
  return realDir;
1827
1777
  }
1828
- function resolveOutputPath(outputPath) {
1778
+ function resolveOutputPath(outputPath, extension = ".iki") {
1829
1779
  if (typeof outputPath !== "string" || outputPath.trim() === "") {
1830
1780
  throw new AutoRigInputError("output path is empty");
1831
1781
  }
1832
- if (!outputPath.toLowerCase().endsWith(".iki")) {
1833
- throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);
1782
+ if (!outputPath.toLowerCase().endsWith(extension)) {
1783
+ throw new AutoRigInputError(
1784
+ `output path must end in ${extension}: ${outputPath}`
1785
+ );
1834
1786
  }
1835
1787
  const root = process.cwd();
1836
1788
  const resolved = import_node_path.default.resolve(root, outputPath);
@@ -1880,18 +1832,989 @@ function writeFileAtomic(outPath, data) {
1880
1832
  import_node_fs.default.rmSync(tmp, { force: true });
1881
1833
  } catch {
1882
1834
  }
1883
- throw e;
1835
+ throw e;
1836
+ }
1837
+ } catch (e) {
1838
+ throw new AutoRigInputError(
1839
+ `write: ${e instanceof Error ? e.message : String(e)}`
1840
+ );
1841
+ }
1842
+ }
1843
+
1844
+ // src/bake-report.ts
1845
+ var BAKE_TOLERANCE_PX = 0.1;
1846
+ var BUG = "the rig and the engine disagree; report this as a bug in the packages";
1847
+ function checkBakes(model, reports) {
1848
+ const restOf = /* @__PURE__ */ new Map();
1849
+ for (const id of new Set(reports.map((r) => r.part))) {
1850
+ const rest = landParts(model, {}, [id]).get(id);
1851
+ const bare = landParts(
1852
+ {
1853
+ ...model,
1854
+ parts: model.parts.map(
1855
+ (p) => p.id === id ? { ...p, warps: void 0 } : p
1856
+ )
1857
+ },
1858
+ {},
1859
+ [id]
1860
+ ).get(id);
1861
+ let restGap = 0;
1862
+ for (let i = 0; i < rest.length; i++) {
1863
+ restGap = Math.max(restGap, Math.abs(rest[i] - bare[i]));
1864
+ }
1865
+ if (restGap >= BAKE_TOLERANCE_PX) {
1866
+ throw new AutoRigInputError(
1867
+ `BAKE ERROR ${id} at rest: the part moved ${restGap.toFixed(3)} px, where the bake must leave it (limit ${BAKE_TOLERANCE_PX} px); ${BUG}`
1868
+ );
1869
+ }
1870
+ restOf.set(id, rest);
1871
+ }
1872
+ return reports.map((r) => {
1873
+ const rest = restOf.get(r.part);
1874
+ let errorPx = 0;
1875
+ const asked = [
1876
+ ...r.stops.map((value, s) => ({ value, wanted: r.wanted[s] })),
1877
+ ...r.ends
1878
+ ];
1879
+ asked.forEach(({ value, wanted }) => {
1880
+ const posed = landParts(model, { [r.param]: value }, [r.part]).get(
1881
+ r.part
1882
+ );
1883
+ let worst = 0;
1884
+ let worstVertex = 0;
1885
+ for (let v = 0; v < r.vertexCount; v++) {
1886
+ const gap = Math.hypot(
1887
+ posed[v * 2] - rest[v * 2] - wanted[v * 2],
1888
+ -(posed[v * 2 + 1] - rest[v * 2 + 1]) - wanted[v * 2 + 1]
1889
+ );
1890
+ if (gap > worst) {
1891
+ worst = gap;
1892
+ worstVertex = v;
1893
+ }
1894
+ }
1895
+ if (worst >= BAKE_TOLERANCE_PX) {
1896
+ throw new AutoRigInputError(
1897
+ `BAKE ERROR ${r.part} ${r.param}=${value}: vertex ${worstVertex} lands ${worst.toFixed(3)} px from the displacement the bake asked for (limit ${BAKE_TOLERANCE_PX} px); ${BUG}`
1898
+ );
1899
+ }
1900
+ errorPx = Math.max(errorPx, worst);
1901
+ });
1902
+ return {
1903
+ part: r.part,
1904
+ param: r.param,
1905
+ vertices: r.vertexCount,
1906
+ stops: r.stops,
1907
+ errorPx
1908
+ };
1909
+ });
1910
+ }
1911
+
1912
+ // src/custom-gate.ts
1913
+ var import_editor3 = require("@ikijs/editor");
1914
+ var import_format9 = require("@ikijs/format");
1915
+
1916
+ // src/fold-report.ts
1917
+ var import_editor = require("@ikijs/editor");
1918
+ function checkModelFolds(model, extraValues = []) {
1919
+ const declared = new Set(model.parameters.map((p) => p.id));
1920
+ return checkFolds(model, {
1921
+ poses: [...foldPoses(model), ...extraValues.map(foldPose)],
1922
+ // The effective value, not the pose's overrides: the auto-rig's mouth
1923
+ // rests shut at its default, so `rest` and the other parameters' singles
1924
+ // are shut-mouth poses too.
1925
+ expected: (target2, _pose, value) => {
1926
+ if (target2.kind !== "part") return false;
1927
+ const shutBy = import_editor.SHUT_BY.get(target2.id);
1928
+ return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
1929
+ }
1930
+ });
1931
+ }
1932
+ function formatFoldReport(report, canvas) {
1933
+ const lines = report.offenders.length === 0 ? [`FOLDS: none over ${report.poses} poses`] : report.offenders.map((t) => offenderLine(t, t.worst, canvas));
1934
+ const closures = report.targets.flatMap((t) => {
1935
+ if (t.expected === void 0) return [];
1936
+ if (t.expected.ratio >= report.thresholds.collapse) return [];
1937
+ const shutBy = import_editor.SHUT_BY.get(t.target.id);
1938
+ const at = shutBy === void 0 ? "" : ` at ${shutBy}=0`;
1939
+ return [`${t.target.id} ${ratioText(t.expected.ratio)}${at}`];
1940
+ });
1941
+ if (closures.length > 0) {
1942
+ lines.push(
1943
+ `FOLDS expected: by-design closures, not findings \u2014 ${closures.join(", ")}`
1944
+ );
1945
+ }
1946
+ return lines;
1947
+ }
1948
+ function foldPose(values) {
1949
+ const ids = Object.keys(values).sort();
1950
+ const name = ids.length === 0 ? "rest" : ids.map((id) => `${id}=${values[id]}`).join(" ");
1951
+ return { name, values };
1952
+ }
1953
+ function offenderLine(t, hit, canvas) {
1954
+ const where = "triangle" in hit.where ? `triangle ${hit.where.triangle}` : `cell (${hit.where.col},${hit.where.row})`;
1955
+ const { x, y } = hit.rest;
1956
+ return `FOLD ${t.kind} ${t.target.kind} ${t.target.id} ${where} ratio ${ratioText(hit.ratio)} pose [${hit.pose.name}] rest at (${x.toFixed(1)}, ${y.toFixed(1)}) model space, (${(canvas.width / 2 + x).toFixed(0)}, ${(canvas.height / 2 - y).toFixed(0)}) model px from the top-left`;
1957
+ }
1958
+ function ratioText(ratio) {
1959
+ if (ratio === 0) return "0";
1960
+ return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);
1961
+ }
1962
+
1963
+ // src/probe.ts
1964
+ var import_node_fs2 = require("fs");
1965
+ var import_format8 = require("@ikijs/format");
1966
+
1967
+ // src/node-images.ts
1968
+ var import_sharp = __toESM(require("sharp"));
1969
+ var import_editor2 = require("@ikijs/editor");
1970
+ async function decodePng(filePath) {
1971
+ try {
1972
+ const pipeline = (0, import_sharp.default)(filePath, { limitInputPixels: MAX_INPUT_PIXELS });
1973
+ const metadata = await pipeline.metadata();
1974
+ if (metadata.format !== "png") {
1975
+ throw new AutoRigInputError(
1976
+ `non-PNG image (${metadata.format ?? "unknown"}): ${filePath}`
1977
+ );
1978
+ }
1979
+ const { data, info } = await pipeline.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1980
+ return {
1981
+ width: info.width,
1982
+ height: info.height,
1983
+ rgba: data,
1984
+ hasAlpha: metadata.hasAlpha ?? false
1985
+ };
1986
+ } catch (e) {
1987
+ if (e instanceof AutoRigInputError) throw e;
1988
+ const msg = e instanceof Error ? e.message : String(e);
1989
+ throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);
1990
+ }
1991
+ }
1992
+ function detectAlphaBbox(rgba, width, height) {
1993
+ const bbox = (0, import_editor2.detectAlphaBbox)(rgba, width, height);
1994
+ if (bbox === null) {
1995
+ throw new AutoRigInputError("layer is empty after alpha threshold");
1996
+ }
1997
+ return bbox;
1998
+ }
1999
+ function cropToBuffer(rgba, width, height, bbox) {
2000
+ return (0, import_sharp.default)(rgba, { raw: { width, height, channels: 4 } }).extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h }).png().toBuffer();
2001
+ }
2002
+ function encodeOverlayPng(filePath, svg) {
2003
+ return (0, import_sharp.default)(filePath, { limitInputPixels: MAX_INPUT_PIXELS }).composite([{ input: Buffer.from(svg) }]).png().toBuffer();
2004
+ }
2005
+ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
2006
+ const byId = /* @__PURE__ */ new Map();
2007
+ for (const crop of crops) byId.set(crop.id, crop);
2008
+ const pad = layout.padding;
2009
+ const composites = await Promise.all(
2010
+ layout.placements.map(async (placement3) => {
2011
+ const crop = byId.get(placement3.id);
2012
+ if (crop === void 0) {
2013
+ throw new AutoRigInputError(
2014
+ `no crop for atlas placement "${placement3.id}"`
2015
+ );
2016
+ }
2017
+ const input = pad > 0 ? await (0, import_sharp.default)(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
2018
+ return { input, left: placement3.x, top: placement3.y };
2019
+ })
2020
+ );
2021
+ const page = await (0, import_sharp.default)({
2022
+ create: {
2023
+ width: layout.pageWidth,
2024
+ height: layout.pageHeight,
2025
+ channels: 4,
2026
+ background: { r: 0, g: 0, b: 0, alpha: 0 }
2027
+ }
2028
+ }).composite(composites).png(
2029
+ quantizeColors === void 0 ? {} : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 }
2030
+ ).toBuffer();
2031
+ return `data:image/png;base64,${page.toString("base64")}`;
2032
+ }
2033
+
2034
+ // src/probe.ts
2035
+ var OUTPUT_SUFFIX = ".probe.json";
2036
+ var OPAQUE = 128;
2037
+ function paintRuns(png) {
2038
+ const { width, height, rgba } = png;
2039
+ const rows = [];
2040
+ let y0 = -1;
2041
+ for (let y = 0; y < height; y++) {
2042
+ const runs = [];
2043
+ let start = -1;
2044
+ for (let x = 0; x < width; x++) {
2045
+ const on = rgba[(y * width + x) * 4 + 3] >= OPAQUE;
2046
+ if (on && start < 0) start = x;
2047
+ if (!on && start >= 0) {
2048
+ runs.push([start, x]);
2049
+ start = -1;
2050
+ }
2051
+ }
2052
+ if (start >= 0) runs.push([start, width]);
2053
+ if (runs.length > 0 && y0 < 0) y0 = y;
2054
+ if (y0 >= 0) rows.push(runs);
2055
+ }
2056
+ while (rows.length > 0 && rows[rows.length - 1].length === 0) rows.pop();
2057
+ return rows.length === 0 ? { y0: 0, rows: [] } : { y0, rows };
2058
+ }
2059
+ function toCanvas(model, pts) {
2060
+ const hw = model.canvas.width / 2;
2061
+ const hh = model.canvas.height / 2;
2062
+ const out = new Float64Array(pts.length);
2063
+ for (let i = 0; i < pts.length; i += 2) {
2064
+ out[i] = hw + pts[i];
2065
+ out[i + 1] = hh - pts[i + 1];
2066
+ }
2067
+ return out;
2068
+ }
2069
+ var round = (v) => Math.round(v * 1e3) / 1e3 + 0;
2070
+ function locate(vertices, tri, x, y) {
2071
+ const [a, b, c] = tri;
2072
+ const ax = vertices[a * 2];
2073
+ const ay = vertices[a * 2 + 1];
2074
+ const bx = vertices[b * 2];
2075
+ const by = vertices[b * 2 + 1];
2076
+ const cx = vertices[c * 2];
2077
+ const cy = vertices[c * 2 + 1];
2078
+ const d = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
2079
+ if (Math.abs(d) < 1e-12) return null;
2080
+ const l1 = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / d;
2081
+ const l2 = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / d;
2082
+ const l3 = 1 - l1 - l2;
2083
+ const eps = 1e-9;
2084
+ return l1 >= -eps && l2 >= -eps && l3 >= -eps ? [l1, l2, l3] : null;
2085
+ }
2086
+ var QUAD_INDICES = [0, 1, 2, 1, 3, 2];
2087
+ function restMesh(model, cache, partId) {
2088
+ let m = cache.get(partId);
2089
+ if (m) return m;
2090
+ const part = model.parts.find((p) => p.id === partId);
2091
+ const indices = part.mesh ? part.mesh.indices : QUAD_INDICES;
2092
+ const rest = toCanvas(model, landParts(model, {}, [partId]).get(partId));
2093
+ const boxes = new Float64Array(indices.length / 3 * 4);
2094
+ for (let t = 0; t < indices.length / 3; t++) {
2095
+ let x0 = Infinity;
2096
+ let y0 = Infinity;
2097
+ let x1 = -Infinity;
2098
+ let y1 = -Infinity;
2099
+ for (let k = 0; k < 3; k++) {
2100
+ const v = indices[t * 3 + k];
2101
+ x0 = Math.min(x0, rest[v * 2]);
2102
+ x1 = Math.max(x1, rest[v * 2]);
2103
+ y0 = Math.min(y0, rest[v * 2 + 1]);
2104
+ y1 = Math.max(y1, rest[v * 2 + 1]);
2105
+ }
2106
+ boxes.set([x0, y0, x1, y1], t * 4);
2107
+ }
2108
+ m = { indices, rest, boxes };
2109
+ cache.set(partId, m);
2110
+ return m;
2111
+ }
2112
+ function locatePoints(mesh, points) {
2113
+ const { indices, rest, boxes } = mesh;
2114
+ const slack = 1e-6;
2115
+ return points.map(([x, y]) => {
2116
+ for (let t = 0; t < indices.length / 3; t++) {
2117
+ const b = t * 4;
2118
+ if (x < boxes[b] - slack || x > boxes[b + 2] + slack || y < boxes[b + 1] - slack || y > boxes[b + 3] + slack) {
2119
+ continue;
2120
+ }
2121
+ const tri = [
2122
+ indices[t * 3],
2123
+ indices[t * 3 + 1],
2124
+ indices[t * 3 + 2]
2125
+ ];
2126
+ const w = locate(rest, tri, x, y);
2127
+ if (w) return { tri, w };
2128
+ }
2129
+ return null;
2130
+ });
2131
+ }
2132
+ function landLocated(posed, at) {
2133
+ if (at === null) return null;
2134
+ let px2 = 0;
2135
+ let py = 0;
2136
+ for (let k = 0; k < 3; k++) {
2137
+ px2 += at.w[k] * posed[at.tri[k] * 2];
2138
+ py += at.w[k] * posed[at.tri[k] * 2 + 1];
2139
+ }
2140
+ return [px2, py];
2141
+ }
2142
+ function landPoints(model, cache, partId, points, pose) {
2143
+ const located = locatePoints(restMesh(model, cache, partId), points);
2144
+ const posed = toCanvas(model, landParts(model, pose, [partId]).get(partId));
2145
+ return located.map((at) => landLocated(posed, at));
2146
+ }
2147
+ function invalid(i, field, what) {
2148
+ return new AutoRigInputError(`queries[${i}].${field} ${what}`);
2149
+ }
2150
+ function checkPoints(i, points) {
2151
+ if (!Array.isArray(points) || points.length === 0) {
2152
+ throw invalid(i, "points", "must be a non-empty list of [x, y]");
2153
+ }
2154
+ if (points.length > MAX_PROBE_POINTS) {
2155
+ throw invalid(
2156
+ i,
2157
+ "points",
2158
+ `has ${points.length} points; at most ${MAX_PROBE_POINTS} per query`
2159
+ );
2160
+ }
2161
+ points.forEach((pt, k) => {
2162
+ if (!Array.isArray(pt) || pt.length !== 2 || !pt.every((v) => Number.isFinite(v))) {
2163
+ throw invalid(i, `points[${k}]`, "must be [x, y] with finite numbers");
2164
+ }
2165
+ });
2166
+ return points;
2167
+ }
2168
+ function checkPose(model, i, pose) {
2169
+ const declared = new Set(model.parameters.map((p) => p.id));
2170
+ for (const [id, v] of Object.entries(pose ?? {})) {
2171
+ if (!declared.has(id)) {
2172
+ throw invalid(i, `pose.${id}`, "is not a parameter the model declares");
2173
+ }
2174
+ if (typeof v !== "number" || !Number.isFinite(v)) {
2175
+ throw invalid(i, `pose.${id}`, "must be a finite number");
2176
+ }
2177
+ }
2178
+ return pose ?? {};
2179
+ }
2180
+ function checkQuery(model, q, i) {
2181
+ if (q.op === "paint") return { op: "paint", path: q.path };
2182
+ if (q.op !== "land" && q.op !== "displacement") {
2183
+ throw invalid(i, "op", `must be paint, land or displacement`);
2184
+ }
2185
+ if (!model.parts.some((p) => p.id === q.part)) {
2186
+ throw invalid(i, "part", `names no part of the model: ${String(q.part)}`);
2187
+ }
2188
+ return {
2189
+ op: q.op,
2190
+ part: q.part,
2191
+ points: checkPoints(i, q.points),
2192
+ pose: checkPose(model, i, q.pose)
2193
+ };
2194
+ }
2195
+ async function runQuery(model, cache, q, i) {
2196
+ if (q.op === "paint") {
2197
+ const file = resolveInputPath(q.path, `queries[${i}].path`);
2198
+ let png;
2199
+ try {
2200
+ png = await decodePng(file);
2201
+ } catch (e) {
2202
+ if (e instanceof AutoRigInputError) throw invalid(i, "path", e.message);
2203
+ throw e;
2204
+ }
2205
+ const { width, height } = model.canvas;
2206
+ if (png.width !== width || png.height !== height) {
2207
+ throw invalid(
2208
+ i,
2209
+ "path",
2210
+ `is ${png.width}x${png.height}, not the model's canvas ${width}x${height}: ${q.path}`
2211
+ );
2212
+ }
2213
+ return { op: "paint", ...paintRuns(png) };
2214
+ }
2215
+ const { points } = q;
2216
+ const landed = landPoints(model, cache, q.part, points, q.pose);
2217
+ return {
2218
+ op: q.op,
2219
+ part: q.part,
2220
+ points: landed.map(
2221
+ (l, k) => l === null ? null : q.op === "land" ? [round(l[0]), round(l[1])] : [round(l[0] - points[k][0]), round(l[1] - points[k][1])]
2222
+ )
2223
+ };
2224
+ }
2225
+ function summarize(r, i) {
2226
+ if (r.op === "paint") {
2227
+ return `${i} paint: ${r.rows.length} rows from y ${r.y0}`;
2228
+ }
2229
+ const off = r.points.filter((p) => p === null).length;
2230
+ return `${i} ${r.op} ${r.part}: ${r.points.length} points, ${off} off the mesh`;
2231
+ }
2232
+ async function probeRig(input) {
2233
+ try {
2234
+ const outFile = input.outputPath !== void 0 ? resolveOutputPath(input.outputPath, OUTPUT_SUFFIX) : void 0;
2235
+ const modelFile = confineToWorkingDirectory(
2236
+ process.cwd(),
2237
+ resolveInputPath(input.modelPath, "model"),
2238
+ "model path",
2239
+ input.modelPath
2240
+ );
2241
+ const model = (0, import_format8.loadIkiModel)((0, import_node_fs2.readFileSync)(modelFile, "utf8"));
2242
+ if (!Array.isArray(input.queries) || input.queries.length === 0) {
2243
+ throw new AutoRigInputError("queries must be a non-empty list");
2244
+ }
2245
+ if (input.queries.length > MAX_PROBE_QUERIES) {
2246
+ throw new AutoRigInputError(
2247
+ `queries has ${input.queries.length} entries; at most ${MAX_PROBE_QUERIES} per call`
2248
+ );
2249
+ }
2250
+ const checked = input.queries.map((q, i) => checkQuery(model, q, i));
2251
+ const cache = /* @__PURE__ */ new Map();
2252
+ const results = [];
2253
+ for (const [i, q] of checked.entries()) {
2254
+ results.push(await runQuery(model, cache, q, i));
2255
+ }
2256
+ if (outFile === void 0) return { ok: true, results };
2257
+ writeFileAtomic(outFile, JSON.stringify(results));
2258
+ return {
2259
+ ok: true,
2260
+ outputPath: outFile,
2261
+ lines: results.map(summarize)
2262
+ };
2263
+ } catch (e) {
2264
+ if (e instanceof AutoRigInputError || e instanceof import_format8.IkiFormatError) {
2265
+ return { ok: false, error: e.message };
2266
+ }
2267
+ throw e;
2268
+ }
2269
+ }
2270
+
2271
+ // src/custom-gate.ts
2272
+ var CUSTOM_GATE_LIMITS = {
2273
+ tie: 5e-3,
2274
+ slide: 0.1,
2275
+ onAnchor: 0.015,
2276
+ exposed: 9e-4,
2277
+ rigid: 25e-4
2278
+ };
2279
+ function foldLimit(model) {
2280
+ return checkFolds(model, { poses: [] }).thresholds.collapse;
2281
+ }
2282
+ function failedCustomGate(model, error) {
2283
+ const message = error instanceof Error ? error.message : String(error);
2284
+ return {
2285
+ ok: false,
2286
+ faceWidth: model.parts.find((p) => p.id === "face")?.width ?? 0,
2287
+ limits: { ...CUSTOM_GATE_LIMITS, fold: foldLimit(model) },
2288
+ poses: 0,
2289
+ parts: [],
2290
+ failed: [`gate error: ${message}`]
2291
+ };
2292
+ }
2293
+ function readingOf(faceWidth, amount, dimension, pose, limit, reason) {
2294
+ const value = amount === null ? null : amount / faceWidth ** dimension;
2295
+ const pass = value !== null && value <= limit;
2296
+ return {
2297
+ value,
2298
+ ...dimension === 1 ? { px: amount } : { px2: amount },
2299
+ pose,
2300
+ limit,
2301
+ pass,
2302
+ ...pass ? {} : { reason }
2303
+ };
2304
+ }
2305
+ var TWIN_FACE = 402;
2306
+ var RING_PX = 5;
2307
+ var RING_DIAGONAL_PX = 4;
2308
+ var SAMPLE_REACH_PX = 80;
2309
+ var SAMPLE_STEP_PX = 4;
2310
+ var TIP_INSET_PX = 6;
2311
+ var EXPOSED_REACH = 0.15;
2312
+ var runsAt = (paint, y) => paint.rows[y - paint.y0] ?? [];
2313
+ function paintedAt(paint, x, y) {
2314
+ const px2 = Math.floor(x);
2315
+ return runsAt(paint, Math.floor(y)).some(([a, b]) => px2 >= a && px2 < b);
2316
+ }
2317
+ var GRID_CELLS = 64;
2318
+ function triangleGrid(posed, indices, bounds) {
2319
+ const cell = Math.max(
2320
+ 16,
2321
+ (bounds.x1 - bounds.x0) / GRID_CELLS,
2322
+ (bounds.y1 - bounds.y0) / GRID_CELLS
2323
+ );
2324
+ const cols = Math.floor((bounds.x1 - bounds.x0) / cell) + 1;
2325
+ const rows = Math.floor((bounds.y1 - bounds.y0) / cell) + 1;
2326
+ const bins = /* @__PURE__ */ new Map();
2327
+ for (let t = 0; t < indices.length / 3; t++) {
2328
+ let x0 = Infinity;
2329
+ let y0 = Infinity;
2330
+ let x1 = -Infinity;
2331
+ let y1 = -Infinity;
2332
+ for (let k = 0; k < 3; k++) {
2333
+ const v = indices[t * 3 + k];
2334
+ x0 = Math.min(x0, posed[v * 2]);
2335
+ x1 = Math.max(x1, posed[v * 2]);
2336
+ y0 = Math.min(y0, posed[v * 2 + 1]);
2337
+ y1 = Math.max(y1, posed[v * 2 + 1]);
2338
+ }
2339
+ if (x1 < bounds.x0 || x0 > bounds.x1 || y1 < bounds.y0 || y0 > bounds.y1) {
2340
+ continue;
2341
+ }
2342
+ const cx0 = Math.max(0, Math.floor((x0 - bounds.x0) / cell));
2343
+ const cx1 = Math.min(cols - 1, Math.floor((x1 - bounds.x0) / cell));
2344
+ const cy0 = Math.max(0, Math.floor((y0 - bounds.y0) / cell));
2345
+ const cy1 = Math.min(rows - 1, Math.floor((y1 - bounds.y0) / cell));
2346
+ for (let cy = cy0; cy <= cy1; cy++) {
2347
+ for (let cx = cx0; cx <= cx1; cx++) {
2348
+ const k = cx + cy * cols;
2349
+ const bin = bins.get(k);
2350
+ if (bin) bin.push(t);
2351
+ else bins.set(k, [t]);
2352
+ }
2353
+ }
2354
+ }
2355
+ return (x, y) => x < bounds.x0 || y < bounds.y0 || x > bounds.x1 || y > bounds.y1 ? [] : bins.get(
2356
+ Math.floor((x - bounds.x0) / cell) + Math.floor((y - bounds.y0) / cell) * cols
2357
+ ) ?? [];
2358
+ }
2359
+ function posesOf(model, baked, base) {
2360
+ const byName = new Map(base.map((p) => [p.name, p]));
2361
+ const add = (values) => {
2362
+ const pose = foldPose(values);
2363
+ if (!byName.has(pose.name)) byName.set(pose.name, pose);
2364
+ };
2365
+ const defaults = new Map(model.parameters.map((p) => [p.id, p.default]));
2366
+ for (const [param, stops] of baked) {
2367
+ for (const v of stops) if (v !== defaults.get(param)) add({ [param]: v });
2368
+ }
2369
+ const params = [...baked.keys()];
2370
+ for (let i = 0; i < params.length; i++) {
2371
+ for (let j = i + 1; j < params.length; j++) {
2372
+ for (const a of baked.get(params[i])) {
2373
+ if (a === defaults.get(params[i])) continue;
2374
+ for (const b of baked.get(params[j])) {
2375
+ if (b === defaults.get(params[j])) continue;
2376
+ add({ [params[i]]: a, [params[j]]: b });
2377
+ }
2378
+ }
2379
+ }
2380
+ }
2381
+ return [...byName.values()];
2382
+ }
2383
+ function freeEnd(paint, tie, inset) {
2384
+ if (paint.rows.length === 0) return null;
2385
+ const [top, bottom] = [paint.y0, paint.y0 + paint.rows.length - 1];
2386
+ const y = Math.abs(bottom - tie[1]) > Math.abs(top - tie[1]) ? bottom : top;
2387
+ const runs = runsAt(paint, y);
2388
+ if (runs.length === 0) return null;
2389
+ const widest = runs.reduce((a, b) => b[1] - b[0] > a[1] - a[0] ? b : a);
2390
+ return [(widest[0] + widest[1]) / 2, y > tie[1] ? y - inset : y + inset];
2391
+ }
2392
+ function checkCustomGate(model, parts, paints, options = {}) {
2393
+ const face = model.parts.find((p) => p.id === "face");
2394
+ if (face === void 0) throw new Error("custom gate: the model has no face");
2395
+ const faceWidth = face.width;
2396
+ const limits = {
2397
+ ...CUSTOM_GATE_LIMITS,
2398
+ fold: foldLimit(model)
2399
+ };
2400
+ if (parts.length === 0) {
2401
+ return {
2402
+ ok: true,
2403
+ faceWidth,
2404
+ limits,
2405
+ poses: 0,
2406
+ parts: [],
2407
+ failed: []
2408
+ };
2409
+ }
2410
+ const scale2 = faceWidth / TWIN_FACE;
2411
+ const px2 = (twin) => Math.max(1, Math.round(twin * scale2));
2412
+ const cache = /* @__PURE__ */ new Map();
2413
+ const turnParam = model.parameters.find(
2414
+ (p) => p.id === import_format9.StandardParameter.AngleX
2415
+ );
2416
+ const turns = (pose) => turnParam !== void 0 && (pose.values[import_format9.StandardParameter.AngleX] ?? turnParam.default) !== turnParam.default;
2417
+ const bakedOf = (id) => {
2418
+ const part = model.parts.find((p) => p.id === id);
2419
+ return new Map(
2420
+ (part.warps ?? []).map((w) => [
2421
+ w.parameter,
2422
+ w.keyforms.map((k) => k.value)
2423
+ ])
2424
+ );
2425
+ };
2426
+ const base = options.poses ?? foldPoses(model);
2427
+ const poseSets = parts.map((part) => {
2428
+ if (!model.parts.some((p) => p.id === part.id)) {
2429
+ throw new Error(`custom gate: the model has no part "${part.id}"`);
2430
+ }
2431
+ return options.poses ?? posesOf(model, bakedOf(part.id), base);
2432
+ });
2433
+ const all = new Map(poseSets.flat().map((p) => [p.name, p]));
2434
+ const reports = parts.map((part, n) => {
2435
+ const poses = poseSets[n];
2436
+ const roleParts = (0, import_editor3.partIdsOfRole)(part.anchor).filter(
2437
+ (id) => model.parts.some((p) => p.id === id)
2438
+ );
2439
+ const anchorId = roleParts.find(
2440
+ (id) => locatePoints(restMesh(model, cache, id), [part.tie])[0] !== null
2441
+ ) ?? roleParts[0];
2442
+ const folds = checkFolds(model, { poses });
2443
+ const anchorPart = model.parts.find((p) => p.id === anchorId);
2444
+ if (anchorPart === void 0) {
2445
+ throw new Error(`custom gate: the model has no part "${anchorId}"`);
2446
+ }
2447
+ const ownPaint = paints.get(part.id);
2448
+ const anchorPaint = paints.get(part.anchor);
2449
+ if (ownPaint === void 0 || anchorPaint === void 0) {
2450
+ throw new Error(
2451
+ `custom gate: no paint for "${ownPaint === void 0 ? part.id : part.anchor}"`
2452
+ );
2453
+ }
2454
+ const partMesh = restMesh(model, cache, part.id);
2455
+ const anchorMesh = restMesh(model, cache, anchorId);
2456
+ const length = (amount, pose, limit, reason) => readingOf(faceWidth, amount, 1, pose, limit, reason);
2457
+ const ring = [
2458
+ [0, 0],
2459
+ [px2(RING_PX), 0],
2460
+ [-px2(RING_PX), 0],
2461
+ [0, px2(RING_PX)],
2462
+ [0, -px2(RING_PX)],
2463
+ [px2(RING_DIAGONAL_PX), px2(RING_DIAGONAL_PX)],
2464
+ [-px2(RING_DIAGONAL_PX), px2(RING_DIAGONAL_PX)],
2465
+ [px2(RING_DIAGONAL_PX), -px2(RING_DIAGONAL_PX)],
2466
+ [-px2(RING_DIAGONAL_PX), -px2(RING_DIAGONAL_PX)]
2467
+ ].map(([dx, dy]) => [part.tie[0] + dx, part.tie[1] + dy]);
2468
+ const onPart = locatePoints(partMesh, ring);
2469
+ const onAnchor = locatePoints(anchorMesh, ring);
2470
+ const shared = ring.flatMap(
2471
+ (_, i) => onPart[i] && onAnchor[i] ? [i] : []
2472
+ );
2473
+ const reach = px2(SAMPLE_REACH_PX);
2474
+ const step = px2(SAMPLE_STEP_PX);
2475
+ const samples = [];
2476
+ const cx = Math.round(part.tie[0]);
2477
+ const cy = Math.round(part.tie[1]);
2478
+ for (let y = cy - reach; y <= cy + reach; y += step) {
2479
+ const runs = runsAt(anchorPaint, y);
2480
+ for (let x = cx - reach; x <= cx + reach; x += step) {
2481
+ if (runs.some(([a, b]) => x >= a && x < b))
2482
+ samples.push([x + 0.5, y + 0.5]);
2483
+ }
2484
+ }
2485
+ const samplesOn = locatePoints(anchorMesh, samples).filter(
2486
+ (l) => l !== null
2487
+ );
2488
+ const [tieOnPart] = locatePoints(partMesh, [part.tie]);
2489
+ const partIndex = model.parts.findIndex((p) => p.id === part.id);
2490
+ const anchorIndex = model.parts.indexOf(anchorPart);
2491
+ const ownPart = model.parts[partIndex];
2492
+ const partLower = ownPart.order < anchorPart.order || ownPart.order === anchorPart.order && partIndex < anchorIndex;
2493
+ const [lowerId, upperId] = partLower ? [part.id, anchorId] : [anchorId, part.id];
2494
+ const [lowerMesh, upperMesh] = [
2495
+ restMesh(model, cache, lowerId),
2496
+ restMesh(model, cache, upperId)
2497
+ ];
2498
+ const upperPaint = partLower ? anchorPaint : ownPaint;
2499
+ const exposedReach = Math.round(EXPOSED_REACH * faceWidth);
2500
+ const hidden = [];
2501
+ for (let y = Math.floor(part.tie[1]) - exposedReach; y <= Math.ceil(part.tie[1]) + exposedReach; y++) {
2502
+ for (const [a0, a1] of runsAt(ownPaint, y)) {
2503
+ for (const [b0, b1] of runsAt(anchorPaint, y)) {
2504
+ for (let x = Math.max(a0, b0); x < Math.min(a1, b1); x++) {
2505
+ if (Math.hypot(x + 0.5 - part.tie[0], y + 0.5 - part.tie[1]) <= exposedReach) {
2506
+ hidden.push([x + 0.5, y + 0.5]);
2507
+ }
2508
+ }
2509
+ }
2510
+ }
2511
+ }
2512
+ const onAnchorMesh = locatePoints(anchorMesh, hidden);
2513
+ const hiddenOn = locatePoints(lowerMesh, hidden).filter(
2514
+ (l, i) => l !== null && onAnchorMesh[i] !== null
2515
+ );
2516
+ const stops = bakedOf(part.id);
2517
+ const worstOf = {
2518
+ tie: { v: -1, pose: "rest" },
2519
+ slide: { v: -1, pose: "rest" },
2520
+ onAnchor: { v: -1, pose: "rest" },
2521
+ exposed: { v: -1, pose: "rest" },
2522
+ exposedTurn: { v: -1, pose: "rest" },
2523
+ rigid: { v: -1, pose: "rest" }
2524
+ };
2525
+ const keep = (w, v, pose) => {
2526
+ if (v > w.v) {
2527
+ w.v = v;
2528
+ w.pose = pose;
2529
+ }
2530
+ };
2531
+ let onAnchorNull = null;
2532
+ let turningPoses = 0;
2533
+ const rest = partMesh.rest;
2534
+ const restPoints = [];
2535
+ for (let i = 0; i < rest.length; i += 2)
2536
+ restPoints.push([rest[i], rest[i + 1]]);
2537
+ const measureRigid = (pose, posed) => {
2538
+ const moved = [];
2539
+ for (let i = 0; i < posed.length; i += 2)
2540
+ moved.push([posed[i], posed[i + 1]]);
2541
+ keep(worstOf.rigid, (0, import_editor3.rigidResidual)(restPoints, moved), pose.name);
2542
+ };
2543
+ for (const pose of poses) {
2544
+ const landed = landParts(model, pose.values, [part.id, anchorId]);
2545
+ const partPosed = toCanvas(model, landed.get(part.id));
2546
+ const anchorPosed = toCanvas(model, landed.get(anchorId));
2547
+ const turning = turns(pose);
2548
+ if (turning) turningPoses++;
2549
+ let gap = 0;
2550
+ for (const i of shared) {
2551
+ const a = landLocated(partPosed, onPart[i]);
2552
+ const b = landLocated(anchorPosed, onAnchor[i]);
2553
+ gap = Math.max(gap, Math.hypot(a[0] - b[0], a[1] - b[1]));
2554
+ }
2555
+ if (shared.length > 0) {
2556
+ keep(turning ? worstOf.slide : worstOf.tie, gap, pose.name);
2557
+ }
2558
+ if (turning) {
2559
+ const at = landLocated(partPosed, tieOnPart);
2560
+ let nearest = null;
2561
+ if (at !== null) {
2562
+ for (const l of samplesOn) {
2563
+ const q = landLocated(anchorPosed, l);
2564
+ const d = Math.hypot(q[0] - at[0], q[1] - at[1]);
2565
+ if (nearest === null || d < nearest) nearest = d;
2566
+ }
2567
+ }
2568
+ if (nearest === null) onAnchorNull ??= pose.name;
2569
+ else keep(worstOf.onAnchor, nearest, pose.name);
2570
+ }
2571
+ if (hiddenOn.length > 0) {
2572
+ const lowerPosed = lowerId === part.id ? partPosed : anchorPosed;
2573
+ const upperPosed = upperId === part.id ? partPosed : anchorPosed;
2574
+ const upperIndices = upperMesh.indices;
2575
+ const lands = hiddenOn.map((l) => landLocated(lowerPosed, l));
2576
+ const bounds = {
2577
+ x0: Infinity,
2578
+ y0: Infinity,
2579
+ x1: -Infinity,
2580
+ y1: -Infinity
2581
+ };
2582
+ for (const [x, y] of lands) {
2583
+ bounds.x0 = Math.min(bounds.x0, x);
2584
+ bounds.y0 = Math.min(bounds.y0, y);
2585
+ bounds.x1 = Math.max(bounds.x1, x);
2586
+ bounds.y1 = Math.max(bounds.y1, y);
2587
+ }
2588
+ const find = triangleGrid(upperPosed, upperIndices, bounds);
2589
+ let showing = 0;
2590
+ for (const at of lands) {
2591
+ let covered = false;
2592
+ for (const t of find(at[0], at[1])) {
2593
+ const tri = [
2594
+ upperIndices[t * 3],
2595
+ upperIndices[t * 3 + 1],
2596
+ upperIndices[t * 3 + 2]
2597
+ ];
2598
+ const w = locate(upperPosed, tri, at[0], at[1]);
2599
+ if (!w) continue;
2600
+ let rx = 0;
2601
+ let ry = 0;
2602
+ for (let k = 0; k < 3; k++) {
2603
+ rx += w[k] * upperMesh.rest[tri[k] * 2];
2604
+ ry += w[k] * upperMesh.rest[tri[k] * 2 + 1];
2605
+ }
2606
+ covered = paintedAt(upperPaint, rx, ry);
2607
+ break;
2608
+ }
2609
+ if (!covered) showing++;
2610
+ }
2611
+ keep(
2612
+ turning ? worstOf.exposedTurn : worstOf.exposed,
2613
+ showing,
2614
+ pose.name
2615
+ );
2616
+ }
2617
+ if (part.rigid) measureRigid(pose, partPosed);
2618
+ }
2619
+ if (part.rigid) {
2620
+ for (const [param, values] of stops) {
2621
+ const def = model.parameters.find((p) => p.id === param).default;
2622
+ const sorted = [.../* @__PURE__ */ new Set([...values, def])].sort((a, b) => a - b);
2623
+ for (let i = 0; i + 1 < sorted.length; i++) {
2624
+ const mid = foldPose({ [param]: (sorted[i] + sorted[i + 1]) / 2 });
2625
+ const posed = landParts(model, mid.values, [part.id]).get(part.id);
2626
+ measureRigid(mid, toCanvas(model, posed));
2627
+ }
2628
+ }
1884
2629
  }
1885
- } catch (e) {
1886
- throw new AutoRigInputError(
1887
- `write: ${e instanceof Error ? e.message : String(e)}`
2630
+ const tieReading = shared.length === 0 ? length(
2631
+ null,
2632
+ "rest",
2633
+ limits.tie,
2634
+ `no point of the ring around the tie lies on both ${part.id} and ${anchorId}`
2635
+ ) : length(
2636
+ Math.max(0, worstOf.tie.v),
2637
+ worstOf.tie.pose,
2638
+ limits.tie,
2639
+ "the tie comes apart"
2640
+ );
2641
+ const slideReading = length(
2642
+ Math.max(0, worstOf.slide.v),
2643
+ worstOf.slide.pose,
2644
+ limits.slide,
2645
+ "the tie slides too far"
2646
+ );
2647
+ const onAnchorReading = onAnchorNull !== null ? length(
2648
+ null,
2649
+ onAnchorNull,
2650
+ limits.onAnchor,
2651
+ `the tie lands off ${part.id}'s mesh, or no painted point of ${anchorId} near it is on its mesh`
2652
+ ) : length(
2653
+ Math.max(0, worstOf.onAnchor.v),
2654
+ worstOf.onAnchor.pose,
2655
+ limits.onAnchor,
2656
+ `the tie leaves ${anchorId}'s paint`
2657
+ );
2658
+ const exposedReading = readingOf(
2659
+ faceWidth,
2660
+ Math.max(0, worstOf.exposed.v),
2661
+ 2,
2662
+ worstOf.exposed.pose,
2663
+ limits.exposed,
2664
+ "hidden art shows"
2665
+ );
2666
+ const ratioHit = folds.targets.find(
2667
+ (t) => t.target.kind === "part" && t.target.id === part.id
2668
+ )?.worst;
2669
+ const ratio = ratioHit?.ratio ?? 1;
2670
+ const foldsPass = ratio >= limits.fold;
2671
+ const rigidReading = part.rigid ? length(
2672
+ Math.max(0, worstOf.rigid.v),
2673
+ worstOf.rigid.pose,
2674
+ limits.rigid,
2675
+ "the part bends"
2676
+ ) : void 0;
2677
+ const tipAt = freeEnd(ownPaint, part.tie, px2(TIP_INSET_PX));
2678
+ const [tipLoc] = tipAt === null ? [null] : locatePoints(partMesh, [tipAt]);
2679
+ const bareModel = stops.size === 0 ? model : {
2680
+ ...model,
2681
+ parts: model.parts.map(
2682
+ (p) => p.id === part.id ? { ...p, warps: void 0 } : p
2683
+ )
2684
+ };
2685
+ const tip = [...stops.keys()].map((param) => {
2686
+ const def = model.parameters.find((p) => p.id === param);
2687
+ const ends = [def.min, def.max].map((value) => {
2688
+ const at = (m) => landLocated(
2689
+ toCanvas(
2690
+ m,
2691
+ landParts(m, { [param]: value }, [part.id]).get(part.id)
2692
+ ),
2693
+ tipLoc ?? null
2694
+ );
2695
+ const landed = at(model);
2696
+ const bare = at(bareModel);
2697
+ return {
2698
+ value,
2699
+ landed,
2700
+ bare,
2701
+ fromBare: landed && bare ? Math.hypot(landed[0] - bare[0], landed[1] - bare[1]) : null
2702
+ };
2703
+ });
2704
+ const [a, b] = ends;
2705
+ return {
2706
+ param,
2707
+ ends,
2708
+ travel: a.landed && b.landed ? Math.hypot(b.landed[0] - a.landed[0], b.landed[1] - a.landed[1]) : null
2709
+ };
2710
+ });
2711
+ const turningExposed = worstOf.exposedTurn.v < 0 ? null : (({ value, px2: px22, pose }) => ({ value, px2: px22, pose }))(
2712
+ readingOf(
2713
+ faceWidth,
2714
+ worstOf.exposedTurn.v,
2715
+ 2,
2716
+ worstOf.exposedTurn.pose,
2717
+ Infinity,
2718
+ ""
2719
+ )
2720
+ );
2721
+ const slidePass = slideReading.pass && onAnchorReading.pass;
2722
+ const ok = foldsPass && tieReading.pass && slidePass && exposedReading.pass && (rigidReading?.pass ?? true);
2723
+ return {
2724
+ id: part.id,
2725
+ anchor: part.anchor,
2726
+ folds: {
2727
+ ratio,
2728
+ pose: ratioHit?.pose.name ?? "rest",
2729
+ limit: limits.fold,
2730
+ pass: foldsPass,
2731
+ ...foldsPass ? {} : { reason: ratio <= 0 ? "a flip" : "a collapse" }
2732
+ },
2733
+ tie: tieReading,
2734
+ slide: {
2735
+ slide: slideReading,
2736
+ onAnchor: onAnchorReading,
2737
+ turningPoses,
2738
+ pass: slidePass
2739
+ },
2740
+ exposed: {
2741
+ hiddenPx: hiddenOn.length,
2742
+ noTurn: exposedReading,
2743
+ turning: turningExposed,
2744
+ pass: exposedReading.pass
2745
+ },
2746
+ ...rigidReading === void 0 ? {} : { rigid: rigidReading },
2747
+ tip,
2748
+ ok
2749
+ };
2750
+ });
2751
+ const failed = reports.flatMap((r) => [
2752
+ ...r.folds.pass ? [] : [`${r.id} FOLDS`],
2753
+ ...r.tie.pass ? [] : [`${r.id} TIE`],
2754
+ ...r.slide.pass ? [] : [`${r.id} SLIDE`],
2755
+ ...r.exposed.pass ? [] : [`${r.id} EXPOSED`],
2756
+ ...r.rigid === void 0 || r.rigid.pass ? [] : [`${r.id} RIGID`]
2757
+ ]);
2758
+ return {
2759
+ ok: failed.length === 0,
2760
+ faceWidth,
2761
+ limits,
2762
+ poses: all.size,
2763
+ parts: reports,
2764
+ failed
2765
+ };
2766
+ }
2767
+ var both = (faceWidth, px2, digits = 4) => px2 === null ? "off the mesh" : `${px2.toFixed(1)} px (${(px2 / faceWidth).toFixed(digits)} face widths)`;
2768
+ function formatCustomGate(report) {
2769
+ const w = report.faceWidth;
2770
+ const verdict = (pass, reason) => pass ? "pass" : `FAIL: ${reason}`;
2771
+ const limit = (fw) => `${fw} face widths, ${(fw * w).toFixed(1)} px`;
2772
+ const lines = [];
2773
+ for (const r of report.parts) {
2774
+ const at = `CUSTOM ${r.id}`;
2775
+ lines.push(
2776
+ `${at} FOLDS: least triangle area ratio ${r.folds.ratio.toFixed(3)} at [${r.folds.pose}] (limit >= ${r.folds.limit}) ${verdict(r.folds.pass, r.folds.reason)}`
2777
+ );
2778
+ lines.push(
2779
+ `${at} TIE: at the tie and the ring around it, ${r.id} against ${r.anchor}, poses that do not turn the head: max ${both(w, r.tie.px)} at [${r.tie.pose}] (limit <= ${limit(r.tie.limit)}) ${verdict(r.tie.pass, r.tie.reason)}`
2780
+ );
2781
+ const s = r.slide;
2782
+ lines.push(
2783
+ s.turningPoses === 0 ? `${at} SLIDE: no pose turns the head pass` : `${at} SLIDE: poses that turn the head, the same length: max ${both(w, s.slide.px)} at [${s.slide.pose}] (limit <= ${limit(s.slide.limit)}); the tie's distance to the nearest painted point of ${r.anchor} as landed: max ${both(w, s.onAnchor.px)} at [${s.onAnchor.pose}] (limit <= ${limit(s.onAnchor.limit)}) ${verdict(s.pass, s.slide.pass ? s.onAnchor.reason : s.slide.reason)}`
1888
2784
  );
2785
+ const e = r.exposed;
2786
+ const turnText = e.turning === null ? "no pose turns the head" : `max ${e.turning.px2.toFixed(0)} px\xB2 (${e.turning.value.toFixed(5)} face widths\xB2) at [${e.turning.pose}] (reported, no limit)`;
2787
+ lines.push(
2788
+ `${at} EXPOSED: ${e.hiddenPx} px of art both ${r.id} and ${r.anchor} paint near the tie, the lower one's hidden at rest; showing where the head does not turn: max ${(e.noTurn.px2 ?? 0).toFixed(0)} px\xB2 (${(e.noTurn.value ?? 0).toFixed(5)} face widths\xB2) at [${e.noTurn.pose}] (limit <= ${e.noTurn.limit} face widths\xB2, ${(e.noTurn.limit * w * w).toFixed(0)} px\xB2) ${verdict(e.pass, e.noTurn.reason)}; where it turns: ${turnText}`
2789
+ );
2790
+ if (r.rigid) {
2791
+ lines.push(
2792
+ `${at} RIGID: bend against rest: max ${both(w, r.rigid.px)} at [${r.rigid.pose}] (limit <= ${limit(r.rigid.limit)}) ${verdict(r.rigid.pass, r.rigid.reason)}`
2793
+ );
2794
+ }
2795
+ for (const t of r.tip) {
2796
+ const ends = t.ends.map(
2797
+ (x) => `${t.param}=${x.value} lands ${x.landed ? `(${x.landed.map((v) => v.toFixed(1)).join(", ")})` : "off the mesh"}, ${x.fromBare === null ? "-" : both(w, x.fromBare)} from where its deformer alone lands it`
2798
+ ).join("; ");
2799
+ lines.push(
2800
+ `${at} TIP ${t.param}: free end ${ends}; travel end to end ${t.travel === null ? "-" : both(w, t.travel)} (reported, no limit)`
2801
+ );
2802
+ }
1889
2803
  }
2804
+ lines.push(
2805
+ report.ok ? "CUSTOM GATE pass" : `CUSTOM GATE FAIL: ${report.failed.join(", ")}`
2806
+ );
2807
+ return lines;
1890
2808
  }
1891
2809
 
2810
+ // src/render-poses.ts
2811
+ var import_node_fs5 = require("fs");
2812
+ var import_node_path4 = __toESM(require("path"));
2813
+ var import_format10 = require("@ikijs/format");
2814
+
1892
2815
  // src/render-browser.ts
1893
2816
  var import_node_child_process = require("child_process");
1894
- var import_node_fs2 = __toESM(require("fs"));
2817
+ var import_node_fs3 = __toESM(require("fs"));
1895
2818
  var import_node_os = __toESM(require("os"));
1896
2819
  var import_node_path2 = __toESM(require("path"));
1897
2820
  var NO_BROWSER_MESSAGE = "render_poses needs a Chromium-based browser and found none. Install Google Chrome, Microsoft Edge or Chromium, or set CHROME_PATH to its executable.";
@@ -1918,8 +2841,8 @@ var DEFAULT_TIMEOUT_MS = 3e4;
1918
2841
  var BROWSER_CLOSE_MS = 1e3;
1919
2842
  function isExecutableFile(file) {
1920
2843
  try {
1921
- if (!import_node_fs2.default.statSync(file).isFile()) return false;
1922
- import_node_fs2.default.accessSync(file, import_node_fs2.default.constants.X_OK);
2844
+ if (!import_node_fs3.default.statSync(file).isFile()) return false;
2845
+ import_node_fs3.default.accessSync(file, import_node_fs3.default.constants.X_OK);
1923
2846
  return true;
1924
2847
  } catch {
1925
2848
  return false;
@@ -2078,7 +3001,7 @@ async function openPage(cdp, timeoutMs) {
2078
3001
  }
2079
3002
  function removeProfile(profile) {
2080
3003
  try {
2081
- import_node_fs2.default.rmSync(profile, {
3004
+ import_node_fs3.default.rmSync(profile, {
2082
3005
  recursive: true,
2083
3006
  force: true,
2084
3007
  maxRetries: 5,
@@ -2094,7 +3017,7 @@ async function launchBrowser(executable, timeoutMs) {
2094
3017
  "render_poses needs Node 22 or newer (the global WebSocket is missing)."
2095
3018
  );
2096
3019
  }
2097
- const profile = import_node_fs2.default.mkdtempSync(import_node_path2.default.join(import_node_os.default.tmpdir(), "iki-render-"));
3020
+ const profile = import_node_fs3.default.mkdtempSync(import_node_path2.default.join(import_node_os.default.tmpdir(), "iki-render-"));
2098
3021
  let child;
2099
3022
  try {
2100
3023
  child = (0, import_node_child_process.spawn)(
@@ -2114,7 +3037,7 @@ async function launchBrowser(executable, timeoutMs) {
2114
3037
  { stdio: ["ignore", "ignore", "pipe"] }
2115
3038
  );
2116
3039
  } catch (error) {
2117
- import_node_fs2.default.rmSync(profile, { recursive: true, force: true });
3040
+ import_node_fs3.default.rmSync(profile, { recursive: true, force: true });
2118
3041
  throw startError(executable, error);
2119
3042
  }
2120
3043
  let spawnError;
@@ -2397,13 +3320,13 @@ function formatNodReport(report) {
2397
3320
  }
2398
3321
 
2399
3322
  // src/sweep.ts
2400
- var import_node_fs3 = __toESM(require("fs"));
3323
+ var import_node_fs4 = __toESM(require("fs"));
2401
3324
  var import_node_path3 = __toESM(require("path"));
2402
3325
  var SWEEP_CLOCK_HZ = 60;
2403
3326
  var SWEEP_FPS = 30;
2404
3327
  var SWEEP_DURATION_S = 3;
2405
3328
  var BOX_DURATION_S = 6;
2406
- var SWEEP_PRESETS = ["turn", "turn-nod"];
3329
+ var SWEEP_PRESETS = ["turn", "turn-nod", "roll"];
2407
3330
  var SWEEP_WARMUP_S = 0.5;
2408
3331
  var SWEEP_FRAME_MS = 1e3 / SWEEP_CLOCK_HZ * (1 + 1e-9);
2409
3332
  var SHEET_THETAS = [-30, -20, -10, -5, 0, 5, 10, 20, 30];
@@ -2456,29 +3379,37 @@ function boxAngles(t) {
2456
3379
  }
2457
3380
  return { x: 0, y: 0 };
2458
3381
  }
2459
- function sweepDurationS(preset) {
2460
- return preset === "turn" ? SWEEP_DURATION_S : BOX_DURATION_S;
2461
- }
2462
- function schedule(preset) {
2463
- const durationS = sweepDurationS(preset);
2464
- const n = SWEEP_CLOCK_HZ * durationS;
2465
- if (preset === "turn") {
2466
- return {
2467
- parameters: ["ParamAngleX"],
2468
- steps: Array.from({ length: n }, (_, j) => ({
2469
- ParamAngleX: turnTheta(j / SWEEP_CLOCK_HZ)
2470
- })),
2471
- durationS
2472
- };
2473
- }
2474
- return {
2475
- parameters: ["ParamAngleX", "ParamAngleY"],
2476
- steps: Array.from({ length: n }, (_, j) => {
2477
- const { x, y } = boxAngles(j / SWEEP_CLOCK_HZ);
3382
+ var legSheet = (id) => (steps, n) => turnSheetFrames(steps, n, id);
3383
+ var SHAPES = {
3384
+ turn: {
3385
+ durationS: SWEEP_DURATION_S,
3386
+ angles: (t) => ({ ParamAngleX: turnTheta(t) }),
3387
+ sheetFrames: legSheet("ParamAngleX"),
3388
+ label: (s) => `\u03B8 ${signedDeg(s.ParamAngleX)}\xB0`,
3389
+ kymograph: true
3390
+ },
3391
+ // The roll rides the turn's own curve, so its frames sit at the angles the
3392
+ // turn sheet's do.
3393
+ roll: {
3394
+ durationS: SWEEP_DURATION_S,
3395
+ angles: (t) => ({ ParamAngleZ: turnTheta(t) }),
3396
+ sheetFrames: legSheet("ParamAngleZ"),
3397
+ label: (s) => `Z ${signedDeg(s.ParamAngleZ)}\xB0`,
3398
+ kymograph: false
3399
+ },
3400
+ "turn-nod": {
3401
+ durationS: BOX_DURATION_S,
3402
+ angles: (t) => {
3403
+ const { x, y } = boxAngles(t);
2478
3404
  return { ParamAngleX: x, ParamAngleY: y };
2479
- }),
2480
- durationS
2481
- };
3405
+ },
3406
+ sheetFrames: boxSheetFrames,
3407
+ label: (s) => `X ${signedDeg(s.ParamAngleX)}\xB0 Y ${signedDeg(s.ParamAngleY)}\xB0`,
3408
+ kymograph: false
3409
+ }
3410
+ };
3411
+ function sweepDurationS(preset) {
3412
+ return SHAPES[preset].durationS;
2482
3413
  }
2483
3414
  function eyeRowModelPx(model) {
2484
3415
  const landed = landParts(model, {}, ["eye_L", "eye_R"]);
@@ -2504,13 +3435,13 @@ function physicsOutputIds(model) {
2504
3435
  }
2505
3436
  return [...ids];
2506
3437
  }
2507
- function turnSheetFrames(steps, frames) {
3438
+ function turnSheetFrames(steps, frames, id) {
2508
3439
  const onLeg = [];
2509
3440
  for (let k = 0; k < frames; k++) {
2510
3441
  const t = k / SWEEP_FPS;
2511
3442
  if (t >= LEG_FROM_S && t <= LEG_TO_S) onLeg.push(k);
2512
3443
  }
2513
- const x = (k) => steps[CAPTURE_EVERY * k].ParamAngleX;
3444
+ const x = (k) => steps[CAPTURE_EVERY * k][id];
2514
3445
  const picked = [];
2515
3446
  for (const target2 of SHEET_THETAS) {
2516
3447
  let best = onLeg[0];
@@ -2540,7 +3471,13 @@ function signedDeg(angle) {
2540
3471
  return rounded > 0 ? `+${deg}` : deg.replace("-", "\u2212");
2541
3472
  }
2542
3473
  function sweepSpec(model, preset, crop) {
2543
- const { parameters, steps, durationS } = schedule(preset);
3474
+ const shape = SHAPES[preset];
3475
+ const { durationS } = shape;
3476
+ const steps = Array.from(
3477
+ { length: SWEEP_CLOCK_HZ * durationS },
3478
+ (_, j) => shape.angles(j / SWEEP_CLOCK_HZ)
3479
+ );
3480
+ const parameters = Object.keys(steps[0]);
2544
3481
  const frameCount = durationS * SWEEP_FPS;
2545
3482
  const dw = crop ? crop.dw : BUST_SIZE;
2546
3483
  const dh = crop ? crop.dh : BUST_SIZE;
@@ -2551,15 +3488,11 @@ function sweepSpec(model, preset, crop) {
2551
3488
  (SHEET_MAX_SIDE - 2 * m) / (3 * dw),
2552
3489
  (SHEET_MAX_SIDE - 2 * m - 3 * b) / (3 * dh)
2553
3490
  );
2554
- const frames = preset === "turn" ? turnSheetFrames(steps, frameCount) : boxSheetFrames(steps, frameCount);
2555
- const labelOf = (k) => {
2556
- const s = steps[CAPTURE_EVERY * k];
2557
- const t = (k / SWEEP_FPS).toFixed(2);
2558
- return preset === "turn" ? `\u03B8 ${signedDeg(s.ParamAngleX)}\xB0 t ${t} s` : `X ${signedDeg(s.ParamAngleX)}\xB0 Y ${signedDeg(s.ParamAngleY)}\xB0 t ${t} s`;
2559
- };
3491
+ const frames = shape.sheetFrames(steps, frameCount);
3492
+ const labelOf = (k) => `${shape.label(steps[CAPTURE_EVERY * k])} t ${(k / SWEEP_FPS).toFixed(2)} s`;
2560
3493
  const { width: W, height: H } = model.canvas;
2561
3494
  let kymograph;
2562
- if (preset === "turn") {
3495
+ if (shape.kymograph) {
2563
3496
  const yModel = eyeRowModelPx(model);
2564
3497
  let row = Math.round(dh / 2);
2565
3498
  let at = "middle";
@@ -2639,7 +3572,7 @@ img { max-width: 48vw; height: auto; background: #444; }
2639
3572
  scrub.max = String(n - 1);
2640
3573
  if (b) { bi.style.display = "block"; }
2641
3574
  function short(id) {
2642
- return id === "ParamAngleX" ? "X" : id === "ParamAngleY" ? "Y" : id;
3575
+ return id === "ParamAngleX" ? "X" : id === "ParamAngleY" ? "Y" : id === "ParamAngleZ" ? "Z" : id;
2643
3576
  }
2644
3577
  function show(k) {
2645
3578
  i = k;
@@ -2678,13 +3611,13 @@ var STALE_NAMES = [
2678
3611
  function prepareSweepDir(outDir, name, label) {
2679
3612
  const dir = import_node_path3.default.join(outDir, name);
2680
3613
  try {
2681
- import_node_fs3.default.mkdirSync(dir);
3614
+ import_node_fs4.default.mkdirSync(dir);
2682
3615
  } catch (e) {
2683
3616
  if (e.code !== "EEXIST") {
2684
3617
  throw new AutoRigInputError(`sweep dir: ${e.message}`);
2685
3618
  }
2686
3619
  }
2687
- const stat = import_node_fs3.default.lstatSync(dir);
3620
+ const stat = import_node_fs4.default.lstatSync(dir);
2688
3621
  if (stat.isSymbolicLink()) {
2689
3622
  throw new AutoRigInputError(`${label}.name names ${dir}, a symbolic link`);
2690
3623
  }
@@ -2694,9 +3627,9 @@ function prepareSweepDir(outDir, name, label) {
2694
3627
  return confineToWorkingDirectory(process.cwd(), dir, "sweep dir", name);
2695
3628
  }
2696
3629
  function clearSweepDir(real) {
2697
- for (const entry of import_node_fs3.default.readdirSync(real)) {
3630
+ for (const entry of import_node_fs4.default.readdirSync(real)) {
2698
3631
  if (STALE_FILE.test(entry) || STALE_NAMES.includes(entry)) {
2699
- import_node_fs3.default.rmSync(import_node_path3.default.join(real, entry));
3632
+ import_node_fs4.default.rmSync(import_node_path3.default.join(real, entry));
2700
3633
  }
2701
3634
  }
2702
3635
  }
@@ -2812,9 +3745,9 @@ function planRenders(model, requested, sweep, sweeps) {
2812
3745
  }
2813
3746
  const bodyAngles = Object.fromEntries(
2814
3747
  [
2815
- import_format8.StandardParameter.BodyAngleX,
2816
- import_format8.StandardParameter.BodyAngleY,
2817
- import_format8.StandardParameter.BodyAngleZ
3748
+ import_format10.StandardParameter.BodyAngleX,
3749
+ import_format10.StandardParameter.BodyAngleY,
3750
+ import_format10.StandardParameter.BodyAngleZ
2818
3751
  ].filter((id) => model.parameters.some((p) => p.id === id)).map((id) => [id, -10])
2819
3752
  );
2820
3753
  const poses = [
@@ -2900,7 +3833,7 @@ function planRenders(model, requested, sweep, sweeps) {
2900
3833
  whole("full-elbow-r-45", { ParamElbowR: 45 }),
2901
3834
  whole("full-elbow-r-90", { ParamElbowR: 90 })
2902
3835
  );
2903
- if (model.parameters.some((p) => p.id === import_format8.StandardParameter.ArmPoseRight)) {
3836
+ if (model.parameters.some((p) => p.id === import_format10.StandardParameter.ArmPoseRight)) {
2904
3837
  poses.push(
2905
3838
  whole("full-pose-l", { ParamArmPoseL: 1 }),
2906
3839
  whole("full-pose-r", { ParamArmPoseR: 1 }),
@@ -2941,6 +3874,25 @@ function checkRequest(requested, i) {
2941
3874
  }
2942
3875
  }
2943
3876
  }
3877
+ function withoutParts(model, hideParts) {
3878
+ const hidden = new Set(hideParts);
3879
+ hideParts.forEach((id, i) => {
3880
+ if (!model.parts.some((p) => p.id === id)) {
3881
+ throw new AutoRigInputError(
3882
+ `hideParts[${i}] ${JSON.stringify(id)} is not a part of the model`
3883
+ );
3884
+ }
3885
+ const kept = model.parts.find(
3886
+ (p) => !hidden.has(p.id) && p.clip?.masks.includes(id)
3887
+ );
3888
+ if (kept) {
3889
+ throw new AutoRigInputError(
3890
+ `hideParts[${i}] ${JSON.stringify(id)} masks ${JSON.stringify(kept.id)}, which stays; hide ${JSON.stringify(kept.id)} too`
3891
+ );
3892
+ }
3893
+ });
3894
+ return { ...model, parts: model.parts.filter((p) => !hidden.has(p.id)) };
3895
+ }
2944
3896
  var PNG_PREFIX = "data:image/png;base64,";
2945
3897
  var PAGE_SCRIPT_MS = 1e4;
2946
3898
  var LOAD_MS = 6e4;
@@ -2948,7 +3900,7 @@ var CAPTURE_MS = 15e3;
2948
3900
  function readPageScript() {
2949
3901
  const url = new URL("../dist/render-page.global.js", importMetaUrl);
2950
3902
  try {
2951
- return (0, import_node_fs4.readFileSync)(url, "utf8");
3903
+ return (0, import_node_fs5.readFileSync)(url, "utf8");
2952
3904
  } catch (cause) {
2953
3905
  throw new Error(
2954
3906
  "could not read the render page script; run `pnpm build` in packages/mcp",
@@ -3049,8 +4001,9 @@ async function renderPoses(input) {
3049
4001
  input.modelPath
3050
4002
  );
3051
4003
  const outDir = resolveOutputDir(input.outDir);
3052
- const model = (0, import_format8.loadIkiModel)((0, import_node_fs4.readFileSync)(modelFile, "utf8"));
4004
+ const model = (0, import_format10.loadIkiModel)((0, import_node_fs5.readFileSync)(modelFile, "utf8"));
3053
4005
  const plan = planRenders(model, input.poses, input.sweep, input.sweeps);
4006
+ const drawn = input.hideParts ? withoutParts(model, input.hideParts) : model;
3054
4007
  const browser = findBrowser();
3055
4008
  if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
3056
4009
  const pageScript = readPageScript();
@@ -3073,7 +4026,7 @@ async function renderPoses(input) {
3073
4026
  async (evaluate) => {
3074
4027
  await evaluate(pageScript, PAGE_SCRIPT_MS);
3075
4028
  const loaded = await evaluate(
3076
- `window.__ikiRender.load(${JSON.stringify(model)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
4029
+ `window.__ikiRender.load(${JSON.stringify(drawn)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
3077
4030
  LOAD_MS
3078
4031
  );
3079
4032
  const written = [];
@@ -3141,87 +4094,20 @@ async function renderPoses(input) {
3141
4094
  sweeps
3142
4095
  };
3143
4096
  } catch (error) {
3144
- if (error instanceof AutoRigInputError || error instanceof import_format8.IkiFormatError) {
4097
+ if (error instanceof AutoRigInputError || error instanceof import_format10.IkiFormatError) {
3145
4098
  return { ok: false, error: error.message };
3146
4099
  }
3147
4100
  throw error;
3148
4101
  }
3149
4102
  }
3150
4103
 
3151
- // src/node-images.ts
3152
- var import_sharp = __toESM(require("sharp"));
3153
- var import_editor2 = require("@ikijs/editor");
3154
- async function decodePng(filePath) {
3155
- try {
3156
- const pipeline = (0, import_sharp.default)(filePath, { limitInputPixels: MAX_INPUT_PIXELS });
3157
- const metadata = await pipeline.metadata();
3158
- if (metadata.format !== "png") {
3159
- throw new AutoRigInputError(
3160
- `non-PNG image (${metadata.format ?? "unknown"}): ${filePath}`
3161
- );
3162
- }
3163
- const { data, info } = await pipeline.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
3164
- return {
3165
- width: info.width,
3166
- height: info.height,
3167
- rgba: data,
3168
- hasAlpha: metadata.hasAlpha ?? false
3169
- };
3170
- } catch (e) {
3171
- if (e instanceof AutoRigInputError) throw e;
3172
- const msg = e instanceof Error ? e.message : String(e);
3173
- throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);
3174
- }
3175
- }
3176
- function detectAlphaBbox(rgba, width, height) {
3177
- const bbox = (0, import_editor2.detectAlphaBbox)(rgba, width, height);
3178
- if (bbox === null) {
3179
- throw new AutoRigInputError("layer is empty after alpha threshold");
3180
- }
3181
- return bbox;
3182
- }
3183
- function cropToBuffer(rgba, width, height, bbox) {
3184
- return (0, import_sharp.default)(rgba, { raw: { width, height, channels: 4 } }).extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h }).png().toBuffer();
3185
- }
3186
- function encodeOverlayPng(filePath, svg) {
3187
- return (0, import_sharp.default)(filePath, { limitInputPixels: MAX_INPUT_PIXELS }).composite([{ input: Buffer.from(svg) }]).png().toBuffer();
3188
- }
3189
- async function renderAtlasToDataUri(crops, layout, quantizeColors) {
3190
- const byId = /* @__PURE__ */ new Map();
3191
- for (const crop of crops) byId.set(crop.id, crop);
3192
- const pad = layout.padding;
3193
- const composites = await Promise.all(
3194
- layout.placements.map(async (placement3) => {
3195
- const crop = byId.get(placement3.id);
3196
- if (crop === void 0) {
3197
- throw new AutoRigInputError(
3198
- `no crop for atlas placement "${placement3.id}"`
3199
- );
3200
- }
3201
- const input = pad > 0 ? await (0, import_sharp.default)(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
3202
- return { input, left: placement3.x, top: placement3.y };
3203
- })
3204
- );
3205
- const page = await (0, import_sharp.default)({
3206
- create: {
3207
- width: layout.pageWidth,
3208
- height: layout.pageHeight,
3209
- channels: 4,
3210
- background: { r: 0, g: 0, b: 0, alpha: 0 }
3211
- }
3212
- }).composite(composites).png(
3213
- quantizeColors === void 0 ? {} : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 }
3214
- ).toBuffer();
3215
- return `data:image/png;base64,${page.toString("base64")}`;
3216
- }
3217
-
3218
4104
  // src/tools.ts
3219
4105
  function coerceModel(model) {
3220
4106
  try {
3221
- const parsed = typeof model === "string" ? (0, import_format9.loadIkiModel)(model) : (0, import_format9.parseIkiModel)(model);
4107
+ const parsed = typeof model === "string" ? (0, import_format11.loadIkiModel)(model) : (0, import_format11.parseIkiModel)(model);
3222
4108
  return { ok: true, model: parsed };
3223
4109
  } catch (e) {
3224
- if (e instanceof import_format9.IkiFormatError) return { ok: false, error: e.message };
4110
+ if (e instanceof import_format11.IkiFormatError) return { ok: false, error: e.message };
3225
4111
  throw e;
3226
4112
  }
3227
4113
  }
@@ -3330,7 +4216,7 @@ function describeIkiAt(modelPath) {
3330
4216
  "model path",
3331
4217
  modelPath
3332
4218
  );
3333
- return describeIki((0, import_node_fs5.readFileSync)(modelFile, "utf8"));
4219
+ return describeIki((0, import_node_fs6.readFileSync)(modelFile, "utf8"));
3334
4220
  } catch (e) {
3335
4221
  if (e instanceof AutoRigInputError) return { ok: false, error: e.message };
3336
4222
  throw e;
@@ -3338,123 +4224,123 @@ function describeIkiAt(modelPath) {
3338
4224
  }
3339
4225
  var STANDARD_PARAMETER_INFO = [
3340
4226
  {
3341
- id: import_format9.StandardParameter.MouthOpen,
4227
+ id: import_format11.StandardParameter.MouthOpen,
3342
4228
  description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
3343
4229
  },
3344
4230
  {
3345
- id: import_format9.StandardParameter.MouthForm,
4231
+ id: import_format11.StandardParameter.MouthForm,
3346
4232
  description: "Mouth form / smile (-1 .. 1)."
3347
4233
  },
3348
4234
  {
3349
- id: import_format9.StandardParameter.EyeOpenLeft,
4235
+ id: import_format11.StandardParameter.EyeOpenLeft,
3350
4236
  description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
3351
4237
  },
3352
4238
  {
3353
- id: import_format9.StandardParameter.EyeOpenRight,
4239
+ id: import_format11.StandardParameter.EyeOpenRight,
3354
4240
  description: "Right eye open (0 closed .. 1 open)."
3355
4241
  },
3356
4242
  {
3357
- id: import_format9.StandardParameter.EyeballX,
4243
+ id: import_format11.StandardParameter.EyeballX,
3358
4244
  description: "Eyeball gaze, horizontal (-1 .. 1)."
3359
4245
  },
3360
4246
  {
3361
- id: import_format9.StandardParameter.EyeballY,
4247
+ id: import_format11.StandardParameter.EyeballY,
3362
4248
  description: "Eyeball gaze, vertical (-1 .. 1)."
3363
4249
  },
3364
4250
  {
3365
- id: import_format9.StandardParameter.AngleX,
4251
+ id: import_format11.StandardParameter.AngleX,
3366
4252
  description: "Head angle, horizontal degrees."
3367
4253
  },
3368
4254
  {
3369
- id: import_format9.StandardParameter.AngleY,
4255
+ id: import_format11.StandardParameter.AngleY,
3370
4256
  description: "Head angle, vertical degrees."
3371
4257
  },
3372
4258
  {
3373
- id: import_format9.StandardParameter.AngleZ,
4259
+ id: import_format11.StandardParameter.AngleZ,
3374
4260
  description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
3375
4261
  },
3376
4262
  {
3377
- id: import_format9.StandardParameter.BodyAngleX,
4263
+ id: import_format11.StandardParameter.BodyAngleX,
3378
4264
  description: "Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head."
3379
4265
  },
3380
4266
  {
3381
- id: import_format9.StandardParameter.BodyAngleY,
4267
+ id: import_format11.StandardParameter.BodyAngleY,
3382
4268
  description: "Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows."
3383
4269
  },
3384
4270
  {
3385
- id: import_format9.StandardParameter.BodyAngleZ,
4271
+ id: import_format11.StandardParameter.BodyAngleZ,
3386
4272
  description: "Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head."
3387
4273
  },
3388
4274
  {
3389
- id: import_format9.StandardParameter.Breath,
4275
+ id: import_format11.StandardParameter.Breath,
3390
4276
  description: "Idle breath (0 .. 1), cycled by the host."
3391
4277
  },
3392
4278
  {
3393
- id: import_format9.StandardParameter.AmbientSway,
4279
+ id: import_format11.StandardParameter.AmbientSway,
3394
4280
  description: "Ambient sway (-1 .. 1): a slow zero-mean drift the idle writes for physics rigs to follow (the auto-rig's hair in idle). Not a wind: no bias. Stays procedural under a declared Idle group, as Breath does."
3395
4281
  },
3396
4282
  {
3397
- id: import_format9.StandardParameter.BrowLeftY,
4283
+ id: import_format11.StandardParameter.BrowLeftY,
3398
4284
  description: "Left brow raise/lower (-1 .. 1)."
3399
4285
  },
3400
4286
  {
3401
- id: import_format9.StandardParameter.BrowRightY,
4287
+ id: import_format11.StandardParameter.BrowRightY,
3402
4288
  description: "Right brow raise/lower (-1 .. 1)."
3403
4289
  },
3404
4290
  {
3405
- id: import_format9.StandardParameter.BrowLeftAngle,
4291
+ id: import_format11.StandardParameter.BrowLeftAngle,
3406
4292
  description: "Left brow tilt/angle (-1 .. 1)."
3407
4293
  },
3408
4294
  {
3409
- id: import_format9.StandardParameter.BrowRightAngle,
4295
+ id: import_format11.StandardParameter.BrowRightAngle,
3410
4296
  description: "Right brow tilt/angle (-1 .. 1)."
3411
4297
  },
3412
4298
  {
3413
- id: import_format9.StandardParameter.Cheek,
4299
+ id: import_format11.StandardParameter.Cheek,
3414
4300
  description: "Cheek blush strength (0 .. 1), raised by an expression."
3415
4301
  },
3416
4302
  {
3417
- id: import_format9.StandardParameter.HairSwayX,
4303
+ id: import_format11.StandardParameter.HairSwayX,
3418
4304
  description: "Front hair's horizontal sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
3419
4305
  },
3420
4306
  {
3421
- id: import_format9.StandardParameter.HairSwayZ,
4307
+ id: import_format11.StandardParameter.HairSwayZ,
3422
4308
  description: "Front hair's sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
3423
4309
  },
3424
4310
  {
3425
- id: import_format9.StandardParameter.HairBackSway,
4311
+ id: import_format11.StandardParameter.HairBackSway,
3426
4312
  description: "Back hair's sway driver behind the head turn, tilt and ambient drift, one spring slower than the front hair's so the two swing out of phase. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
3427
4313
  },
3428
4314
  {
3429
- id: import_format9.StandardParameter.ArmLeft,
4315
+ id: import_format11.StandardParameter.ArmLeft,
3430
4316
  description: "Left shoulder, degrees; positive raises the arm outward (mirrored on the right)."
3431
4317
  },
3432
4318
  {
3433
- id: import_format9.StandardParameter.ArmRight,
4319
+ id: import_format11.StandardParameter.ArmRight,
3434
4320
  description: "Right shoulder, degrees; positive raises the arm outward (mirrored on the left)."
3435
4321
  },
3436
4322
  {
3437
- id: import_format9.StandardParameter.ElbowLeft,
4323
+ id: import_format11.StandardParameter.ElbowLeft,
3438
4324
  description: "Left elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right)."
3439
4325
  },
3440
4326
  {
3441
- id: import_format9.StandardParameter.ElbowRight,
4327
+ id: import_format11.StandardParameter.ElbowRight,
3442
4328
  description: "Right elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left)."
3443
4329
  },
3444
4330
  {
3445
- id: import_format9.StandardParameter.ArmPoseLeft,
4331
+ id: import_format11.StandardParameter.ArmPoseLeft,
3446
4332
  description: "Left pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm."
3447
4333
  },
3448
4334
  {
3449
- id: import_format9.StandardParameter.ArmPoseRight,
4335
+ id: import_format11.StandardParameter.ArmPoseRight,
3450
4336
  description: "Right pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm."
3451
4337
  },
3452
4338
  {
3453
- id: import_format9.StandardParameter.ArmPoseAngleLeft,
4339
+ id: import_format11.StandardParameter.ArmPoseAngleLeft,
3454
4340
  description: "Left pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the right)."
3455
4341
  },
3456
4342
  {
3457
- id: import_format9.StandardParameter.ArmPoseAngleRight,
4343
+ id: import_format11.StandardParameter.ArmPoseAngleRight,
3458
4344
  description: "Right pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the left)."
3459
4345
  }
3460
4346
  ];
@@ -3462,10 +4348,10 @@ function listStandardParameters() {
3462
4348
  return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));
3463
4349
  }
3464
4350
  function describeRigPlan() {
3465
- return { fields: [...import_editor3.RIG_PLAN_FIELDS] };
4351
+ return { fields: [...import_editor4.RIG_PLAN_FIELDS] };
3466
4352
  }
3467
4353
  function formatRigPlanReport(r) {
3468
- const fields = import_editor3.RIG_PLAN_FIELDS.map((f) => {
4354
+ const fields = import_editor4.RIG_PLAN_FIELDS.map((f) => {
3469
4355
  const value = `${f.path}=${r.effective[f.path]}`;
3470
4356
  const clamp2 = r.clamped.find((c) => c.field === f.path);
3471
4357
  if (clamp2 !== void 0) {
@@ -3488,7 +4374,7 @@ function expectInput(label, fn) {
3488
4374
  }
3489
4375
  var LOSSLESS_PAGE_ROLE = "nose";
3490
4376
  async function renderAtlasPage(crops, quantizeColors) {
3491
- const layout = (0, import_editor3.packAtlas)(
4377
+ const layout = (0, import_editor4.packAtlas)(
3492
4378
  crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),
3493
4379
  void 0,
3494
4380
  MAX_ATLAS_SIDE
@@ -3511,9 +4397,20 @@ async function autoRigFromLayers(input) {
3511
4397
  if (!Array.isArray(layers) || layers.length === 0) {
3512
4398
  throw new AutoRigInputError("layers must be a non-empty array");
3513
4399
  }
3514
- if (layers.length > MAX_LAYERS) {
4400
+ const customInputs = input.customParts;
4401
+ if (customInputs !== void 0 && !Array.isArray(customInputs)) {
4402
+ throw new AutoRigInputError("customParts must be an array");
4403
+ }
4404
+ const customEntries = customInputs ?? [];
4405
+ customEntries.forEach((entry, i) => {
4406
+ const at = `customParts[${i}]`;
4407
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
4408
+ throw new AutoRigInputError(`${at} must be a plain object`);
4409
+ }
4410
+ });
4411
+ if (layers.length + customEntries.length > MAX_LAYERS) {
3515
4412
  throw new AutoRigInputError(
3516
- `too many layers: ${layers.length} > ${MAX_LAYERS}`
4413
+ `too many layers: ${layers.length + customEntries.length} > ${MAX_LAYERS}`
3517
4414
  );
3518
4415
  }
3519
4416
  const outPath = resolveOutputPath(
@@ -3526,7 +4423,7 @@ async function autoRigFromLayers(input) {
3526
4423
  );
3527
4424
  }
3528
4425
  if (input.style !== void 0) {
3529
- throw new AutoRigInputError((0, import_editor3.styleRemovedMessage)("style"));
4426
+ throw new AutoRigInputError((0, import_editor4.styleRemovedMessage)("style"));
3530
4427
  }
3531
4428
  const turnTargets = input.turnTargets;
3532
4429
  if (turnTargets !== void 0) {
@@ -3543,9 +4440,12 @@ async function autoRigFromLayers(input) {
3543
4440
  const resolved = resolveInputPath(layer.path);
3544
4441
  return { resolved, fileName: layer.fileName ?? import_node_path5.default.basename(resolved) };
3545
4442
  });
4443
+ const customPaths = customEntries.map(
4444
+ (entry, i) => resolveInputPath(entry.path, `customParts[${i}].path`)
4445
+ );
3546
4446
  const rolePairs = expectInput(
3547
4447
  "role parsing",
3548
- () => (0, import_editor3.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
4448
+ () => (0, import_editor4.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
3549
4449
  );
3550
4450
  const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
3551
4451
  let canvasW = 0;
@@ -3553,6 +4453,8 @@ async function autoRigFromLayers(input) {
3553
4453
  let totalPixels = 0;
3554
4454
  let measurer;
3555
4455
  const crops = [];
4456
+ const paints = /* @__PURE__ */ new Map();
4457
+ const anchorRoles = new Set(customEntries.map((e) => e.anchor));
3556
4458
  for (let i = 0; i < resolvedLayers.length; i++) {
3557
4459
  const { resolved, fileName } = resolvedLayers[i];
3558
4460
  const png = await decodePng(resolved);
@@ -3575,7 +4477,7 @@ async function autoRigFromLayers(input) {
3575
4477
  `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
3576
4478
  );
3577
4479
  }
3578
- measurer = (0, import_editor3.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
4480
+ measurer = (0, import_editor4.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
3579
4481
  } else if (png.width !== canvasW || png.height !== canvasH) {
3580
4482
  throw new AutoRigInputError(
3581
4483
  `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
@@ -3592,9 +4494,48 @@ async function autoRigFromLayers(input) {
3592
4494
  );
3593
4495
  }
3594
4496
  const { bbox } = layer;
4497
+ if (anchorRoles.has(role)) paints.set(role, paintRuns(png));
3595
4498
  const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
3596
4499
  crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
3597
4500
  }
4501
+ const customLayers = [];
4502
+ const customCrops = [];
4503
+ for (let i = 0; i < customEntries.length; i++) {
4504
+ const at = `customParts[${i}]`;
4505
+ const { id } = customEntries[i];
4506
+ const resolved = customPaths[i];
4507
+ const png = await decodePng(resolved);
4508
+ if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
4509
+ throw new AutoRigInputError(
4510
+ `${at}.path ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
4511
+ );
4512
+ }
4513
+ totalPixels += png.width * png.height;
4514
+ if (totalPixels > MAX_TOTAL_PIXELS) {
4515
+ throw new AutoRigInputError(
4516
+ `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
4517
+ );
4518
+ }
4519
+ if (png.width !== canvasW || png.height !== canvasH) {
4520
+ throw new AutoRigInputError(
4521
+ `${at}.path size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
4522
+ );
4523
+ }
4524
+ const bbox = (0, import_editor4.detectAlphaBbox)(png.rgba, png.width, png.height);
4525
+ if (bbox === null) {
4526
+ throw new AutoRigInputError(
4527
+ `${at}.path "${import_node_path5.default.basename(resolved)}": layer is empty after alpha threshold`
4528
+ );
4529
+ }
4530
+ customLayers.push({ fileName: import_node_path5.default.basename(resolved), bbox });
4531
+ paints.set(id, paintRuns(png));
4532
+ customCrops.push({
4533
+ id,
4534
+ buffer: await cropToBuffer(png.rgba, png.width, png.height, bbox),
4535
+ width: bbox.w,
4536
+ height: bbox.h
4537
+ });
4538
+ }
3598
4539
  const measurement = measurer.finish();
3599
4540
  const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;
3600
4541
  const { headEdges, strandEdges } = turnOptions;
@@ -3604,9 +4545,10 @@ async function autoRigFromLayers(input) {
3604
4545
  let turn;
3605
4546
  let patches;
3606
4547
  let rigPlan;
4548
+ let bakeReports;
3607
4549
  let model;
3608
4550
  try {
3609
- model = (0, import_editor3.generateIkiFromLayerSet)(
4551
+ model = (0, import_editor4.generateIkiFromLayerSet)(
3610
4552
  measurement.layers,
3611
4553
  { width: canvasW, height: canvasH },
3612
4554
  {
@@ -3628,16 +4570,30 @@ async function autoRigFromLayers(input) {
3628
4570
  }
3629
4571
  },
3630
4572
  ...headEdges === void 0 ? {} : { headEdges },
3631
- ...strandEdges === void 0 ? {} : { strandEdges }
4573
+ ...strandEdges === void 0 ? {} : { strandEdges },
4574
+ ...input.customParts === void 0 ? {} : {
4575
+ customParts: customEntries.map(
4576
+ ({ path: _path, ...rest }, i) => ({
4577
+ ...rest,
4578
+ layer: customLayers[i]
4579
+ })
4580
+ )
4581
+ },
4582
+ ...input.bakes === void 0 ? {} : {
4583
+ bakes: input.bakes,
4584
+ onBakesApplied: (reports) => {
4585
+ bakeReports = reports;
4586
+ }
4587
+ }
3632
4588
  }
3633
4589
  );
3634
4590
  } catch (e) {
3635
- if (!(e instanceof import_editor3.TurnTargetError || e instanceof import_editor3.LayerGeometryError || e instanceof import_editor3.PatchError || e instanceof import_editor3.RigPlanError)) {
4591
+ if (!(e instanceof import_editor4.TurnTargetError || e instanceof import_editor4.LayerGeometryError || e instanceof import_editor4.PatchError || e instanceof import_editor4.RigPlanError || e instanceof import_editor4.CustomPartError || e instanceof import_editor4.BakeError)) {
3636
4592
  throw e;
3637
4593
  }
3638
4594
  throw new AutoRigInputError(e.message);
3639
4595
  }
3640
- const doc = new import_editor3.EditorDocument(model);
4596
+ const doc = new import_editor4.EditorDocument(model);
3641
4597
  const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
3642
4598
  const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
3643
4599
  await renderAtlasPage(
@@ -3646,7 +4602,9 @@ async function autoRigFromLayers(input) {
3646
4602
  ),
3647
4603
  await renderAtlasPage([losslessCrop], void 0)
3648
4604
  ];
3649
- const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
4605
+ const customPage = customCrops.length === 0 ? void 0 : await renderAtlasPage(customCrops, quantizeColors);
4606
+ const allPages = customPage === void 0 ? pages : [...pages, customPage];
4607
+ const atlasBytes = allPages.reduce((sum, p) => sum + p.dataUri.length, 0);
3650
4608
  if (atlasBytes > MAX_OUTPUT_BYTES) {
3651
4609
  throw new AutoRigInputError(
3652
4610
  `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
@@ -3658,29 +4616,68 @@ async function autoRigFromLayers(input) {
3658
4616
  if (placement3 === void 0) {
3659
4617
  throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
3660
4618
  }
3661
- const uv = (0, import_editor3.uvRectFor)(placement3, {
4619
+ const uv = (0, import_editor4.uvRectFor)(placement3, {
3662
4620
  width: layout.pageWidth,
3663
4621
  height: layout.pageHeight
3664
4622
  });
3665
- return (0, import_editor3.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
4623
+ return (0, import_editor4.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
3666
4624
  })
3667
4625
  );
4626
+ if (customPage !== void 0) {
4627
+ partTextureAssignments.push(
4628
+ ...customPage.crops.map((crop) => {
4629
+ const placement3 = customPage.layout.placements.find(
4630
+ (p) => p.id === crop.id
4631
+ );
4632
+ return {
4633
+ partId: crop.id,
4634
+ uv: (0, import_editor4.uvRectFor)(placement3, {
4635
+ width: customPage.layout.pageWidth,
4636
+ height: customPage.layout.pageHeight
4637
+ })
4638
+ };
4639
+ })
4640
+ );
4641
+ }
3668
4642
  doc.applyAtlas({
3669
4643
  textures: [{ source: pages[0].dataUri }],
3670
4644
  partTextureAssignments
3671
4645
  });
3672
4646
  let patched = doc.getModel();
3673
- if (losslessCrop !== void 0) {
4647
+ if (losslessCrop !== void 0 || customPage !== void 0) {
3674
4648
  patched = structuredClone(patched);
3675
- patched.textures = pages.map((p) => ({ source: p.dataUri }));
3676
- for (const partId of (0, import_editor3.partIdsOfRole)(losslessCrop.id)) {
3677
- patched.parts.find((p) => p.id === partId).texture.index = 1;
4649
+ patched.textures = allPages.map((p) => ({ source: p.dataUri }));
4650
+ if (losslessCrop !== void 0) {
4651
+ for (const partId of (0, import_editor4.partIdsOfRole)(losslessCrop.id)) {
4652
+ patched.parts.find((p) => p.id === partId).texture.index = 1;
4653
+ }
4654
+ }
4655
+ for (const crop of customCrops) {
4656
+ patched.parts.find((p) => p.id === crop.id).texture.index = pages.length;
3678
4657
  }
3679
4658
  }
3680
- const finalModel = (0, import_format9.parseIkiModel)(patched);
4659
+ const finalModel = (0, import_format11.parseIkiModel)(patched);
4660
+ const bakes = bakeReports === void 0 ? void 0 : checkBakes(finalModel, bakeReports);
3681
4661
  writeFileAtomic(outPath, JSON.stringify(finalModel));
3682
4662
  const folds = checkModelFolds(finalModel);
3683
4663
  const physics = checkPhysics(finalModel);
4664
+ let gate;
4665
+ if (input.customParts !== void 0) {
4666
+ try {
4667
+ gate = checkCustomGate(
4668
+ finalModel,
4669
+ customEntries.map(({ id, anchor, tie, rigid }) => ({
4670
+ id,
4671
+ anchor,
4672
+ tie,
4673
+ ...rigid === void 0 ? {} : { rigid }
4674
+ })),
4675
+ paints
4676
+ );
4677
+ } catch (e) {
4678
+ gate = failedCustomGate(finalModel, e);
4679
+ }
4680
+ }
3684
4681
  return {
3685
4682
  ok: true,
3686
4683
  path: outPath,
@@ -3696,7 +4693,26 @@ async function autoRigFromLayers(input) {
3696
4693
  folds,
3697
4694
  physics,
3698
4695
  ...patches === void 0 ? {} : { patches },
3699
- rigPlan
4696
+ rigPlan,
4697
+ ...input.customParts === void 0 ? {} : {
4698
+ customParts: {
4699
+ parts: customCrops.map((crop, i) => {
4700
+ const part = finalModel.parts.find((p) => p.id === crop.id);
4701
+ return {
4702
+ id: crop.id,
4703
+ box: customLayers[i].bbox,
4704
+ mesh: {
4705
+ vertices: part.mesh.vertices.length / 2,
4706
+ triangles: part.mesh.indices.length / 3
4707
+ },
4708
+ order: part.order,
4709
+ page: part.texture.index
4710
+ };
4711
+ }),
4712
+ ...bakes === void 0 ? {} : { bakes },
4713
+ gate
4714
+ }
4715
+ }
3700
4716
  };
3701
4717
  } catch (err) {
3702
4718
  if (err instanceof AutoRigInputError)
@@ -3706,13 +4722,13 @@ async function autoRigFromLayers(input) {
3706
4722
  }
3707
4723
 
3708
4724
  // src/compose.ts
3709
- var import_node_fs7 = __toESM(require("fs"));
4725
+ var import_node_fs8 = __toESM(require("fs"));
3710
4726
  var import_node_path10 = __toESM(require("path"));
3711
4727
  var import_sharp4 = __toESM(require("sharp"));
3712
- var import_editor13 = require("@ikijs/editor");
4728
+ var import_editor14 = require("@ikijs/editor");
3713
4729
 
3714
4730
  // src/trim.ts
3715
- var import_editor4 = require("@ikijs/editor");
4731
+ var import_editor5 = require("@ikijs/editor");
3716
4732
  var TRIM_THRESHOLD = 12;
3717
4733
  var STRAY_SPECK_FRACTION = 0.01;
3718
4734
  function luma(rgba, i) {
@@ -3741,7 +4757,7 @@ function boxWithoutStraySpecks(rgba, W, H) {
3741
4757
  while (depth > 0) {
3742
4758
  const p = stack[--depth];
3743
4759
  size++;
3744
- if (rgba[p * 4 + 3] >= import_editor4.ALPHA_OPAQUE) opaque = true;
4760
+ if (rgba[p * 4 + 3] >= import_editor5.ALPHA_OPAQUE) opaque = true;
3745
4761
  const px2 = p % W;
3746
4762
  const py = (p - px2) / W;
3747
4763
  setLeft = Math.min(setLeft, px2);
@@ -3778,12 +4794,12 @@ function boxWithoutStraySpecks(rgba, W, H) {
3778
4794
  }
3779
4795
 
3780
4796
  // src/measure.ts
3781
- var import_node_fs6 = __toESM(require("fs"));
4797
+ var import_node_fs7 = __toESM(require("fs"));
3782
4798
  var import_node_path9 = __toESM(require("path"));
3783
4799
 
3784
4800
  // src/measure-arms.ts
3785
4801
  var import_node_path6 = __toESM(require("path"));
3786
- var import_editor5 = require("@ikijs/editor");
4802
+ var import_editor6 = require("@ikijs/editor");
3787
4803
  var ARM_ROLES = ["arm_L", "arm_R"];
3788
4804
  var CAP_OVERLAP = 0.5;
3789
4805
  var px = (v) => `${Number(v.toFixed(1))}`;
@@ -3812,7 +4828,7 @@ async function armWarnings(absDir, layers) {
3812
4828
  continue;
3813
4829
  }
3814
4830
  if (set === void 0) {
3815
- const measurer = (0, import_editor5.createLayerSetMeasurer)({
4831
+ const measurer = (0, import_editor6.createLayerSetMeasurer)({
3816
4832
  width: body.canvasW,
3817
4833
  height: body.canvasH
3818
4834
  });
@@ -3820,12 +4836,12 @@ async function armWarnings(absDir, layers) {
3820
4836
  }
3821
4837
  let g;
3822
4838
  try {
3823
- g = (0, import_editor5.armGeometry)(
4839
+ g = (0, import_editor6.armGeometry)(
3824
4840
  await measured(set.measurer, absDir, arm),
3825
4841
  set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2
3826
4842
  );
3827
4843
  } catch (err) {
3828
- if (err instanceof import_editor5.LayerGeometryError) {
4844
+ if (err instanceof import_editor6.LayerGeometryError) {
3829
4845
  warnings.push(
3830
4846
  `${arm}: ${err.message} \u2014 auto_rig_from_layers refuses it. Regenerate arm.png drawn hanging, shoulder at the top. Billed.`
3831
4847
  );
@@ -3853,7 +4869,7 @@ function capWarning(arm, g, body) {
3853
4869
  }
3854
4870
 
3855
4871
  // src/measure-hair-side.ts
3856
- var import_editor6 = require("@ikijs/editor");
4872
+ var import_editor7 = require("@ikijs/editor");
3857
4873
  var LOCK_ROLES = ["hair_side_R", "hair_side_L"];
3858
4874
  var VISIBLE_MIN_PX = 3;
3859
4875
  var LEAN_HH = 0.12;
@@ -3865,7 +4881,7 @@ function covers(runs, x) {
3865
4881
  }
3866
4882
  return false;
3867
4883
  }
3868
- function runsAt(layer, y) {
4884
+ function runsAt2(layer, y) {
3869
4885
  return layer?.rowRuns?.[y - layer.bbox.y] ?? [];
3870
4886
  }
3871
4887
  function opaqueRows(layer) {
@@ -3901,7 +4917,7 @@ async function hairSideWarnings(absDir, layers) {
3901
4917
  }
3902
4918
  }
3903
4919
  if (mismatched) return warnings;
3904
- const measurer = (0, import_editor6.createLayerSetMeasurer)({
4920
+ const measurer = (0, import_editor7.createLayerSetMeasurer)({
3905
4921
  width: ref.canvasW,
3906
4922
  height: ref.canvasH
3907
4923
  });
@@ -3941,8 +4957,8 @@ async function hairSideWarnings(absDir, layers) {
3941
4957
  function rootWarning(role, lock, front) {
3942
4958
  const y = opaqueRows(lock)?.top;
3943
4959
  if (y === void 0) return void 0;
3944
- const frontRuns = runsAt(front, y);
3945
- const lockRuns = runsAt(lock, y);
4960
+ const frontRuns = runsAt2(front, y);
4961
+ const lockRuns = runsAt2(lock, y);
3946
4962
  let shown = 0;
3947
4963
  for (let i = 0; i + 1 < lockRuns.length; i += 2) {
3948
4964
  let stretch = 0;
@@ -3961,7 +4977,7 @@ function rootWarning(role, lock, front) {
3961
4977
  function eyeCornerWarning(role, lock, side, eyeRole, eye) {
3962
4978
  const row = Math.floor(eye.bboxCy);
3963
4979
  const corner = side < 0 ? eye.marginLeft : eye.marginLeft + eye.w - 1;
3964
- const runs = runsAt(lock, row);
4980
+ const runs = runsAt2(lock, row);
3965
4981
  let overlap = 0;
3966
4982
  for (let i = 0; i + 1 < runs.length; i += 2) {
3967
4983
  if (corner < runs[i] || corner >= runs[i + 1]) continue;
@@ -3980,14 +4996,14 @@ function leanWarning(role, lock, side, face, back, eye) {
3980
4996
  const bare = /* @__PURE__ */ new Set();
3981
4997
  const rows = /* @__PURE__ */ new Set();
3982
4998
  for (let y = lockRows.top; y <= Math.min(lockRows.bottom, faceBottom); y++) {
3983
- const runs = runsAt(lock, y);
4999
+ const runs = runsAt2(lock, y);
3984
5000
  if (runs.length === 0) continue;
3985
5001
  const from = side < 0 ? runs[0] : runs[runs.length - 2];
3986
5002
  const to = side < 0 ? runs[1] : runs[runs.length - 1];
3987
5003
  const start = side < 0 ? from : Math.max(from, to - lean);
3988
5004
  const end = side < 0 ? Math.min(to, from + lean) : to;
3989
- const faceRuns = runsAt(face, y);
3990
- const backRuns = runsAt(back, y);
5005
+ const faceRuns = runsAt2(face, y);
5006
+ const backRuns = runsAt2(back, y);
3991
5007
  for (let x = start; x < end; x++) {
3992
5008
  if (covers(faceRuns, x) || covers(backRuns, x)) continue;
3993
5009
  bare.add(x);
@@ -4029,7 +5045,7 @@ function drawsTwoLocks(lock) {
4029
5045
  }
4030
5046
 
4031
5047
  // src/measure-forearm-pose.ts
4032
- var import_editor7 = require("@ikijs/editor");
5048
+ var import_editor8 = require("@ikijs/editor");
4033
5049
  var POSE_ROLES = ["forearm_pose_L", "forearm_pose_R"];
4034
5050
  var ARM_OF = {
4035
5051
  forearm_pose_L: "arm_L",
@@ -4063,7 +5079,7 @@ async function forearmPoseWarnings(absDir, layers) {
4063
5079
  continue;
4064
5080
  }
4065
5081
  if (layers.body === void 0) continue;
4066
- const measurer = (0, import_editor7.createLayerSetMeasurer)({
5082
+ const measurer = (0, import_editor8.createLayerSetMeasurer)({
4067
5083
  width: stats.canvasW,
4068
5084
  height: stats.canvasH
4069
5085
  });
@@ -4071,12 +5087,12 @@ async function forearmPoseWarnings(absDir, layers) {
4071
5087
  let armLayer;
4072
5088
  try {
4073
5089
  armLayer = await measured(measurer, absDir, arm);
4074
- a = (0, import_editor7.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
5090
+ a = (0, import_editor8.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
4075
5091
  } catch (err) {
4076
- if (err instanceof import_editor7.LayerGeometryError) continue;
5092
+ if (err instanceof import_editor8.LayerGeometryError) continue;
4077
5093
  throw err;
4078
5094
  }
4079
- const b = (0, import_editor7.forearmPoseGeometry)(await measured(measurer, absDir, pose));
5095
+ const b = (0, import_editor8.forearmPoseGeometry)(await measured(measurer, absDir, pose));
4080
5096
  warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));
4081
5097
  }
4082
5098
  return warnings;
@@ -4116,11 +5132,11 @@ function jointWarnings(pose, arm, stats, a, armLayer, b) {
4116
5132
 
4117
5133
  // src/measure-lips.ts
4118
5134
  var import_node_path7 = __toESM(require("path"));
4119
- var import_editor9 = require("@ikijs/editor");
5135
+ var import_editor10 = require("@ikijs/editor");
4120
5136
 
4121
5137
  // src/compose-lips.ts
4122
5138
  var import_sharp2 = __toESM(require("sharp"));
4123
- var import_editor8 = require("@ikijs/editor");
5139
+ var import_editor9 = require("@ikijs/editor");
4124
5140
  var KEYED_SRC = "mouth_keyed.png";
4125
5141
  var INTERIOR_SRC = "mouth_interior.png";
4126
5142
  var KEY_CANDIDATE = 0.5;
@@ -4218,7 +5234,7 @@ function keyGreen(rgba, W, H) {
4218
5234
  let candidates = 0;
4219
5235
  for (let p = 0; p < n; p++) {
4220
5236
  const i = p * 4;
4221
- if (rgba[i + 3] < import_editor8.ALPHA_OPAQUE) continue;
5237
+ if (rgba[i + 3] < import_editor9.ALPHA_OPAQUE) continue;
4222
5238
  const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;
4223
5239
  if (excess < KEY_CANDIDATE) continue;
4224
5240
  candidates++;
@@ -4245,7 +5261,7 @@ function keyGreen(rgba, W, H) {
4245
5261
  const dg = rgba[i + 1] - G[1];
4246
5262
  const db = rgba[i + 2] - G[2];
4247
5263
  const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;
4248
- if (rgba[i + 3] < import_editor8.ALPHA_OPAQUE) {
5264
+ if (rgba[i + 3] < import_editor9.ALPHA_OPAQUE) {
4249
5265
  if (green) out[i + 3] = 0;
4250
5266
  } else if (green) {
4251
5267
  fill[p] = 1;
@@ -4421,7 +5437,7 @@ async function prepInterior(rgba, W, H) {
4421
5437
  for (let y = box2.y; y < box2.y + box2.h; y++) {
4422
5438
  for (let x = box2.x; x < box2.x + box2.w; x++) {
4423
5439
  const i = (y * cw + x) * 4;
4424
- if (crop[i + 3] < import_editor8.ALPHA_OPAQUE) continue;
5440
+ if (crop[i + 3] < import_editor9.ALPHA_OPAQUE) continue;
4425
5441
  count++;
4426
5442
  for (let c = 0; c < 3; c++) all[c] += crop[i + c];
4427
5443
  if (luma(crop, i) < CAVITY_LUMA) {
@@ -4444,7 +5460,7 @@ function enclosedHole(frame, w, h) {
4444
5460
  const stack = new Int32Array(n);
4445
5461
  let depth = 0;
4446
5462
  const seed = (p) => {
4447
- if (!outside[p] && alpha(p) < import_editor8.ALPHA_OPAQUE) {
5463
+ if (!outside[p] && alpha(p) < import_editor9.ALPHA_OPAQUE) {
4448
5464
  outside[p] = 1;
4449
5465
  stack[depth++] = p;
4450
5466
  }
@@ -4467,7 +5483,7 @@ function enclosedHole(frame, w, h) {
4467
5483
  }
4468
5484
  const mask = new Uint8Array(n);
4469
5485
  for (let p = 0; p < n; p++) {
4470
- if (alpha(p) < import_editor8.ALPHA_OPAQUE && !outside[p]) mask[p] = 1;
5486
+ if (alpha(p) < import_editor9.ALPHA_OPAQUE && !outside[p]) mask[p] = 1;
4471
5487
  }
4472
5488
  const { label, sizes, boxes } = components(mask, w, h);
4473
5489
  const main2 = largest(sizes);
@@ -4494,7 +5510,7 @@ function enclosedHole(frame, w, h) {
4494
5510
  return { label, main: main2, box: box2 };
4495
5511
  }
4496
5512
  function measureLips(layers, w, h) {
4497
- const measurer = (0, import_editor8.createLayerSetMeasurer)({ width: w, height: h });
5513
+ const measurer = (0, import_editor9.createLayerSetMeasurer)({ width: w, height: h });
4498
5514
  return new Map(
4499
5515
  Object.entries(layers).map(([role, rgba]) => [
4500
5516
  role,
@@ -4512,8 +5528,8 @@ function assertFoldContract(layers, w, h) {
4512
5528
  }
4513
5529
  byRole.set(role, layer);
4514
5530
  }
4515
- const opening = (0, import_editor8.mouthOpening)(byRole);
4516
- const runs = (0, import_editor8.columnRuns)(byRole.get("mouth_inner"));
5531
+ const opening = (0, import_editor9.mouthOpening)(byRole);
5532
+ const runs = (0, import_editor9.columnRuns)(byRole.get("mouth_inner"));
4517
5533
  for (let col = opening.x0; col <= opening.x1; col++) {
4518
5534
  const c = opening.at(col);
4519
5535
  const why = !runs.has(col) ? "has no interior run" : c.Tu > c.T ? `has a gap between the line and the interior (Tu ${c.Tu} > T ${c.T})` : c.T > c.lineTop || c.lineH <= 0 ? `has no line above the interior (T ${c.T}, line top ${c.lineTop})` : c.Bl < c.Bb ? `has a gap between the interior and the skin (Bl ${c.Bl} < Bb ${c.Bb})` : null;
@@ -4543,18 +5559,18 @@ async function splitLipSet(keyedPng, w, h, interior) {
4543
5559
  }
4544
5560
  const centre = Math.round((hb.x0 + hb.x1) / 2);
4545
5561
  let stroke = 0;
4546
- while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= import_editor8.ALPHA_OPAQUE)
5562
+ while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= import_editor9.ALPHA_OPAQUE)
4547
5563
  stroke++;
4548
5564
  const bandCap = BAND_CAP * Math.max(1, stroke);
4549
5565
  const skinRow = new Int32Array(w).fill(-1);
4550
5566
  const inM = new Uint8Array(n);
4551
5567
  for (let x = hb.x0; x <= hb.x1; x++) {
4552
5568
  let y = bot[x];
4553
- while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= import_editor8.ALPHA_OPAQUE && luma(frame, (y * w + x) * 4) < BAND_LUMA)
5569
+ while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= import_editor9.ALPHA_OPAQUE && luma(frame, (y * w + x) * 4) < BAND_LUMA)
4554
5570
  y++;
4555
5571
  for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;
4556
5572
  let r = y;
4557
- while (r < h && alpha(r * w + x) < import_editor8.ALPHA_OPAQUE) r++;
5573
+ while (r < h && alpha(r * w + x) < import_editor9.ALPHA_OPAQUE) r++;
4558
5574
  if (r < h) {
4559
5575
  skinRow[x] = r;
4560
5576
  inM[r * w + x] = 1;
@@ -4564,7 +5580,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
4564
5580
  for (let y = 0; y < h; y++) {
4565
5581
  for (let x = 0; x < w; x++) {
4566
5582
  const p = y * w + x;
4567
- if (inM[p] || alpha(p) < import_editor8.ALPHA_OPAQUE) continue;
5583
+ if (inM[p] || alpha(p) < import_editor9.ALPHA_OPAQUE) continue;
4568
5584
  if (top[x] >= 0 && y < top[x]) continue;
4569
5585
  if (x > 0 && inM[p - 1] || x < w - 1 && inM[p + 1]) grown[p] = 1;
4570
5586
  }
@@ -4574,7 +5590,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
4574
5590
  if (x < 0 || x >= w) continue;
4575
5591
  let first = 0;
4576
5592
  while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;
4577
- if (first > 0 && first < h && alpha((first - 1) * w + x) >= import_editor8.ALPHA_OPAQUE)
5593
+ if (first > 0 && first < h && alpha((first - 1) * w + x) >= import_editor9.ALPHA_OPAQUE)
4578
5594
  wall[x] = 1;
4579
5595
  }
4580
5596
  const gx = hb.x0 - 1;
@@ -4601,7 +5617,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
4601
5617
  if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);
4602
5618
  if (!grown[p]) {
4603
5619
  const a = alpha(p);
4604
- if (a >= import_editor8.ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {
5620
+ if (a >= import_editor9.ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {
4605
5621
  inner.set(interior.cavity, p * 4);
4606
5622
  inner[p * 4 + 3] = 255 - a;
4607
5623
  }
@@ -4666,7 +5682,7 @@ async function restShiftOf(layers, width, height) {
4666
5682
  }
4667
5683
  byRole.set(role, layer);
4668
5684
  }
4669
- return (0, import_editor8.mouthRestShift)(byRole);
5685
+ return (0, import_editor9.mouthRestShift)(byRole);
4670
5686
  }
4671
5687
  async function closedLips(upper, lower, shift, left, top) {
4672
5688
  const shut = async (png, role) => {
@@ -4716,7 +5732,7 @@ async function closedLips(upper, lower, shift, left, top) {
4716
5732
  }
4717
5733
 
4718
5734
  // src/measure-lips.ts
4719
- var isLipLayerRole = (role) => import_editor9.LIP_ROLES.includes(role) || (0, import_editor9.isLipInsideRole)(role);
5735
+ var isLipLayerRole = (role) => import_editor10.LIP_ROLES.includes(role) || (0, import_editor10.isLipInsideRole)(role);
4720
5736
  var MIN_OPENING_ROWS = 8;
4721
5737
  var MIN_LINE_ROWS = 2;
4722
5738
  var GREEN_EXCESS = 40;
@@ -4724,8 +5740,8 @@ var INTERIOR_GAP_FRACTION = 0.05;
4724
5740
  var columns = (cols) => `${cols.length} column${cols.length === 1 ? "" : "s"} (first at x=${cols[0]})`;
4725
5741
  async function lipWarnings(absDir, layers) {
4726
5742
  const warnings = [];
4727
- const present = import_editor9.LIP_ROLES.filter((role) => layers[role] !== void 0);
4728
- const inside = import_editor9.LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
5743
+ const present = import_editor10.LIP_ROLES.filter((role) => layers[role] !== void 0);
5744
+ const inside = import_editor10.LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
4729
5745
  if (present.length === 0) {
4730
5746
  if (inside.length > 0) {
4731
5747
  warnings.push(
@@ -4742,8 +5758,8 @@ async function lipWarnings(absDir, layers) {
4742
5758
  `${present.join("/")}: the lip set cannot be mixed with ${legacy.join("/")} \u2014 auto_rig_from_layers refuses it. Remove one route: compose again with only mouth_keyed.png + mouth_interior.png, or without them.`
4743
5759
  );
4744
5760
  }
4745
- if (present.length < import_editor9.LIP_ROLES.length) {
4746
- const missing = import_editor9.LIP_ROLES.filter((role) => layers[role] === void 0);
5761
+ if (present.length < import_editor10.LIP_ROLES.length) {
5762
+ const missing = import_editor10.LIP_ROLES.filter((role) => layers[role] === void 0);
4747
5763
  warnings.push(
4748
5764
  `${present.join("/")}: partial lip set, missing ${missing.join("/")} \u2014 auto_rig_from_layers refuses it. Compose mouth_keyed.png + mouth_interior.png together, which cuts all three.`
4749
5765
  );
@@ -4774,18 +5790,18 @@ async function lipWarnings(absDir, layers) {
4774
5790
  );
4775
5791
  }
4776
5792
  }
4777
- const measurer = (0, import_editor9.createLayerSetMeasurer)({
5793
+ const measurer = (0, import_editor10.createLayerSetMeasurer)({
4778
5794
  width: inner.canvasW,
4779
5795
  height: inner.canvasH
4780
5796
  });
4781
5797
  const set = /* @__PURE__ */ new Map();
4782
5798
  const green = [];
4783
- for (const role of import_editor9.LIP_ROLES) {
5799
+ for (const role of import_editor10.LIP_ROLES) {
4784
5800
  const fileName = `${role}.png`;
4785
5801
  const { rgba } = await decodePng(import_node_path7.default.join(absDir, fileName));
4786
5802
  set.set(role, measurer.add({ role, fileName, rgba }));
4787
5803
  for (let i = 0; i < rgba.length; i += 4) {
4788
- if (rgba[i + 3] >= import_editor9.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
5804
+ if (rgba[i + 3] >= import_editor10.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
4789
5805
  green.push(role);
4790
5806
  break;
4791
5807
  }
@@ -4793,15 +5809,15 @@ async function lipWarnings(absDir, layers) {
4793
5809
  }
4794
5810
  let opening;
4795
5811
  try {
4796
- opening = (0, import_editor9.mouthOpening)(set);
5812
+ opening = (0, import_editor10.mouthOpening)(set);
4797
5813
  } catch (err) {
4798
- if (err instanceof import_editor9.LayerGeometryError) {
5814
+ if (err instanceof import_editor10.LayerGeometryError) {
4799
5815
  warnings.push(err.message);
4800
5816
  return { warnings };
4801
5817
  }
4802
5818
  throw err;
4803
5819
  }
4804
- const innerRuns = (0, import_editor9.columnRuns)(set.get("mouth_inner"));
5820
+ const innerRuns = (0, import_editor10.columnRuns)(set.get("mouth_inner"));
4805
5821
  const noInterior = [];
4806
5822
  const gap = [];
4807
5823
  const noLine = [];
@@ -4887,8 +5903,8 @@ async function lipWarnings(absDir, layers) {
4887
5903
 
4888
5904
  // src/measure-turn.ts
4889
5905
  var import_node_path8 = __toESM(require("path"));
4890
- var import_editor10 = require("@ikijs/editor");
4891
5906
  var import_editor11 = require("@ikijs/editor");
5907
+ var import_editor12 = require("@ikijs/editor");
4892
5908
  var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
4893
5909
  var IRIS_V_MIN = 0.18;
4894
5910
  var IRIS_V_MAX = 0.95;
@@ -5038,7 +6054,7 @@ async function measureTurnImage(filePath, iris) {
5038
6054
  let transparent = false;
5039
6055
  if (hasAlpha) {
5040
6056
  for (let i = 0; i < n; i++) {
5041
- if (rgba[i * 4 + 3] < import_editor10.ALPHA_OPAQUE) {
6057
+ if (rgba[i * 4 + 3] < import_editor11.ALPHA_OPAQUE) {
5042
6058
  transparent = true;
5043
6059
  break;
5044
6060
  }
@@ -5049,7 +6065,7 @@ async function measureTurnImage(filePath, iris) {
5049
6065
  const fg = new Uint8Array(n);
5050
6066
  const value = new Float32Array(n);
5051
6067
  for (let i = 0; i < n; i++) {
5052
- if (rgba[i * 4 + 3] < import_editor10.ALPHA_OPAQUE) continue;
6068
+ if (rgba[i * 4 + 3] < import_editor11.ALPHA_OPAQUE) continue;
5053
6069
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
5054
6070
  if (maskMode === "alpha") {
5055
6071
  fg[i] = 1;
@@ -5115,12 +6131,12 @@ async function measureTurnImage(filePath, iris) {
5115
6131
  }
5116
6132
  const [irisL, irisR] = best.pair;
5117
6133
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
5118
- const { left, right } = (0, import_editor10.foregroundSpan)(
6134
+ const { left, right } = (0, import_editor11.foregroundSpan)(
5119
6135
  fg,
5120
6136
  width,
5121
6137
  height,
5122
- eyeRow - import_editor10.HEAD_BAND,
5123
- eyeRow + import_editor10.HEAD_BAND
6138
+ eyeRow - import_editor11.HEAD_BAND,
6139
+ eyeRow + import_editor11.HEAD_BAND
5124
6140
  );
5125
6141
  if (right <= left) {
5126
6142
  throw new AutoRigInputError(
@@ -5144,7 +6160,7 @@ async function measureTurnImage(filePath, iris) {
5144
6160
  left,
5145
6161
  right,
5146
6162
  cx: (left + right) / 2,
5147
- half: (0, import_editor10.headHalfOf)({ left, right })
6163
+ half: (0, import_editor11.headHalfOf)({ left, right })
5148
6164
  },
5149
6165
  pairCx: (irisL.cx + irisR.cx) / 2,
5150
6166
  eyeGap: irisR.cx - irisL.cx
@@ -5335,7 +6351,7 @@ function noseSpeckWarning({ core, part }, source) {
5335
6351
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
5336
6352
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
5337
6353
  ];
5338
- return `nose: ${found} \u2014 under ${import_editor11.SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with its shading painted denser, so the drawing itself reaches alpha 128. Billed.`;
6354
+ return `nose: ${found} \u2014 under ${import_editor12.SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with its shading painted denser, so the drawing itself reaches alpha 128. Billed.`;
5339
6355
  }
5340
6356
  async function lashOffSclera(eyePath, lashPath) {
5341
6357
  const eye = await decodePng(eyePath);
@@ -5353,7 +6369,7 @@ async function lashOffSclera(eyePath, lashPath) {
5353
6369
  return { opaque, off };
5354
6370
  }
5355
6371
  async function measureDir(absDir, noseSpeck) {
5356
- const files = import_node_fs6.default.readdirSync(absDir).filter((f) => f.endsWith(".png") && !f.startsWith("preview")).sort();
6372
+ const files = import_node_fs7.default.readdirSync(absDir).filter((f) => f.endsWith(".png") && !f.startsWith("preview")).sort();
5357
6373
  if (files.length === 0) {
5358
6374
  throw new AutoRigInputError(`no role layers in ${absDir}`);
5359
6375
  }
@@ -5473,10 +6489,10 @@ async function measureDir(absDir, noseSpeck) {
5473
6489
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
5474
6490
  } else if (layers.nose !== void 0) {
5475
6491
  const nose = await decodePng(import_node_path9.default.join(absDir, "nose.png"));
5476
- const core = (0, import_editor11.denseCoreOf)(nose.rgba, nose.width, nose.height);
6492
+ const core = (0, import_editor12.denseCoreOf)(nose.rgba, nose.width, nose.height);
5477
6493
  if (core !== null) {
5478
6494
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
5479
- if ((0, import_editor11.isSpeckCore)(core, crop))
6495
+ if ((0, import_editor12.isSpeckCore)(core, crop))
5480
6496
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
5481
6497
  }
5482
6498
  }
@@ -5547,12 +6563,12 @@ function formatMeasureReport(result) {
5547
6563
 
5548
6564
  // src/compose-arms.ts
5549
6565
  var import_sharp3 = __toESM(require("sharp"));
5550
- var import_editor12 = require("@ikijs/editor");
6566
+ var import_editor13 = require("@ikijs/editor");
5551
6567
  var ARM_WIDTH = 0.4;
5552
6568
  var SHOULDER_DROP = 0.12;
5553
6569
  async function armPlacement(role, cfg, part, body) {
5554
6570
  const { data } = await (0, import_sharp3.default)(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
5555
- const layer = (0, import_editor12.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
6571
+ const layer = (0, import_editor13.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
5556
6572
  role,
5557
6573
  fileName: "arm.png",
5558
6574
  rgba: data
@@ -5564,9 +6580,9 @@ async function armPlacement(role, cfg, part, body) {
5564
6580
  }
5565
6581
  let g;
5566
6582
  try {
5567
- g = (0, import_editor12.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
6583
+ g = (0, import_editor13.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
5568
6584
  } catch (err) {
5569
- if (err instanceof import_editor12.LayerGeometryError) {
6585
+ if (err instanceof import_editor13.LayerGeometryError) {
5570
6586
  throw new AutoRigInputError(`layout.${role}: ${err.message}`);
5571
6587
  }
5572
6588
  throw err;
@@ -5593,7 +6609,7 @@ async function armPlacement(role, cfg, part, body) {
5593
6609
  }
5594
6610
  async function poseGeometryOf(role, png, size, when) {
5595
6611
  const { data } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
5596
- const layer = (0, import_editor12.createLayerSetMeasurer)({
6612
+ const layer = (0, import_editor13.createLayerSetMeasurer)({
5597
6613
  width: size.w,
5598
6614
  height: size.h
5599
6615
  }).add({ role, fileName: "forearm_pose.png", rgba: data });
@@ -5602,7 +6618,7 @@ async function poseGeometryOf(role, png, size, when) {
5602
6618
  `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`
5603
6619
  );
5604
6620
  }
5605
- return (0, import_editor12.forearmPoseGeometry)(layer);
6621
+ return (0, import_editor13.forearmPoseGeometry)(layer);
5606
6622
  }
5607
6623
  async function forearmPoseWidth(role, trimmed, elbowRun) {
5608
6624
  const g = await poseGeometryOf(role, trimmed.data, trimmed, "");
@@ -5900,18 +6916,18 @@ function keyWhiteToAlpha(rgba) {
5900
6916
  async function coreAndBoundsOf(png) {
5901
6917
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
5902
6918
  return {
5903
- core: (0, import_editor11.denseCoreOf)(data, info.width, info.height),
6919
+ core: (0, import_editor12.denseCoreOf)(data, info.width, info.height),
5904
6920
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
5905
6921
  };
5906
6922
  }
5907
6923
  async function hasCoverage(png) {
5908
6924
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
5909
- return (0, import_editor13.detectAlphaBbox)(data, info.width, info.height) !== null;
6925
+ return (0, import_editor14.detectAlphaBbox)(data, info.width, info.height) !== null;
5910
6926
  }
5911
6927
  async function noseSizingOf(png) {
5912
6928
  const { core, bounds } = await coreAndBoundsOf(png);
5913
6929
  if (core === null) return { box: bounds, whole: true };
5914
- if ((0, import_editor11.isSpeckCore)(core, bounds)) {
6930
+ if ((0, import_editor12.isSpeckCore)(core, bounds)) {
5915
6931
  return {
5916
6932
  box: bounds,
5917
6933
  whole: true,
@@ -5929,7 +6945,7 @@ async function trimmedPart(role, cfg, partsDir, inMemory, flipSource) {
5929
6945
  img = (0, import_sharp4.default)(inMemory);
5930
6946
  } else {
5931
6947
  const srcPath = import_node_path10.default.join(partsDir, cfg.src);
5932
- if (!import_node_fs7.default.existsSync(srcPath)) {
6948
+ if (!import_node_fs8.default.existsSync(srcPath)) {
5933
6949
  if (cfg.optional) return null;
5934
6950
  throw new AutoRigInputError(
5935
6951
  `missing part source for role "${role}": ${srcPath}` + (role === "mouth" ? " \u2014 draw mouth.png (with mouth_open.png), or the lip set's mouth_keyed.png + mouth_interior.png" : "")
@@ -6033,7 +7049,7 @@ function detachedAboveWhite(rgba, W, H) {
6033
7049
  for (let p = 0; p < n; p++) {
6034
7050
  const alpha = rgba[p * 4 + 3];
6035
7051
  if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)
6036
- ink[p] = alpha >= import_editor13.ALPHA_OPAQUE ? 2 : 1;
7052
+ ink[p] = alpha >= import_editor14.ALPHA_OPAQUE ? 2 : 1;
6037
7053
  }
6038
7054
  const label = new Int32Array(n).fill(-1);
6039
7055
  const stack = new Int32Array(n);
@@ -6114,7 +7130,7 @@ function detachedAboveWhite(rgba, W, H) {
6114
7130
  }
6115
7131
  async function prepEyeSplit(partsDir) {
6116
7132
  const srcPath = import_node_path10.default.join(partsDir, EYEWHITE_SRC);
6117
- if (!import_node_fs7.default.existsSync(srcPath)) {
7133
+ if (!import_node_fs8.default.existsSync(srcPath)) {
6118
7134
  throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);
6119
7135
  }
6120
7136
  const { width: W, height: H, rgba: data } = await decodePng(srcPath);
@@ -6138,7 +7154,7 @@ async function prepEyeSplit(partsDir) {
6138
7154
  const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);
6139
7155
  const detached = detachedAboveWhite(data, W, H);
6140
7156
  const isDark = (i) => data[i + 3] > 0 && luma(data, i) < EYE_LASH_LUMA;
6141
- const isLight = (i) => data[i + 3] >= import_editor13.ALPHA_OPAQUE && luma(data, i) >= EYE_LASH_LUMA;
7157
+ const isLight = (i) => data[i + 3] >= import_editor14.ALPHA_OPAQUE && luma(data, i) >= EYE_LASH_LUMA;
6142
7158
  const isWarm = (i) => data[i] - data[i + 2] >= EYE_LID_WARMTH;
6143
7159
  const whiteTop = new Int32Array(W).fill(-1);
6144
7160
  for (let x = 0; x < W; x++) {
@@ -6201,7 +7217,7 @@ function hasTransparency(rgba) {
6201
7217
  return false;
6202
7218
  }
6203
7219
  async function prepLipSources(partsDir, mirrored) {
6204
- const has = (name) => import_node_fs7.default.existsSync(import_node_path10.default.join(partsDir, name));
7220
+ const has = (name) => import_node_fs8.default.existsSync(import_node_path10.default.join(partsDir, name));
6205
7221
  const keyed = has(KEYED_SRC);
6206
7222
  const interior = has(INTERIOR_SRC);
6207
7223
  if (keyed && !interior) {
@@ -6244,7 +7260,7 @@ async function composeLayersFromParts(input) {
6244
7260
  try {
6245
7261
  const outDir = resolveOutputDir(input.outDir);
6246
7262
  const partsDir = resolveInputDir(input.partsDir);
6247
- if (import_node_fs7.default.realpathSync(partsDir) === outDir) {
7263
+ if (import_node_fs8.default.realpathSync(partsDir) === outDir) {
6248
7264
  throw new AutoRigInputError(
6249
7265
  `partsDir and outDir resolve to the same directory (${outDir}): composing would overwrite the source parts`
6250
7266
  );
@@ -6308,7 +7324,7 @@ async function composeLayersFromParts(input) {
6308
7324
  lip_lower: split2.lower,
6309
7325
  lip_upper: split2.upper
6310
7326
  }[role];
6311
- if ((0, import_editor13.isLipInsideRole)(role) && !await hasCoverage(buf)) {
7327
+ if ((0, import_editor14.isLipInsideRole)(role) && !await hasCoverage(buf)) {
6312
7328
  skipped.push(role);
6313
7329
  continue;
6314
7330
  }
@@ -6323,7 +7339,7 @@ async function composeLayersFromParts(input) {
6323
7339
  }
6324
7340
  if (key === "arm_L" || key === "arm_R") {
6325
7341
  const arm = layout[key];
6326
- if (!import_node_fs7.default.existsSync(import_node_path10.default.join(partsDir, arm.src))) continue;
7342
+ if (!import_node_fs8.default.existsSync(import_node_path10.default.join(partsDir, arm.src))) continue;
6327
7343
  const body = placed.find((p) => p.role === "body");
6328
7344
  if (body === void 0) {
6329
7345
  throw new AutoRigInputError(
@@ -6366,7 +7382,7 @@ async function composeLayersFromParts(input) {
6366
7382
  }
6367
7383
  if (key === "forearm_pose_L" || key === "forearm_pose_R") {
6368
7384
  const pose = layout[key];
6369
- if (!import_node_fs7.default.existsSync(import_node_path10.default.join(partsDir, pose.src))) continue;
7385
+ if (!import_node_fs8.default.existsSync(import_node_path10.default.join(partsDir, pose.src))) continue;
6370
7386
  const armRole = key === "forearm_pose_L" ? "arm_L" : "arm_R";
6371
7387
  const arm = placed.find((p) => p.role === armRole);
6372
7388
  if (arm?.elbow === void 0 || arm.elbowRun === void 0) {
@@ -6483,11 +7499,11 @@ async function composeLayersFromParts(input) {
6483
7499
  );
6484
7500
  for (const role of ORDER) {
6485
7501
  if (placed.some((p) => p.role === role)) continue;
6486
- import_node_fs7.default.rmSync(import_node_path10.default.join(outDir, `${role}.png`), { force: true });
7502
+ import_node_fs8.default.rmSync(import_node_path10.default.join(outDir, `${role}.png`), { force: true });
6487
7503
  }
6488
7504
  const posed = (role) => role === "forearm_pose_L" || role === "forearm_pose_R";
6489
7505
  if (!placed.some((p) => posed(p.role))) {
6490
- import_node_fs7.default.rmSync(import_node_path10.default.join(outDir, "preview-pose.png"), { force: true });
7506
+ import_node_fs8.default.rmSync(import_node_path10.default.join(outDir, "preview-pose.png"), { force: true });
6491
7507
  }
6492
7508
  const layers = [];
6493
7509
  for (const { role, part, left, top } of placed) {
@@ -6503,7 +7519,7 @@ async function composeLayersFromParts(input) {
6503
7519
  });
6504
7520
  }
6505
7521
  const restInput = (role, buf) => {
6506
- if (role === "mouth_inner" || (0, import_editor13.isLipInsideRole)(role)) return null;
7522
+ if (role === "mouth_inner" || (0, import_editor14.isLipInsideRole)(role)) return null;
6507
7523
  if (closed === void 0) return buf;
6508
7524
  if (role === "lip_upper") return closed.upper;
6509
7525
  if (role === "lip_lower") return closed.lower;
@@ -6628,8 +7644,18 @@ function formatPatchReports(reports) {
6628
7644
  return `PATCH ${r.index} ${r.target} at ${at}: ${r.moved} of ${r.of} points (${where}), largest move ${r.maxPx} model px`;
6629
7645
  });
6630
7646
  }
7647
+ function formatCustomPartReports(parts) {
7648
+ return parts.map(
7649
+ (p) => `CUSTOM ${p.id}: box ${p.box.x},${p.box.y} ${p.box.w}x${p.box.h} px, mesh ${p.mesh.vertices} vertices ${p.mesh.triangles} triangles, order ${p.order}, atlas page ${p.page}`
7650
+ );
7651
+ }
7652
+ function formatBakeChecks(bakes) {
7653
+ return bakes.map(
7654
+ (b) => `BAKE ${b.part} ${b.param}: ${b.vertices} vertices, stops ${b.stops.join(",")}, error ${Math.round(b.errorPx * 1e3) / 1e3} px`
7655
+ );
7656
+ }
6631
7657
  function createIkiMcpServer() {
6632
- const server = new import_mcp.McpServer({ name: "iki", version: "0.33.0" });
7658
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.34.0" });
6633
7659
  server.registerTool(
6634
7660
  "validate_iki",
6635
7661
  {
@@ -6721,7 +7747,7 @@ function createIkiMcpServer() {
6721
7747
  server.registerTool(
6722
7748
  "auto_rig_from_layers",
6723
7749
  {
6724
- description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, hair_side_L/hair_side_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, a side lock needs hair_front, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given. The result's `folds` is the written rig's fold report, printed after the path the way render_poses prints it, and report-only: a fold never refuses the rig. The `RIGPLAN:` line (the result's `rigPlan`: `effective`, `clamped`, `overriddenBy`) follows the path and precedes the `PATCH` lines. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output \u2014 a spring's, or each chain segment's \u2014 reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. With side locks and a `nose` (which `turn` needs) the `HAIRSIDE` lines follow the `PHYSICS` lines (the result's `turn.hairSide`), each naming the lock's role, report-only as well. `patches` (see its field) adds displacements to existing keyform stops of the freshly generated rig; each op then prints one line between the path and the fold report \u2014 `PATCH <i> <target> at <Param=v \u2026>: <moved> of <of> points (cols a-b, rows c-d), largest move <maxPx> model px`, with `(vertices)` in place of the columns and rows for a mesh part \u2014 and the result's `patches` carries the same reports (`index`, `target`, `at`, `moved`, `of`, `cols`/`rows` for a grid, `maxPx`), present whenever `patches` was passed, `[]` included. An op the input schema accepts but the rig refuses comes back as `INVALID: patches[i]\u2026` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error.",
7750
+ description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, hair_side_L/hair_side_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, a side lock needs hair_front, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given. The result's `folds` is the written rig's fold report, printed after the path the way render_poses prints it, and report-only: a fold never refuses the rig. The `RIGPLAN:` line (the result's `rigPlan`: `effective`, `clamped`, `overriddenBy`) follows the path and precedes the `PATCH` lines. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output \u2014 a spring's, or each chain segment's \u2014 reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. With side locks and a `nose` (which `turn` needs) the `HAIRSIDE` lines follow the `PHYSICS` lines (the result's `turn.hairSide`), each naming the lock's role, report-only as well. `patches` (see its field) adds displacements to existing keyform stops of the freshly generated rig; each op then prints one line between the path and the fold report \u2014 `PATCH <i> <target> at <Param=v \u2026>: <moved> of <of> points (cols a-b, rows c-d), largest move <maxPx> model px`, with `(vertices)` in place of the columns and rows for a mesh part \u2014 and the result's `patches` carries the same reports (`index`, `target`, `at`, `moved`, `of`, `cols`/`rows` for a grid, `maxPx`), present whenever `patches` was passed, `[]` included. An op the input schema accepts but the rig refuses comes back as `INVALID: patches[i]\u2026` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error. `customParts` adds parts the rig has no role for (a twin tail, a hairpin), each from a canvas-sized PNG of its own, as an unrigged mesh on `headDeformer` after its `after` role's parts; it needs @ikijs/mcp 0.34.0, and an older server drops the field and returns no `customParts`. The result's `customParts` (`parts`: `id`, rest `box`, `mesh`, `order`, atlas `page`) is present whenever the input was passed, `[]` included, and one `CUSTOM <id>: \u2026` line per part follows the `HAIRSIDE` lines. `bakes` (see its field) moves the custom parts with a parameter and needs `customParts`; each part and parameter it moves then prints one `BAKE <part> <param>: <n> vertices, stops <values>, error <px> px` line after the `CUSTOM` lines (the result's `customParts.bakes`: `part`, `param`, `vertices`, `stops`, `errorPx`), the written model having been landed through the engine, and a stop off by 0.1 px or more comes back as `INVALID: BAKE ERROR <part> <param>=<value>: \u2026`, and a part the bake moves at rest as `INVALID: BAKE ERROR <part> at rest: \u2026`, with nothing written (the rig and the engine disagree: report it as a bug in the packages). Whenever `customParts` was passed, the written model is also measured per custom part (the result's `customParts.gate`: `ok`, `limits`, `parts`, `failed`) and the text ends with its lines, `CUSTOM <id> FOLDS|TIE|SLIDE|EXPOSED|RIGID|TIP: \u2026` then `CUSTOM GATE pass` or `CUSTOM GATE FAIL: <part LINE, \u2026>`, always the last line: a part's least triangle area ratio, its tie's displacement against the anchor where the head does not turn and where it does, the hidden art showing, how far a rigid part bends and where its free end lands, each in px and face widths with its worst pose; `TIP` never fails the gate and the other lines do. The model is written either way; from 0.34.0 on `customParts` always carries `gate` (a gate that throws still writes the file and ends the text `CUSTOM GATE FAIL: gate error: <message>`), so a result without `customParts` is from an older server and was never gated. The custom layers are not role layers: they are left out of the head's width and turn measurements, and an empty or wrong-size one, or an entry the rig refuses, comes back as `INVALID: customParts[i]\u2026` with nothing written. A missing field or one of the wrong type (a `tie` that is not two numbers, say) is refused by the schema itself, as the SDK's input validation error.",
6725
7751
  inputSchema: {
6726
7752
  layers: import_zod.z.array(
6727
7753
  import_zod.z.object({
@@ -6744,7 +7770,7 @@ function createIkiMcpServer() {
6744
7770
  noseShift: import_zod.z.number().optional(),
6745
7771
  mouthShift: import_zod.z.number().optional()
6746
7772
  }).passthrough().optional().describe(
6747
- "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 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). A passed `silhouetteRatio` is clamped too, only on a face drawn without hair and with ear islands, where narrowing the head that far would no longer cover the far ear's slide. Any other passed target this layer set cannot reach comes back as `INVALID: \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."
7773
+ "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 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). A passed `silhouetteRatio` is clamped too, only on a face drawn without hair and with ear islands, where narrowing the head that far would no longer cover the far ear's slide. Any other passed target this layer set cannot reach comes back as `INVALID: \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. A pair that shows a custom part crossing the eye row reads a wider head than the rig fits to, since the rig measures the role layers alone: measure a pair drawn without the custom parts."
6748
7774
  ),
6749
7775
  style: import_zod.z.unknown().optional().describe(
6750
7776
  "Removed in @ikijs/mcp 0.30.0: pass `rigPlan`. Any value here is refused with the field map."
@@ -6765,6 +7791,63 @@ function createIkiMcpServer() {
6765
7791
  }).passthrough().optional().describe(
6766
7792
  "Per-character tuning from the profile the rig defaults to, in three groups: `turn` (`amount`, `featureLead`, `eyeForeshorten`, `noseLead`: the last two turn only, the nod untouched, and fitted by `turnTargets.farEyeRatio` / `turnTargets.noseShift` when those are given, which the `RIGPLAN:` line then reports as overridden), `hair` (`follow`, `outlineFollow`, `sway`) and `eyes` (`blink`). `describe_rig_plan` lists every field's default, range, recommended span, step and poses. A value out of range, or a group or key not named there, comes back as `INVALID: rigPlan.<path> \u2026`; an object left out or `{}` is the profile. The result reports what the rig built with as `rigPlan` and a `RIGPLAN:` line."
6767
7793
  ),
7794
+ customParts: import_zod.z.array(
7795
+ import_zod.z.object({
7796
+ id: import_zod.z.string().describe(
7797
+ "The part's id: a plain identifier, not a role's name or a part id."
7798
+ ),
7799
+ path: import_zod.z.string().describe(
7800
+ "The part's own PNG, the same size as the role layers (resolved against cwd), drawn alone and whole on a transparent ground."
7801
+ ),
7802
+ anchor: import_zod.z.string().describe("The role whose layer the part is fixed against."),
7803
+ tie: import_zod.z.array(import_zod.z.number()).length(2).describe(
7804
+ "[x, y] in canvas px where the part meets the anchor: inside both the part's alpha box and the anchor layer's."
7805
+ ),
7806
+ after: import_zod.z.string().describe(
7807
+ "A role of the set: the part is drawn right after that role's last part."
7808
+ ),
7809
+ deformer: import_zod.z.string().optional().describe(
7810
+ "The matrix deformer it hangs on; only `headDeformer` (the default) is accepted."
7811
+ ),
7812
+ rigid: import_zod.z.boolean().optional().describe(
7813
+ "The art does not bend (a hairpin, a ribbon): a bake that bends it by more than 0.0025 face widths at a stop, from its best-fit rotation and translation, is refused as `INVALID: bakes\u2026` with nothing written. Give a rigid part one displacement for every control point, or a rotation."
7814
+ )
7815
+ }).passthrough()
7816
+ ).optional().describe(
7817
+ "Parts the auto-rigger has no role for, each `{ id, path, anchor, tie, after, deformer?, rigid? }`. A custom layer is read apart from `layers`: never role-parsed or measured, so its name is free and it does not widen the head the turn is fitted to; it counts toward the layer and pixel limits. All custom parts share one extra atlas page, the last, quantized on a palette of its own, so the other pages keep their bytes. An entry the rig refuses (an unknown key, a bad tie) comes back as `INVALID: customParts[i]\u2026` with nothing written; a missing field or one of the wrong type (a `tie` that is not two numbers, say) is refused by the schema itself, as the SDK's input validation error. `[]` is the same rig as leaving the field out, plus an empty `customParts` in the result."
7818
+ ),
7819
+ bakes: import_zod.z.object({
7820
+ targets: import_zod.z.array(
7821
+ import_zod.z.object({
7822
+ id: import_zod.z.string().optional(),
7823
+ param: import_zod.z.string(),
7824
+ parts: import_zod.z.array(import_zod.z.string()),
7825
+ box: import_zod.z.object({
7826
+ x: import_zod.z.number(),
7827
+ y: import_zod.z.number(),
7828
+ w: import_zod.z.number(),
7829
+ h: import_zod.z.number()
7830
+ }).passthrough().optional(),
7831
+ grid: import_zod.z.object({ cols: import_zod.z.number(), rows: import_zod.z.number() }).passthrough(),
7832
+ stops: import_zod.z.record(
7833
+ import_zod.z.string(),
7834
+ import_zod.z.array(import_zod.z.array(import_zod.z.number()).length(2))
7835
+ ),
7836
+ mirror: import_zod.z.boolean().optional(),
7837
+ why: import_zod.z.string().optional()
7838
+ }).passthrough()
7839
+ ),
7840
+ meshes: import_zod.z.record(
7841
+ import_zod.z.string(),
7842
+ import_zod.z.object({
7843
+ rows: import_zod.z.array(import_zod.z.number()).optional(),
7844
+ cols: import_zod.z.number().optional(),
7845
+ cellPx: import_zod.z.number().optional()
7846
+ }).passthrough()
7847
+ ).optional()
7848
+ }).passthrough().optional().describe(
7849
+ "Lattices that move the CUSTOM parts when a parameter does, which an unrigged custom part otherwise does not: `{ targets, meshes? }`; it needs `customParts` and names no other part. A target `{ id?, param, parts, box?, grid: { cols, rows }, stops, mirror?, why? }` is `(cols + 1) x (rows + 1)` control points laid evenly over `box` (canvas px; absent, the union of the parts' rest boxes grown by 2 px), listed row-major from the top-left; `stops` is `{ \"<value>\": [[dx, dy], \u2026 one per control point] }`. FRAME: every position and displacement is in canvas px, origin top-left, x right, y DOWN, the frame of the layer PNGs and of `describe_iki`'s boxes and `probe_rig`. A STOP is the part's TOTAL landed displacement from rest when `param` alone is at that value and every other parameter is at its default: the head's own carry is inside it, so a neighbour's displacement as `probe_rig` measures it is written as it is. Stop keys are values of `param` inside its range, never its default (rest is implicit). The landing is exact at rest, at each stop and at one end key at the range end on a side whose outermost stop is inside the range (it holds that stop's displacement); a side with no stop is not moved by the target. Between keys the offsets blend linearly, so under the head's roll (ParamAngleZ) the path bows off the line, about 1 px midway over 15\xB0: put a stop where the path matters. Each vertex takes the bilinear value of the lattice at its REST position, and a vertex outside `box` takes the nearest edge's value. `mirror: true` fills a missing stop from the one at the value mirrored about the rest value, when that value is inside the parameter's range: the lattice reflected about the box's vertical centre line, `dx` negated; a stop you wrote is never overwritten. Targets that name the same part and parameter SUM; a part in targets on two parameters gets one warp per parameter, and the two add in the head's frame, so under a roll a sway tilts with the head. `meshes` re-meshes a custom part before the bake, `{ <id>: { rows: [canvas-px y, \u2026], cols } }` (the first row at the part's top and the last at its bottom, within 0.5 px) or `{ <id>: { cellPx } }`; the rest picture is unchanged. The written model is then landed through the engine at every stop and at the range end each side holds its outermost stop to, and refused when one is off by 0.1 px or more. An input the rig refuses comes back as `INVALID: bakes\u2026` (`bakes.targets[2].stops[\"30\"][7]\u2026`) and nothing is written; a field of the wrong type is refused by the schema itself, as the SDK's input validation error. A bake is measured on one rig: after a retune of the layout or `rigPlan`, a regenerated anchor, a changed custom layer or an accepted patch batch, measure the stops again."
7850
+ ),
6768
7851
  patches: import_zod.z.array(
6769
7852
  import_zod.z.object({
6770
7853
  target: import_zod.z.string(),
@@ -6791,7 +7874,11 @@ function createIkiMcpServer() {
6791
7874
  ...args,
6792
7875
  // `.length(2)` makes each region span a pair, which its inferred
6793
7876
  // `number[]` cannot say.
6794
- patches: args.patches
7877
+ patches: args.patches,
7878
+ customParts: args.customParts,
7879
+ // Each stop's `.length(2)` makes it a pair, which its inferred
7880
+ // `number[]` cannot say.
7881
+ bakes: args.bakes
6795
7882
  });
6796
7883
  const text = r.ok ? [
6797
7884
  r.path,
@@ -6799,7 +7886,10 @@ function createIkiMcpServer() {
6799
7886
  ...formatPatchReports(r.patches ?? []),
6800
7887
  ...formatFoldReport(r.folds, r.canvas),
6801
7888
  ...formatPhysicsReport(r.physics),
6802
- ...formatHairSideReport(r.turn?.hairSide, r.canvas)
7889
+ ...formatHairSideReport(r.turn?.hairSide, r.canvas),
7890
+ ...formatCustomPartReports(r.customParts?.parts ?? []),
7891
+ ...formatBakeChecks(r.customParts?.bakes ?? []),
7892
+ ...r.customParts ? formatCustomGate(r.customParts.gate) : []
6803
7893
  ].join("\n") : `INVALID: ${r.error}`;
6804
7894
  return { content: [{ type: "text", text }], structuredContent: r };
6805
7895
  } catch (err) {
@@ -6891,7 +7981,7 @@ function createIkiMcpServer() {
6891
7981
  server.registerTool(
6892
7982
  "measure_turn_reference",
6893
7983
  {
6894
- description: "Measures how far a head turns between two images of the same character \u2014 a front view and a turned one, at the SAME scale \u2014 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.",
7984
+ description: "Measures how far a head turns between two images of the same character \u2014 a front view and a turned one, at the SAME scale \u2014 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. A pair that shows a custom part crossing the eye row reads a wider head than the rig fits to, so measure a pair drawn without the custom parts.",
6895
7985
  inputSchema: {
6896
7986
  front: import_zod.z.string().describe("Front-facing PNG file path (resolved against cwd)."),
6897
7987
  turned: import_zod.z.string().describe("The same character turned, as a PNG file path."),
@@ -6974,7 +8064,10 @@ function createIkiMcpServer() {
6974
8064
  }).optional()
6975
8065
  })
6976
8066
  ).optional().describe(
6977
- "More sweeps rendered after `sweep`, each `{ name, preset, crop? }` into its own `<outDir>/<name>/` (files and `crop` as `sweep`'s). Names are distinct from `sweep`'s and from each other's ignoring case, and presets are distinct (at most one of each). `turn` is `sweep`'s. `turn-nod` is the box (0,0) -> (0,-30) -> (-30,-30) -> (-30,+30) -> (+30,+30) -> (+30,-30) -> (0,-30) -> (0,0) of `ParamAngleX` x `ParamAngleY`, each leg eased, 6 s, 180 frames; its `sheet.png` is a 3 x 3 grid BY ANGLE (columns AngleX -30/0/+30, rows AngleY +30/0/-30, rest in the centre, cells labelled X, Y and t) and it has no kymograph. `manifest.json` is version 2 (`parameters`, and per frame `t` and `values`). A sweep dir's earlier frames, sheet, kymograph, manifest and flipbook are cleared first. An empty list, a repeated name or preset, or a bad crop comes back as `INVALID: sweeps...`. A server before 0.32.0 strips `sweeps` and renders the rest. The `SWEEP nod` lines (the eye-pair and iris-pair gap range and the mouth width range along the nod at each turn, in face widths) and `SWEEP corner` lines (the additivity residual per landmark at the four corners, the rest term included; 0 on an additive rig) print once per call whenever `sweep` or `sweeps` was asked for, report-only like `FOLD` and `PHYSICS`."
8067
+ "More sweeps rendered after `sweep`, each `{ name, preset, crop? }` into its own `<outDir>/<name>/` (files and `crop` as `sweep`'s). Names are distinct from `sweep`'s and from each other's ignoring case, and presets are distinct (at most one of each). `turn` is `sweep`'s. `roll` is the same eased curve on `ParamAngleZ` (0 to -30 to +30 to 0 over 3 s, 90 frames, physics running, idle off); its `sheet.png` is the nine frames nearest the turn sheet's angles on the -30 to +30 leg, labelled with the angle (Z) and time, and it has no kymograph (the eye row moves with the roll). `turn-nod` is the box (0,0) -> (0,-30) -> (-30,-30) -> (-30,+30) -> (+30,+30) -> (+30,-30) -> (0,-30) -> (0,0) of `ParamAngleX` x `ParamAngleY`, each leg eased, 6 s, 180 frames; its `sheet.png` is a 3 x 3 grid BY ANGLE (columns AngleX -30/0/+30, rows AngleY +30/0/-30, rest in the centre, cells labelled X, Y and t) and it has no kymograph. `manifest.json` is version 2 (`parameters`, and per frame `t` and `values`). A sweep dir's earlier frames, sheet, kymograph, manifest and flipbook are cleared first. An empty list, a repeated name or preset, or a bad crop comes back as `INVALID: sweeps...`. A server before 0.32.0 strips `sweeps` and renders the rest. The `SWEEP nod` lines (the eye-pair and iris-pair gap range and the mouth width range along the nod at each turn, in face widths) and `SWEEP corner` lines (the additivity residual per landmark at the four corners, the rest term included; 0 on an additive rig) print once per call whenever `sweep` or `sweeps` was asked for, report-only like `FOLD` and `PHYSICS`. A `roll` adds no `SWEEP` line of its own and changes none: they are read from the model. `roll` needs @ikijs/mcp 0.34.0; an older server refuses it as an input validation error."
8068
+ ),
8069
+ hideParts: import_zod.z.array(import_zod.z.string()).optional().describe(
8070
+ "Part ids left out of the drawn frames (poses and sweeps); the fold, physics and sweep reports still read the whole model. Use it to render a character without its custom parts, so `measure_turn_reference` reads the rig's own head (a custom part crossing the eye row widens the head it measures, as it does on a drawn reference). An id the model lacks, or one that is the clip mask of a part that stays, comes back as `INVALID: hideParts[i] \u2026` and nothing is rendered. Needs @ikijs/mcp 0.34.0; an older server drops the field and draws every part."
6978
8071
  )
6979
8072
  }
6980
8073
  },
@@ -7010,6 +8103,54 @@ function createIkiMcpServer() {
7010
8103
  }
7011
8104
  }
7012
8105
  );
8106
+ server.registerTool(
8107
+ "probe_rig",
8108
+ {
8109
+ description: "Measures a rigged .iki without rendering it, through the engine's own landing. Each query is one of: `paint` (the opaque runs, alpha 128 and over, of a layer PNG, per canvas row, as `{ y0, rows }` with `[x0, x1)` runs; read from the PNG you give, not the atlas, so a quantized model reads the same, and the PNG must be the model's canvas size), `land` (where each canvas-px point of a part lands in a pose) or `displacement` (the landing minus the point). The frame is canvas px, origin top-left, x right, y down \u2014 the frame of the layer PNGs and describe_iki's boxes. A point is `[x, y]` and must lie on the part at rest, inside one of its mesh triangles (a part without a mesh, its unit quad); its landing is then found by barycentric interpolation inside that triangle. A point outside the part's mesh comes back as `null`, never an extrapolation. `pose` is parameter settings: every parameter it does not name is at its default, a value outside the parameter's range is clamped as the player does, and an id the model does not declare or a non-finite value is refused. The text is the results as JSON, one entry per query in order. With `outputPath` (a `.probe.json` under the working directory, its folder existing) the results are written there as the same JSON and the text is the path and one line per query, so a part's paint stays out of your context for a rigging program to read. A query's refusal comes back as `INVALID: queries[i].<field> \u2026`, any refusal writes nothing.",
8110
+ inputSchema: {
8111
+ modelPath: import_zod.z.string().describe(
8112
+ "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
8113
+ ),
8114
+ queries: import_zod.z.array(
8115
+ import_zod.z.discriminatedUnion("op", [
8116
+ import_zod.z.object({
8117
+ op: import_zod.z.literal("paint"),
8118
+ path: import_zod.z.string().describe(
8119
+ "Canvas-sized layer PNG (resolved against cwd), the drawing the part was built from."
8120
+ )
8121
+ }),
8122
+ import_zod.z.object({
8123
+ op: import_zod.z.enum(["land", "displacement"]),
8124
+ part: import_zod.z.string().describe("A part id of the model."),
8125
+ points: import_zod.z.array(import_zod.z.array(import_zod.z.number()).length(2)).describe(
8126
+ "Canvas-px points `[x, y]`, at most 5000, each on the part at rest."
8127
+ ),
8128
+ pose: import_zod.z.record(import_zod.z.string(), import_zod.z.number()).optional().describe(
8129
+ "Parameter id to value; the others stay at their defaults."
8130
+ )
8131
+ })
8132
+ ])
8133
+ ).describe("The queries, answered in order; at most 64 per call."),
8134
+ outputPath: import_zod.z.string().optional().describe(
8135
+ "A path ending in `.probe.json` (resolved against cwd, under it; its folder must exist) to write the results to."
8136
+ )
8137
+ }
8138
+ },
8139
+ async (args) => {
8140
+ try {
8141
+ const r = await probeRig(args);
8142
+ const text = !r.ok ? `INVALID: ${r.error}` : "results" in r ? JSON.stringify(r.results) : [r.outputPath, ...r.lines].join("\n");
8143
+ return { content: [{ type: "text", text }], structuredContent: r };
8144
+ } catch (err) {
8145
+ const error = err instanceof Error ? err.message : String(err);
8146
+ return {
8147
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
8148
+ structuredContent: { ok: false, error },
8149
+ isError: true
8150
+ };
8151
+ }
8152
+ }
8153
+ );
7013
8154
  return server;
7014
8155
  }
7015
8156