pixelkiln 0.147.0 → 0.148.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -73,14 +73,13 @@ function proTierCost(width, height) {
73
73
  if (px <= 102400) return PRO_TIER_PRICES[1];
74
74
  return PRO_TIER_PRICES[2];
75
75
  }
76
+ var PIXMINIMAX_STEPS = [1, 1, 2, 2, 3, 3, 4, 5, 5, 6];
76
77
  function pixMiniMaxCost(width, height, frames, enhancePrompt = false) {
77
- const f = width * height * Math.max(1, frames) / 4096;
78
- let units;
79
- if (f <= 8) units = 1;
80
- else if (f <= 16) units = 1 + (f - 8) / 8;
81
- else if (f <= 40) units = 2 + (f - 16) / 6;
82
- else units = 6 + (f - 40) / 6;
83
- const base = Math.max(1, Math.ceil(units - 1e-9));
78
+ const side = Math.max(1, width, height);
79
+ const upscaled = side * (side <= 64 ? 4 : side <= 128 ? 2 : 1);
80
+ const reference = Math.max(1, frames) * upscaled * upscaled / 65536;
81
+ const step = Math.max(1, Math.ceil(reference / 4 - 1e-9));
82
+ const base = PIXMINIMAX_STEPS[Math.min(step, PIXMINIMAX_STEPS.length) - 1];
84
83
  return enhancePrompt ? base + 0.05 : base;
85
84
  }
86
85
  function tilesCost(tileSize, variations) {
@@ -175,7 +174,7 @@ var CharacterProportionsSchema = z.union([
175
174
  hipWidth: z.number().min(0.5).max(2).optional()
176
175
  }).strict()
177
176
  ]);
178
- var CharacterAnimationModeSchema = z.enum(["template", "skeleton-v3", "v3", "pro"]);
177
+ var CharacterAnimationModeSchema = z.enum(["template", "skeleton-v3", "v3", "pixminimax", "pro"]);
179
178
  var UiPieceSchema = z.discriminatedUnion("kind", [
180
179
  z.object({
181
180
  id: z.string().min(1),
@@ -499,12 +498,13 @@ var CharacterAnimationSchema = z.object({
499
498
  motionFrom: z.string().min(1).optional(),
500
499
  /**
501
500
  * Frames to generate without a template. A v3 loop takes an even 4 to 16;
502
- * a sentence loop (`mode: "skeleton-v3"` with no `template`) takes 3 to 15.
501
+ * a pixminimax loop a multiple of 4 from 4 to 40; a sentence loop
502
+ * (`mode: "skeleton-v3"` with no `template`) takes 3 to 15.
503
503
  */
504
- frames: z.number().int().min(3).max(16).optional(),
504
+ frames: z.number().int().min(3).max(40).optional(),
505
505
  /** Playback rate recorded with the frames; PixelLab does not store one. */
506
506
  fps: z.number().int().min(1).max(60).default(8),
507
- /** v3 only: keep the resting pose as frame 0, so `frames` generated frames land as `frames + 1` files. */
507
+ /** v3 and pixminimax: keep the resting pose as frame 0, so `frames` generated frames land as `frames + 1` files. */
508
508
  keepFirstFrame: z.boolean().default(true),
509
509
  /**
510
510
  * `character` loops: strip the ghost pixels an animation model leaves
@@ -518,28 +518,41 @@ var CharacterAnimationSchema = z.object({
518
518
  * `template` when a template is named, otherwise `v3`; `skeleton-v3`
519
519
  * poses a template with PixelLab's skeleton model instead, or, with no
520
520
  * template, animates the asset's prompt as a sentence written into one 3D
521
- * motion (a v3 base; 3-15 `frames`); `pro` for the sequential
522
- * high-quality engine.
521
+ * motion (a v3 base; 3-15 `frames`); `pixminimax` draws from the
522
+ * prompt on PixelLab's PixMiniMax engine (4 to 40 `frames`, a multiple
523
+ * of 4); `pro` for the sequential high-quality engine.
523
524
  */
524
525
  mode: CharacterAnimationModeSchema.optional(),
525
526
  /**
526
- * v3 only: a manifest-relative image of the pose to start from, instead
527
- * of the character's rotation for this direction. Up to 256px.
527
+ * v3 and pixminimax: a manifest-relative image of the pose to start from,
528
+ * instead of the character's rotation for this direction. Up to 256px.
528
529
  */
529
530
  startFrame: z.string().min(1).optional(),
530
531
  /**
531
- * v3 only: a pose to animate toward. The loop then interpolates from the
532
- * start frame (the rotation, or `startFrame`) to this image, which must
533
- * be the same size as the start frame.
532
+ * v3 and pixminimax: a pose to animate toward. The loop then interpolates
533
+ * from the start frame (the rotation, or `startFrame`) to this image,
534
+ * which must be the same size as the start frame. The same image as
535
+ * `startFrame` closes a loop.
534
536
  */
535
537
  endFrame: z.string().min(1).optional(),
536
- /** What is being animated, when the character's own description would mislead the model. */
538
+ /**
539
+ * What is being animated, when the character's own description would
540
+ * mislead the model. On a pixminimax loop it is PixelLab's
541
+ * `subject_description`, one noun phrase of up to 300 characters; left
542
+ * out, PixelLab reads it off the start frame.
543
+ */
537
544
  subject: z.string().min(1).optional(),
545
+ /**
546
+ * pixminimax only: the pose the start frame shows, up to 300 characters
547
+ * ("standing beside the pole, one hand on it"). Left out, PixelLab reads
548
+ * it off the image.
549
+ */
550
+ initialPose: z.string().min(1).max(300).optional(),
538
551
  /** Template mode only: style hints for this loop, over the character's own. */
539
552
  outline: z.string().min(1).optional(),
540
553
  shading: z.string().min(1).optional(),
541
554
  detail: z.string().min(1).optional(),
542
- /** v3 text loops only: let PixelLab expand the action into a fuller motion description first. */
555
+ /** v3 and pixminimax text loops only: let PixelLab expand the action into a fuller motion description first. */
543
556
  enhancePrompt: z.boolean().optional()
544
557
  }).strict().superRefine((animation, context) => {
545
558
  if (animation.directions !== void 0) {
@@ -550,22 +563,29 @@ var CharacterAnimationSchema = z.object({
550
563
  });
551
564
  }
552
565
  const sentence = animation.mode === "skeleton-v3" && !animation.template;
553
- if (animation.frames !== void 0 && !sentence && animation.mode !== "pro") {
566
+ const pixminimax = animation.mode === "pixminimax";
567
+ if (animation.frames !== void 0 && pixminimax) {
568
+ if (animation.frames % 4 !== 0 || animation.frames < 4) {
569
+ context.addIssue({ code: z.ZodIssueCode.custom, message: "a pixminimax loop takes a multiple of 4 frames, 4 to 40", path: ["frames"] });
570
+ }
571
+ } else if (animation.frames !== void 0 && !sentence && animation.mode !== "pro") {
554
572
  if (animation.frames % 2 !== 0) {
555
573
  context.addIssue({ code: z.ZodIssueCode.custom, message: "frames must be even", path: ["frames"] });
556
- } else if (animation.frames < 4) {
557
- context.addIssue({ code: z.ZodIssueCode.custom, message: "frames must be 4 to 16", path: ["frames"] });
574
+ } else if (animation.frames < 4 || animation.frames > 16) {
575
+ context.addIssue({ code: z.ZodIssueCode.custom, message: "frames must be 4 to 16 (a pixminimax loop takes up to 40)", path: ["frames"] });
558
576
  }
577
+ } else if (animation.frames !== void 0 && animation.mode === "pro" && animation.frames > 16) {
578
+ context.addIssue({ code: z.ZodIssueCode.custom, message: "frames must be 16 or fewer", path: ["frames"] });
559
579
  }
560
580
  if (animation.frames !== void 0 && sentence && animation.frames > 15) {
561
581
  context.addIssue({ code: z.ZodIssueCode.custom, message: "a skeleton-v3 loop from a sentence takes 3 to 15 frames", path: ["frames"] });
562
582
  }
563
583
  const mode2 = animation.mode ?? (animation.template ? "template" : "v3");
564
584
  for (const key3 of ["startFrame", "endFrame", "enhancePrompt"]) {
565
- if (animation[key3] !== void 0 && mode2 !== "v3") {
585
+ if (animation[key3] !== void 0 && mode2 !== "v3" && mode2 !== "pixminimax") {
566
586
  context.addIssue({
567
587
  code: z.ZodIssueCode.custom,
568
- message: `${key3} is for v3 loops; a ${mode2} loop ${mode2 === "template" || mode2 === "skeleton-v3" ? `starts from the character's rotation and ${animation.template ? "follows its template" : "animates its sentence"}` : "takes neither"}`,
588
+ message: `${key3} is for v3 and pixminimax loops; a ${mode2} loop ${mode2 === "template" || mode2 === "skeleton-v3" ? `starts from the character's rotation and ${animation.template ? "follows its template" : "animates its sentence"}` : "takes neither"}`,
569
589
  path: [key3]
570
590
  });
571
591
  }
@@ -575,6 +595,12 @@ var CharacterAnimationSchema = z.object({
575
595
  context.addIssue({ code: z.ZodIssueCode.custom, message: `${key3} overrides apply to template loops only`, path: [key3] });
576
596
  }
577
597
  }
598
+ if (animation.initialPose !== void 0 && mode2 !== "pixminimax") {
599
+ context.addIssue({ code: z.ZodIssueCode.custom, message: `initialPose is for pixminimax loops; PixelLab's ${mode2} engine takes no pose caption`, path: ["initialPose"] });
600
+ }
601
+ if (pixminimax && animation.subject !== void 0 && animation.subject.length > 300) {
602
+ context.addIssue({ code: z.ZodIssueCode.custom, message: "a pixminimax loop's subject is one noun phrase of up to 300 characters", path: ["subject"] });
603
+ }
578
604
  if (animation.template && animation.mode && animation.mode !== "template" && animation.mode !== "skeleton-v3") {
579
605
  context.addIssue({
580
606
  code: z.ZodIssueCode.custom,
@@ -3687,8 +3713,11 @@ var PixelLabClient = class {
3687
3713
  * One animation of one character. Template mode costs a generation per
3688
3714
  * direction and fixes the frame count; skeleton-v3 poses the same template
3689
3715
  * with the skeleton video model (2-4 generations per direction); v3 draws
3690
- * `frameCount` frames from the action text; pro is the sequential engine.
3691
- * One job per direction.
3716
+ * `frameCount` frames from the action text; pixminimax does the same on
3717
+ * PixelLab's PixMiniMax engine (a multiple of 4 frames up to 40, the same
3718
+ * start/end frames, `keep_first_frame` and `enhance_prompt`, plus its own
3719
+ * `subject_description` and `initial_pose` captions); pro is the
3720
+ * sequential engine. One job per direction.
3692
3721
  *
3693
3722
  * Every mode but skeleton-v3 goes to `/animate-character`, the path whose
3694
3723
  * shapes were measured live. skeleton-v3 is documented only on
@@ -3704,6 +3733,7 @@ var PixelLabClient = class {
3704
3733
  async animateCharacter(args) {
3705
3734
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
3706
3735
  const endpoint = args.mode === "skeleton-v3" ? "/characters/animations" : "/animate-character";
3736
+ const custom = args.mode === "v3" || args.mode === "pixminimax";
3707
3737
  const raw = await this.request(endpoint, {
3708
3738
  method: "POST",
3709
3739
  body: JSON.stringify({
@@ -3715,12 +3745,14 @@ var PixelLabClient = class {
3715
3745
  ...args.template ? { template_animation_id: args.template } : {},
3716
3746
  ...args.actionDescription ? { action_description: args.actionDescription } : {},
3717
3747
  ...args.description ? { description: args.description } : {},
3718
- // A template fixes its own frame count; v3 and a skeleton-v3 sentence take one.
3719
- ...(args.mode === "v3" || args.mode === "skeleton-v3" && !args.template) && args.frameCount ? { frame_count: args.frameCount } : {},
3720
- ...args.mode === "v3" && args.keepFirstFrame === false ? { keep_first_frame: false } : {},
3721
- ...args.mode === "v3" && args.startFrame ? { custom_start_frame: encode(args.startFrame) } : {},
3722
- ...args.mode === "v3" && args.endFrame ? { end_frame: encode(args.endFrame) } : {},
3723
- ...args.mode === "v3" && args.enhancePrompt ? { enhance_prompt: true } : {},
3748
+ // A template fixes its own frame count; v3, pixminimax and a skeleton-v3 sentence take one.
3749
+ ...(custom || args.mode === "skeleton-v3" && !args.template) && args.frameCount ? { frame_count: args.frameCount } : {},
3750
+ ...custom && args.keepFirstFrame === false ? { keep_first_frame: false } : {},
3751
+ ...custom && args.startFrame ? { custom_start_frame: encode(args.startFrame) } : {},
3752
+ ...custom && args.endFrame ? { end_frame: encode(args.endFrame) } : {},
3753
+ ...custom && args.enhancePrompt ? { enhance_prompt: true } : {},
3754
+ ...args.mode === "pixminimax" && args.subjectDescription ? { subject_description: args.subjectDescription } : {},
3755
+ ...args.mode === "pixminimax" && args.initialPose ? { initial_pose: args.initialPose } : {},
3724
3756
  ...args.mode === "template" && args.textGuidanceScale !== void 0 ? { text_guidance_scale: args.textGuidanceScale } : {},
3725
3757
  ...args.mode === "template" && args.outline ? { outline: args.outline } : {},
3726
3758
  ...args.mode === "template" && args.shading ? { shading: args.shading } : {},
@@ -6823,10 +6855,10 @@ function despeckle(png, options) {
6823
6855
  for (const still of options.reference) {
6824
6856
  const { pixels } = decodePng(still);
6825
6857
  for (let i = 0; i < pixels.length; i += 4) {
6826
- if (pixels[i + 3] === 0 || outline(pixels, i)) continue;
6858
+ if (pixels[i + 3] === 0) continue;
6827
6859
  const rgb = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
6828
6860
  palette.set(rgb, (palette.get(rgb) ?? 0) + 1);
6829
- total++;
6861
+ if (!outline(pixels, i)) total++;
6830
6862
  }
6831
6863
  }
6832
6864
  if (!total) throw new Error("the reference stills have no opaque pixels that are not outline");
@@ -6886,7 +6918,7 @@ function despeckle(png, options) {
6886
6918
  const strange = run.filter(([x, y]) => foreign(at(image, x, y))).length / run.length > 0.5;
6887
6919
  let debris;
6888
6920
  const exposed = run.some(([x, y]) => STEPS.some(([dx, dy]) => open(x + dx, y + dy)));
6889
- if (strange && !exposed && run.length > limb) {
6921
+ if (strange && run.length > limb) {
6890
6922
  debris = false;
6891
6923
  limbs.add(index);
6892
6924
  } else if (exposed) {
@@ -6921,6 +6953,7 @@ function despeckle(png, options) {
6921
6953
  if (src[at(image, x, y) + 3] > 0 && out[at(image, x, y) + 3] === 0) frontier.push([x, y]);
6922
6954
  }
6923
6955
  }
6956
+ const seeds = frontier.length;
6924
6957
  for (let n = 0; n < frontier.length; n++) {
6925
6958
  const [fx, fy] = frontier[n];
6926
6959
  for (let dy = -1; dy <= 1; dy++) {
@@ -6944,6 +6977,31 @@ function despeckle(png, options) {
6944
6977
  }
6945
6978
  }
6946
6979
  }
6980
+ const chained = new Set(frontier.slice(seeds).map(([x, y]) => local(x, y)));
6981
+ const visited = /* @__PURE__ */ new Set();
6982
+ for (const [sx, sy] of frontier.slice(seeds)) {
6983
+ if (visited.has(local(sx, sy))) continue;
6984
+ const group = [[sx, sy]];
6985
+ visited.add(local(sx, sy));
6986
+ for (let n = 0; n < group.length; n++) {
6987
+ const [gx, gy] = group[n];
6988
+ for (let dy = -1; dy <= 1; dy++) {
6989
+ for (let dx = -1; dx <= 1; dx++) {
6990
+ const x = gx + dx;
6991
+ const y = gy + dy;
6992
+ if (!inside(cell, x, y) || visited.has(local(x, y)) || !chained.has(local(x, y))) continue;
6993
+ visited.add(local(x, y));
6994
+ group.push([x, y]);
6995
+ }
6996
+ }
6997
+ }
6998
+ if (group.length <= limb) continue;
6999
+ for (const [x, y] of group) {
7000
+ const i = at(image, x, y);
7001
+ src.copy(out, i, i, i + 4);
7002
+ removed--;
7003
+ }
7004
+ }
6947
7005
  }
6948
7006
  return { png: encodeRgbaPng(image.width, image.height, out), removed };
6949
7007
  }
@@ -7747,10 +7805,13 @@ function applyPostprocess(bytes, mediaType, record, reference = [], role) {
7747
7805
  if (mediaType !== MediaType.PNG || !record?.palette && !record?.despeckle && !record?.offset) return { bytes, changed: false };
7748
7806
  let out = bytes;
7749
7807
  let removed = 0;
7808
+ let opaque2 = 0;
7750
7809
  if (record.despeckle) {
7751
7810
  if (!reference.length) throw new Error(`cleaning needs the rotations of ${record.despeckle.of}, and none were given`);
7752
7811
  const cleaned = despeckle(out, { reference });
7753
7812
  if (cleaned.removed) {
7813
+ const { pixels } = decodePng(out);
7814
+ for (let i = 3; i < pixels.length; i += 4) if (pixels[i] > 0) opaque2++;
7754
7815
  out = cleaned.png;
7755
7816
  removed = cleaned.removed;
7756
7817
  }
@@ -7774,8 +7835,9 @@ function applyPostprocess(bytes, mediaType, record, reference = [], role) {
7774
7835
  }
7775
7836
  }
7776
7837
  if (!removed && !snapped && !moved) return { bytes, changed: false };
7777
- return { bytes: out, changed: true, ...removed ? { removed } : {}, ...snapped ? { snapped } : {}, ...moved ? { moved } : {} };
7838
+ return { bytes: out, changed: true, ...removed ? { removed, opaque: opaque2 } : {}, ...snapped ? { snapped } : {}, ...moved ? { moved } : {} };
7778
7839
  }
7840
+ var CLEAN_DAMAGE_SHARE = 0.03;
7779
7841
 
7780
7842
  // src/pipeline/mirror.ts
7781
7843
  function mirrorSourceHash(source) {
@@ -8073,6 +8135,13 @@ function characterCost(spec) {
8073
8135
  if (animation.mode === "template") return 1;
8074
8136
  if (animation.mode === "skeleton-v3") return 4;
8075
8137
  if (animation.mode === "v3") return Math.max(1, Math.ceil(px * animation.frames / 65536));
8138
+ if (animation.mode === "pixminimax") {
8139
+ const start = animation.startFrame;
8140
+ return Math.max(
8141
+ pixMiniMaxCost(spec.width, spec.height, animation.frames, animation.enhancePrompt),
8142
+ start ? pixMiniMaxCost(start.width, start.height, animation.frames, animation.enhancePrompt) : 0
8143
+ );
8144
+ }
8076
8145
  return proCharacterTierCost(spec.width, spec.height);
8077
8146
  }
8078
8147
  if (character.kind === "state" || character.kind === "portrait") return proCharacterTierCost(spec.width, spec.height);
@@ -8814,7 +8883,7 @@ var PixelLabProvider = class _PixelLabProvider {
8814
8883
  const { startFrame, endFrame } = character.animation;
8815
8884
  for (const [name, image] of [["start frame", startFrame], ["end frame", endFrame]]) {
8816
8885
  if (image && (image.width > 256 || image.height > 256)) {
8817
- throw new Error(`${label}: ${name} is ${image.width}x${image.height}; PixelLab v3 takes up to 256px`);
8886
+ throw new Error(`${label}: ${name} is ${image.width}x${image.height}; PixelLab ${character.animation.mode} takes up to 256px`);
8818
8887
  }
8819
8888
  }
8820
8889
  if (endFrame) {
@@ -8929,6 +8998,9 @@ var PixelLabProvider = class _PixelLabProvider {
8929
8998
  `${spec.styleId}/${spec.assetId} needs a prompt describing the motion, or a template` + (sentence ? ' (a skeleton-v3 loop with no template animates its prompt, e.g. "swinging a sword in a wide arc")' : "")
8930
8999
  );
8931
9000
  }
9001
+ if (character.animation.mode === "pixminimax" && (character.animation.frames % 4 !== 0 || character.animation.frames < 4 || character.animation.frames > 40)) {
9002
+ throw new Error(`${spec.styleId}/${spec.assetId}: a pixminimax loop takes a multiple of 4 frames, 4 to 40; ${character.animation.frames} is not one`);
9003
+ }
8932
9004
  if (sentence && (character.animation.frames < 3 || character.animation.frames > 15)) {
8933
9005
  throw new Error(`${spec.styleId}/${spec.assetId}: a skeleton-v3 loop from a sentence takes 3 to 15 frames; ${character.animation.frames} is out of range`);
8934
9006
  }
@@ -9240,7 +9312,9 @@ var PixelLabProvider = class _PixelLabProvider {
9240
9312
  isometric: character.isometric,
9241
9313
  startFrame: animation.startFrame ? readPose(spec, "start frame", animation.startFrame) : void 0,
9242
9314
  endFrame: animation.endFrame ? readPose(spec, "end frame", animation.endFrame) : void 0,
9243
- description: animation.subject,
9315
+ // PixMiniMax captions its start frame with its own two fields; the
9316
+ // other engines take `subject` as the general `description`.
9317
+ ...animation.mode === "pixminimax" ? { subjectDescription: animation.subject, initialPose: animation.initialPose } : { description: animation.subject },
9244
9318
  outline: animation.outline,
9245
9319
  shading: animation.shading,
9246
9320
  detail: animation.detail,
@@ -15219,6 +15293,8 @@ async function resolveCharacterShape(asset, style, kind, files) {
15219
15293
  ...asset.animation.startFrame ? { startFrame: await pose(asset.animation.startFrame, "Animation start frame") } : {},
15220
15294
  ...asset.animation.endFrame ? { endFrame: await pose(asset.animation.endFrame, "Animation end frame") } : {},
15221
15295
  ...asset.animation.subject ? { subject: asset.animation.subject } : {},
15296
+ // Set only on a pixminimax loop (the schema refuses it elsewhere), so no other spec's hash moves.
15297
+ ...asset.animation.initialPose ? { initialPose: asset.animation.initialPose } : {},
15222
15298
  ...asset.animation.outline ? { outline: asset.animation.outline } : {},
15223
15299
  ...asset.animation.shading ? { shading: asset.animation.shading } : {},
15224
15300
  ...asset.animation.detail ? { detail: asset.animation.detail } : {},
@@ -15257,6 +15333,7 @@ async function resolveObjectProShape(assetId, asset, style, kind, files) {
15257
15333
  for (const [field, value] of Object.entries({
15258
15334
  template: asset.animation.template,
15259
15335
  subject: asset.animation.subject,
15336
+ initialPose: asset.animation.initialPose,
15260
15337
  outline: asset.animation.outline,
15261
15338
  shading: asset.animation.shading,
15262
15339
  detail: asset.animation.detail
@@ -15270,7 +15347,7 @@ async function resolveObjectProShape(assetId, asset, style, kind, files) {
15270
15347
  if (asset.animation.clean !== void 0) {
15271
15348
  throw new Error(`assets.${assetId}: animation.clean applies to character loops; objectPro loops are not cleaned`);
15272
15349
  }
15273
- if (asset.animation.mode === "template" || asset.animation.mode === "skeleton-v3") {
15350
+ if (asset.animation.mode === "template" || asset.animation.mode === "skeleton-v3" || asset.animation.mode === "pixminimax") {
15274
15351
  throw new Error(`assets.${assetId}: objectPro animations have no "${asset.animation.mode}" mode; use "v3" or "pro"`);
15275
15352
  }
15276
15353
  const pose = async (rel, what) => {
@@ -17025,10 +17102,15 @@ async function buildPlan(specs, lock, opts = {}) {
17025
17102
  } else if (spec.mirror && entry.status === "downloaded" && entry.outputs.some((_output, index) => !existsSync14(currentEntryOutputPath(entry, spec, index)))) {
17026
17103
  state = "stale";
17027
17104
  reason = "mirror output missing on disk; flip it again (no generation cost)";
17028
- } else if (spec.character?.kind === "outfit" && entry.outfit?.sourceSha256 !== mirrorSourceHash(lock.entries[lockKey(spec.styleId, spec.character.parentAssetId)] ?? { outputs: [] })) {
17105
+ } else if (
17106
+ // A mirror carries its source's character shape, but it is a flip of
17107
+ // the source's files: whether it is current is the check above, never
17108
+ // the outfit or layer rule its source answers to (#418).
17109
+ !spec.mirror && spec.character?.kind === "outfit" && entry.outfit?.sourceSha256 !== mirrorSourceHash(lock.entries[lockKey(spec.styleId, spec.character.parentAssetId)] ?? { outputs: [] })
17110
+ ) {
17029
17111
  state = "stale";
17030
17112
  reason = `outfit source ${spec.character.parentAssetId} changed; re-clothe the loop again`;
17031
- } else if (spec.character?.kind === "layer" && changedLayerSource(spec, entry, lock)) {
17113
+ } else if (!spec.mirror && spec.character?.kind === "layer" && changedLayerSource(spec, entry, lock)) {
17032
17114
  state = "stale";
17033
17115
  reason = isHeldItem(spec) ? `layer source ${changedLayerSource(spec, entry, lock)} changed; place the item again (no generation cost)` : `layer source ${changedLayerSource(spec, entry, lock)} changed; dress the frames again`;
17034
17116
  } else if (isHeldItem(spec) && entry.status === "downloaded" && entry.outputs.some((_output, index) => !existsSync14(currentEntryOutputPath(entry, spec, index)))) {
@@ -17096,6 +17178,7 @@ async function buildPlan(specs, lock, opts = {}) {
17096
17178
  }
17097
17179
  const isActionable = (i) => i.state === "missing" || i.state === "stale" || i.state === "failed";
17098
17180
  const stateOf = new Map(items.map((i) => [i.key, i.state]));
17181
+ const waiting = /* @__PURE__ */ new Set();
17099
17182
  for (const item of items) {
17100
17183
  if (!isActionable(item)) continue;
17101
17184
  for (const parent of dependencies(item.spec)) {
@@ -17104,11 +17187,35 @@ async function buildPlan(specs, lock, opts = {}) {
17104
17187
  if (parentState && isActionable({ state: parentState })) {
17105
17188
  item.state = "blocked";
17106
17189
  item.reason = `parent ${parentKey} is being generated in this run; this follows in the next wave`;
17190
+ waiting.add(item.key);
17107
17191
  break;
17108
17192
  }
17109
17193
  if ((item.spec.mirror || item.spec.derive || isHeldItem(item.spec)) && (parentState === "recoverable" || parentState === "in-flight")) {
17110
17194
  item.state = "blocked";
17111
17195
  item.reason = `mirror source ${parentKey} is ${parentState}; this follows in the next wave`;
17196
+ waiting.add(item.key);
17197
+ break;
17198
+ }
17199
+ }
17200
+ }
17201
+ const byKey = new Map(items.map((i) => [i.key, i]));
17202
+ for (let changed = true; changed; ) {
17203
+ changed = false;
17204
+ for (const item of items) {
17205
+ if (item.state !== "blocked" || waiting.has(item.key)) continue;
17206
+ for (const parent of dependencies(item.spec)) {
17207
+ const parentKey = lockKey(parent.styleId, parent.assetId);
17208
+ const parentItem = byKey.get(parentKey);
17209
+ if (!parentItem || !item.reason.includes(`${parentKey} is not ready`)) continue;
17210
+ if (isActionable(parentItem)) {
17211
+ item.reason = `waits for ${parentKey}, which this run generates first; follows in a later wave (${item.reason})`;
17212
+ } else if (waiting.has(parentKey)) {
17213
+ item.reason = `waits for ${parentKey}, which itself follows in a later wave of this run (${item.reason})`;
17214
+ } else {
17215
+ continue;
17216
+ }
17217
+ waiting.add(item.key);
17218
+ changed = true;
17112
17219
  break;
17113
17220
  }
17114
17221
  }
@@ -19825,6 +19932,9 @@ async function fetchAssets(provider, specs, lock, lockPath, opts = {}) {
19825
19932
  if (processed.changed) rawHash = sha256(raw);
19826
19933
  if (processed.moved?.clipped) log(` moved ${path29.relative(process.cwd(), target)}: ${processed.moved.clipped} pixels fell off the canvas; raise layer.padding to keep them`);
19827
19934
  if (processed.removed) log(` cleaned ${path29.relative(process.cwd(), target)} (${processed.removed} ghost pixels)`);
19935
+ if (processed.removed && processed.opaque && processed.removed > processed.opaque * CLEAN_DAMAGE_SHARE) {
19936
+ log(` warning: cleaning took ${processed.removed} of ${processed.opaque} opaque pixels (${(100 * processed.removed / processed.opaque).toFixed(1)}%) from ${path29.relative(process.cwd(), target)}; check the frame for holes, and set clean: false then fetch to restore the provider's bytes`);
19937
+ }
19828
19938
  if (processed.snapped) log(` snapped ${path29.relative(process.cwd(), target)} to ${wanted.palette.colors.length} colours`);
19829
19939
  }
19830
19940
  if (cacheDir) await cacheMedia(cacheDir, buf, mediaType);
@@ -22763,12 +22873,12 @@ async function adopt(provider, specs, lock, lockPath, opts = {}) {
22763
22873
  provider: provider.id
22764
22874
  });
22765
22875
  matched++;
22766
- log(` adopted ${key3} \u2190 ${obj.id}`);
22876
+ log(` ${opts.dryRun ? "would adopt" : "adopted"} ${key3} \u2190 ${obj.id}`);
22767
22877
  }
22768
22878
  }
22769
22879
  }
22770
22880
  await Promise.all(Array.from({ length: Math.min(concurrency, remote.length || 1) }, worker));
22771
- await saveLock(lockPath, lock);
22881
+ if (!opts.dryRun) await saveLock(lockPath, lock);
22772
22882
  if (!opts.noCache) {
22773
22883
  pruneCache(cache, new Set(remote.map((o) => o.id)));
22774
22884
  await saveCache(cachePath, cache);
@@ -22803,10 +22913,11 @@ async function tagAdopted(provider, specs, lock, opts = {}) {
22803
22913
 
22804
22914
  // src/pipeline/import.ts
22805
22915
  import { existsSync as existsSync32 } from "fs";
22806
- import { readFile as readFile22 } from "fs/promises";
22916
+ import { readdir as readdir4, readFile as readFile22 } from "fs/promises";
22807
22917
  import path37 from "path";
22808
- function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date()) {
22918
+ function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Date(), frames) {
22809
22919
  const png = decodePng(bytes);
22920
+ for (const frame of frames ?? []) decodePng(frame.bytes);
22810
22921
  const at2 = now.toISOString();
22811
22922
  const origin = {
22812
22923
  ...opts.tool ? { tool: opts.tool } : {},
@@ -22831,7 +22942,14 @@ function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Da
22831
22942
  error: null,
22832
22943
  sourceUrl: null,
22833
22944
  sourceUrls: [],
22834
- outputs: [{ path: portableOutputPath(spec.outFile, spec.root), sha256: sha256(bytes) }],
22945
+ // A frame set is recorded the way fetch records one: an output per frame,
22946
+ // in order, each with its `frame-NN` role, so `plan` resolves the same paths.
22947
+ outputs: frames?.length ? frames.map((frame) => ({
22948
+ path: portableOutputPath(frame.file, spec.root),
22949
+ sha256: sha256(frame.bytes),
22950
+ role: frame.role,
22951
+ mediaType: MediaType.PNG
22952
+ })) : [{ path: portableOutputPath(spec.outFile, spec.root), sha256: sha256(bytes) }],
22835
22953
  submittedAt: null,
22836
22954
  downloadedAt: at2,
22837
22955
  cost: opts.cost ?? 0,
@@ -22846,6 +22964,32 @@ function buildImportedEntry(spec, bytes, opts = {}, now = /* @__PURE__ */ new Da
22846
22964
  }
22847
22965
  };
22848
22966
  }
22967
+ var frameRole2 = (index) => `frame-${String(index).padStart(2, "0")}`;
22968
+ async function findFrames(spec) {
22969
+ const at2 = (index) => memberPath(spec.outFile, frameRole2(index), 0, 2, MediaType.PNG);
22970
+ const base = path37.basename(at2(0)).replace(/00\.png$/, "");
22971
+ let names = [];
22972
+ try {
22973
+ names = await readdir4(path37.dirname(spec.outFile));
22974
+ } catch {
22975
+ names = [];
22976
+ }
22977
+ const found = /* @__PURE__ */ new Set();
22978
+ for (const name of names) {
22979
+ if (!name.startsWith(base)) continue;
22980
+ const match = /^(\d+)\.png$/i.exec(name.slice(base.length));
22981
+ if (match) found.add(Number(match[1]));
22982
+ }
22983
+ const expected = spec.revision?.frames;
22984
+ const expectsFrames = expected !== void 0 || spec.generator === "frames";
22985
+ if (!found.size && !expectsFrames) return null;
22986
+ const highest = found.size ? Math.max(...found) : -1;
22987
+ const upTo = Math.max(highest + 1, expected ?? 0, expectsFrames ? 1 : 0);
22988
+ const missing = [];
22989
+ for (let index = 0; index < upTo; index++) if (!found.has(index)) missing.push(at2(index));
22990
+ if (missing.length) return { missing };
22991
+ return { files: Array.from({ length: upTo }, (_, index) => ({ role: frameRole2(index), file: at2(index) })) };
22992
+ }
22849
22993
  function unimportable(spec) {
22850
22994
  if (spec.character) return "a character is several files; import it with account adopt";
22851
22995
  if (spec.vfx) return "an effect is rendered from its recipe, not imported";
@@ -22878,9 +23022,18 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22878
23022
  skipped.push({ key: key3, reason });
22879
23023
  continue;
22880
23024
  }
23025
+ let frameFiles;
22881
23026
  if (!existsSync32(spec.outFile)) {
22882
- skipped.push({ key: key3, reason: `no file at ${spec.outFile}` });
22883
- continue;
23027
+ const frames2 = await findFrames(spec);
23028
+ if (!frames2) {
23029
+ skipped.push({ key: key3, reason: `no file at ${spec.outFile}` });
23030
+ continue;
23031
+ }
23032
+ if ("missing" in frames2) {
23033
+ skipped.push({ key: key3, reason: `frame set is missing ${frames2.missing.map((file) => path37.basename(file)).join(", ")} (in ${path37.dirname(spec.outFile)})` });
23034
+ continue;
23035
+ }
23036
+ frameFiles = frames2.files;
22884
23037
  }
22885
23038
  if (lock.entries[key3] && !opts.force) {
22886
23039
  skipped.push({ key: key3, reason: "already in the lockfile (use --force to replace it)" });
@@ -22888,9 +23041,11 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22888
23041
  }
22889
23042
  let patch;
22890
23043
  let bytes;
23044
+ let frames;
22891
23045
  try {
22892
- bytes = await readFile22(spec.outFile);
22893
- patch = buildImportedEntry(spec, bytes, { ...opts, rawSha256 }, /* @__PURE__ */ new Date());
23046
+ frames = frameFiles ? await Promise.all(frameFiles.map(async (frame) => ({ ...frame, bytes: await readFile22(frame.file) }))) : void 0;
23047
+ bytes = frames ? frames[0].bytes : await readFile22(spec.outFile);
23048
+ patch = buildImportedEntry(spec, bytes, { ...opts, rawSha256 }, /* @__PURE__ */ new Date(), frames);
22894
23049
  } catch (error) {
22895
23050
  skipped.push({ key: key3, reason: `invalid PNG: ${error instanceof Error ? error.message : String(error)}` });
22896
23051
  continue;
@@ -22900,9 +23055,10 @@ async function importLocal(specs, lock, lockPath, opts = {}) {
22900
23055
  continue;
22901
23056
  }
22902
23057
  const existing = lock.entries[key3];
22903
- const history = existing?.outputs[0]?.sha256 === sha256(bytes) ? existing.history : historyAfterReplacing(existing, opts.historyLimit ?? DEFAULT_HISTORY_LIMIT, patch.downloadedAt ?? (/* @__PURE__ */ new Date()).toISOString());
23058
+ const sameBytes = existing !== void 0 && existing.outputs.length === patch.outputs.length && existing.outputs.every((output, index) => output.sha256 === patch.outputs[index].sha256);
23059
+ const history = sameBytes ? existing.history : historyAfterReplacing(existing, opts.historyLimit ?? DEFAULT_HISTORY_LIMIT, patch.downloadedAt ?? (/* @__PURE__ */ new Date()).toISOString());
22904
23060
  if (cacheDir) {
22905
- await cacheMedia(cacheDir, bytes, MediaType.PNG);
23061
+ for (const member of frames ?? [{ bytes }]) await cacheMedia(cacheDir, member.bytes, MediaType.PNG);
22906
23062
  if (rawBytes) await cacheMedia(cacheDir, rawBytes, MediaType.PNG);
22907
23063
  }
22908
23064
  imported.push({ key: key3, entry: upsert(lock, key3, {
@@ -22954,7 +23110,7 @@ import { existsSync as existsSync34 } from "fs";
22954
23110
  import { readFile as readFile25 } from "fs/promises";
22955
23111
 
22956
23112
  // src/pipeline/init.ts
22957
- import { readdir as readdir4, readFile as readFile23, writeFile as writeFile16 } from "fs/promises";
23113
+ import { readdir as readdir5, readFile as readFile23, writeFile as writeFile16 } from "fs/promises";
22958
23114
  import { existsSync as existsSync33 } from "fs";
22959
23115
  import path38 from "path";
22960
23116
  function pngSize(buf) {
@@ -22969,7 +23125,7 @@ function slugify(value) {
22969
23125
  }
22970
23126
  async function walk(dir, exclude) {
22971
23127
  const out = [];
22972
- for (const entry of await readdir4(dir, { withFileTypes: true })) {
23128
+ for (const entry of await readdir5(dir, { withFileTypes: true })) {
22973
23129
  const full = path38.join(dir, entry.name);
22974
23130
  if (exclude.some((x) => full.includes(x))) continue;
22975
23131
  if (entry.isDirectory()) out.push(...await walk(full, exclude));
@@ -24868,7 +25024,8 @@ var NewAnimationSchema = z9.object({
24868
25024
  /** A PixelLab template id (`character` only; `objectPro` has no template concept). */
24869
25025
  template: z9.string().min(1).optional(),
24870
25026
  direction: CharacterDirectionSchema.optional(),
24871
- frames: z9.number().int().min(4).max(16).optional(),
25027
+ /** 4 to 16; a pixminimax loop takes a multiple of 4 up to 40. The manifest's own schema checks the rest. */
25028
+ frames: z9.number().int().min(4).max(40).optional(),
24872
25029
  fps: z9.number().int().min(1).max(60).optional(),
24873
25030
  /** One loop per named direction, plus free mirrors; expanded when the manifest loads. */
24874
25031
  directions: z9.array(CharacterDirectionSchema).min(1).optional(),
@@ -25576,7 +25733,7 @@ function openInEditor(file, editor = process.env.PIXELKILN_EDITOR) {
25576
25733
  // src/pipeline/model-edit.ts
25577
25734
  import { spawn as spawn2 } from "child_process";
25578
25735
  import { existsSync as existsSync36, readdirSync as readdirSync2 } from "fs";
25579
- import { mkdir as mkdir16, readdir as readdir5, readFile as readFile28, rename as rename11, rm as rm10, writeFile as writeFile19 } from "fs/promises";
25736
+ import { mkdir as mkdir16, readdir as readdir6, readFile as readFile28, rename as rename11, rm as rm10, writeFile as writeFile19 } from "fs/promises";
25580
25737
  import path41 from "path";
25581
25738
  import { z as z11 } from "zod";
25582
25739
 
@@ -25966,7 +26123,7 @@ async function discoverModels(loaded, opts = {}) {
25966
26123
  if (depth > MAX_DEPTH || models.length >= MAX_MODELS) return;
25967
26124
  let entries;
25968
26125
  try {
25969
- entries = await readdir5(dir, { withFileTypes: true });
26126
+ entries = await readdir6(dir, { withFileTypes: true });
25970
26127
  } catch {
25971
26128
  return;
25972
26129
  }
@@ -26264,7 +26421,7 @@ function openInBlender(model, opts = {}) {
26264
26421
  // src/pipeline/model-normals.ts
26265
26422
  import { createHash as createHash7 } from "crypto";
26266
26423
  import { existsSync as existsSync37 } from "fs";
26267
- import { mkdir as mkdir17, readdir as readdir6, readFile as readFile29, writeFile as writeFile20 } from "fs/promises";
26424
+ import { mkdir as mkdir17, readdir as readdir7, readFile as readFile29, writeFile as writeFile20 } from "fs/promises";
26268
26425
  import path42 from "path";
26269
26426
  var MODEL_NORMAL_SOURCES = ["texture", "views", "sprites"];
26270
26427
  var TILE_MAX = 512;
@@ -26995,7 +27152,7 @@ function modelSpritesDir(modelFile) {
26995
27152
  }
26996
27153
  async function readSpriteFolder(dir) {
26997
27154
  const folder = existsSync37(path42.join(dir, "rotations")) ? path42.join(dir, "rotations") : dir;
26998
- const names = (await readdir6(folder)).filter((name) => name.toLowerCase().endsWith(".png") && VIEW_TURNS[name.slice(0, -4).toLowerCase()] !== void 0).sort();
27155
+ const names = (await readdir7(folder)).filter((name) => name.toLowerCase().endsWith(".png") && VIEW_TURNS[name.slice(0, -4).toLowerCase()] !== void 0).sort();
26999
27156
  return Promise.all(names.map(async (name) => ({ direction: name.slice(0, -4).toLowerCase(), png: await readFile29(path42.join(folder, name)), file: path42.join(folder, name) })));
27000
27157
  }
27001
27158
  function modelNormalDir(editFile) {