pixelkiln 0.101.0 → 0.102.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/cli.js CHANGED
@@ -67,8 +67,8 @@ function exitCodeFor(err) {
67
67
  }
68
68
 
69
69
  // src/cli/main.ts
70
- import { existsSync as existsSync47 } from "fs";
71
- import { readFile as readFile40 } from "fs/promises";
70
+ import { existsSync as existsSync49 } from "fs";
71
+ import { readFile as readFile43 } from "fs/promises";
72
72
 
73
73
  // src/cli/args.ts
74
74
  import path from "path";
@@ -124,8 +124,21 @@ var VALUE_FLAGS = [
124
124
  "--part",
125
125
  "--sprite",
126
126
  "--fps",
127
+ "--sprite-frames",
128
+ "--sprite-fps",
127
129
  "--artist",
128
130
  "--convention",
131
+ "--text",
132
+ "--mood",
133
+ "--visemes",
134
+ "--engine",
135
+ "--frame-ms",
136
+ "--hold-ms",
137
+ "--target",
138
+ "--tile-type",
139
+ "--lower",
140
+ "--upper",
141
+ "--transition",
129
142
  "--id",
130
143
  "--state",
131
144
  "--element",
@@ -220,6 +233,7 @@ var COMMANDS = [
220
233
  "sfx",
221
234
  "ui",
222
235
  "asset",
236
+ "talk",
223
237
  "help",
224
238
  "--help",
225
239
  "-h",
@@ -235,7 +249,8 @@ var TOOLS_SUBCOMMANDS = ["status", "install"];
235
249
  var TOOLS = ["editor"];
236
250
  var VFX_SUBCOMMANDS = ["make", "presets", "parts"];
237
251
  var MUSIC_SUBCOMMANDS = ["make", "style", "lyrics"];
238
- var ASSET_SUBCOMMANDS = ["canvas", "mirror", "import", "expand", "review", "export"];
252
+ var TALK_SUBCOMMANDS = ["visemes", "gif", "plan"];
253
+ var ASSET_SUBCOMMANDS = ["canvas", "mirror", "import", "save", "expand", "review", "export"];
239
254
  var UI_SUBCOMMANDS = ["show", "split", "states", "nine-slice", "pull"];
240
255
  function parseArgs(argv) {
241
256
  const [command = "help"] = argv;
@@ -332,6 +347,15 @@ function parseArgs(argv) {
332
347
  throw new UsageError(`Unknown vfx subcommand "${subcommand}". Known: ${VFX_SUBCOMMANDS.join(", ")}`);
333
348
  }
334
349
  if (rest[0] === subcommand) rest = rest.slice(1);
350
+ } else if (command === "talk") {
351
+ subcommand = rest[0];
352
+ if (subcommand === void 0 || subcommand.startsWith("-")) {
353
+ throw new UsageError(`talk needs a subcommand: ${TALK_SUBCOMMANDS.join(", ")}`);
354
+ }
355
+ if (!TALK_SUBCOMMANDS.includes(subcommand)) {
356
+ throw new UsageError(`Unknown talk subcommand "${subcommand}". Known: ${TALK_SUBCOMMANDS.join(", ")}`);
357
+ }
358
+ rest = rest.slice(1);
335
359
  } else if (command === "asset") {
336
360
  subcommand = rest[0];
337
361
  if (subcommand === void 0 || subcommand.startsWith("-")) {
@@ -543,6 +567,8 @@ function parseArgs(argv) {
543
567
  parts: list("--part"),
544
568
  sprite: get("--sprite"),
545
569
  fps: numberOption("--fps", { min: 1, max: 60, integer: true }),
570
+ spriteFrames: numberOption("--sprite-frames", { min: 1, max: 32, integer: true }),
571
+ spriteFps: numberOption("--sprite-fps", { min: 1, max: 60, integer: true }),
546
572
  gamePack: rest.includes("--game-pack"),
547
573
  mode: get("--mode"),
548
574
  strength: numberOption("--strength", { min: 0, max: 2 }),
@@ -552,6 +578,17 @@ function parseArgs(argv) {
552
578
  detailSoftness: numberOption("--detail-softness", { min: 0.6, max: 3 }),
553
579
  kind: get("--kind"),
554
580
  size: get("--size"),
581
+ saveTarget: get("--target"),
582
+ text: get("--text"),
583
+ mood: get("--mood"),
584
+ visemes: numberOption("--visemes", { min: 3, max: 12, integer: true }),
585
+ engine: get("--engine"),
586
+ frameMs: numberOption("--frame-ms", { min: 1, max: 5e3, integer: true }),
587
+ holdMs: numberOption("--hold-ms", { min: 0, max: 1e4, integer: true }),
588
+ tileType: get("--tile-type"),
589
+ lower: get("--lower"),
590
+ upper: get("--upper"),
591
+ transition: get("--transition"),
555
592
  animation: get("--animation"),
556
593
  direction: get("--direction"),
557
594
  keep: rest.includes("--keep"),
@@ -672,11 +709,19 @@ Commands
672
709
  first); ui nine-slice sets stretch insets (free); ui pull downloads
673
710
  every image with a ui.json record.
674
711
  asset PixelLab: upkeep for an object or character by --id. asset import
675
- stores your own PNG as an object; asset expand draws a 1-direction
712
+ stores your own PNG as an object (--kind tileset: a Wang sheet as
713
+ a tileset; --kind tiles: tile PNGs as a tile group); asset save
714
+ writes edited pixels back over a stored asset (--target) and
715
+ keeps what it replaced; asset expand draws a 1-direction
676
716
  object's other 7 (10-25 generations; asks first), asset review
677
717
  downloads them, then --keep or --discard; asset canvas resizes
678
718
  the canvas; asset mirror flips a loop's direction; asset export
679
719
  writes a zip, spritesheet, .aseprite or gif. All but expand free.
720
+ talk PixelLab: a talking portrait. talk visemes draws a portrait's mouth
721
+ positions once (--from <png> or --id <character>; 3-24
722
+ generations; asks first) and writes a strip and a .talk.json
723
+ record; talk gif lip-syncs --text to a GIF and talk plan prints
724
+ the frame plan for a game engine, both free.
680
725
  sfx PixelLab: a sound effect (--description, --seconds, --out); writes
681
726
  a WAV and a .sfx.json record. From 1 generation, by length.
682
727
 
@@ -708,15 +753,30 @@ Options
708
753
  --artist <a> vfx --description: lite (default) or pro
709
754
  --weight <w> font: Bold or Regular (default)
710
755
  --id <id> ui/asset: the PixelLab asset to work on
711
- --kind <kind> asset: object (default) or character; normal-map: what the
756
+ --kind <kind> asset: object (default) or character; asset import also
757
+ takes tileset and tiles; normal-map: what the
712
758
  picture is (character, object, topdown, side, iso, ui)
713
- --mode <mode> normal-map: lite (default, 0.1 generation) or pro (0.5)
759
+ --mode <mode> normal-map: lite (default, 0.1 generation) or pro (0.5);
760
+ asset import --kind tileset: topdown (default) or sidescroller
714
761
  --strength <n> normal-map: how far pixels tilt from the viewer, 0-2
715
762
  --outline-rounding <n> normal-map: how much the outline rounds off, 0-3
716
763
  --part-shapes <n> normal-map: how much the sprite's 3D parts add, 0-2
717
764
  --surface-detail <n> normal-map: the art's light and dark as bumps, 0-2
718
765
  --detail-softness <n> normal-map: blur of that detail in px, 0.6-3
719
- --size <WxH> asset canvas: the new canvas, in multiples of 4
766
+ --size <WxH> asset canvas: the new canvas, in multiples of 4;
767
+ asset import --kind tileset/tiles: the tile size, e.g. 32
768
+ --text <line> talk gif/plan: the line of dialogue, up to 500 characters
769
+ --mood <mood> talk: neutral (default), happy, angry, sad or surprised
770
+ --visemes <n> talk visemes/plan: mouth positions, 3, 5, 7 (default) or 12
771
+ --engine <e> talk visemes: v3 (default) or pixminimax
772
+ --frame-ms <n> talk gif/plan: milliseconds per mouth position (default 90)
773
+ --hold-ms <n> talk gif/plan: pause on the closed mouth at the end (default 600)
774
+ --target <target> asset save: character:<id>:<dir>, object:<id>[:<dir>],
775
+ gallery:<id>, gallery:new, or tileset:<id>
776
+ --tile-type <type> asset import --kind tiles: square_topdown, isometric,
777
+ oblique, hex, hex_pointy or octagon
778
+ --lower, --upper, --transition <text>
779
+ asset import --kind tileset: the terrains' descriptions
720
780
  --animation <id> asset mirror/export: an animation group id
721
781
  --direction <dir> asset mirror: the direction to flip; asset expand: the
722
782
  way the object faces now; asset export gif: the direction
@@ -747,6 +807,8 @@ Options
747
807
  --part <name> vfx: add a part (repeatable; vfx parts lists them)
748
808
  --sprite <ref> vfx: build around a sprite: a file, a URL, or character:<id>:<dir>
749
809
  --fps <n> vfx: frames per second, 1-60
810
+ --sprite-frames <n> vfx --description: --sprite is a strip of n equal frames (2-32)
811
+ --sprite-fps <n> vfx --description: how fast the sprite animation plays (default 12)
750
812
  --game-pack vfx: also download the game-pack ZIP
751
813
  --glyph-px <n> font: native glyph size, 8, 16 (default), 32, or 64
752
814
  --prune cache: remove invalid/unreferenced local cache data
@@ -1296,10 +1358,10 @@ function normalizeHex(value) {
1296
1358
  function sha256(data) {
1297
1359
  return createHash("sha256").update(data).digest("hex");
1298
1360
  }
1299
- async function sha256File(path63) {
1361
+ async function sha256File(path65) {
1300
1362
  return new Promise((resolve, reject) => {
1301
1363
  const hash = createHash("sha256");
1302
- const stream = createReadStream(path63);
1364
+ const stream = createReadStream(path65);
1303
1365
  stream.on("data", (chunk2) => hash.update(chunk2));
1304
1366
  stream.on("error", reject);
1305
1367
  stream.on("end", () => resolve(hash.digest("hex")));
@@ -1459,7 +1521,11 @@ function specHash(spec, styleImageHashes, providerOptionIdentity = spec.provider
1459
1521
  fps: spec.vfx.fps,
1460
1522
  sprite: spec.vfx.sprite ? "reference" in spec.vfx.sprite ? spec.vfx.sprite.reference : spec.vfx.sprite.sha256 : void 0,
1461
1523
  description: spec.vfx.description,
1462
- artist: spec.vfx.description ? spec.vfx.artist : void 0
1524
+ artist: spec.vfx.description ? spec.vfx.artist : void 0,
1525
+ // Absent for a still sprite, so every effect made before strips
1526
+ // existed keeps its hash.
1527
+ spriteFrames: spec.vfx.spriteFrames,
1528
+ spriteFps: spec.vfx.spriteFps
1463
1529
  } : void 0,
1464
1530
  // A mirror's bytes come from its source's recorded outputs; the plan
1465
1531
  // compares those directly, so only the choice of source is identity.
@@ -1830,8 +1896,21 @@ var AssetVfxSchema = z.object({
1830
1896
  fps: z.number().int().min(1).max(60).optional(),
1831
1897
  name: z.string().min(1).optional(),
1832
1898
  description: z.string().trim().min(1).max(8e3).optional(),
1833
- artist: z.enum(["lite", "pro"]).optional()
1899
+ artist: z.enum(["lite", "pro"]).optional(),
1900
+ spriteFrames: z.number().int().min(1).max(32).optional(),
1901
+ spriteFps: z.number().int().min(1).max(60).optional()
1834
1902
  }).strict().superRefine((vfx, context) => {
1903
+ for (const key2 of ["spriteFrames", "spriteFps"]) {
1904
+ if (vfx[key2] === void 0) continue;
1905
+ if (vfx.description === void 0) {
1906
+ context.addIssue({ code: z.ZodIssueCode.custom, message: `${key2} describes the sprite sent to PixelLab's VFX artist; add a description`, path: [key2] });
1907
+ } else if (!vfx.sprite) {
1908
+ context.addIssue({ code: z.ZodIssueCode.custom, message: `${key2} describes a sprite strip; add a sprite`, path: [key2] });
1909
+ }
1910
+ }
1911
+ if (vfx.spriteFps !== void 0 && vfx.sprite && vfx.description !== void 0 && (vfx.spriteFrames ?? 1) < 2) {
1912
+ context.addIssue({ code: z.ZodIssueCode.custom, message: "spriteFps is the speed of a sprite strip; set spriteFrames to 2 or more", path: ["spriteFps"] });
1913
+ }
1835
1914
  if (vfx.description !== void 0) {
1836
1915
  for (const key2 of ["preset", "recipe", "parts", "fps"]) {
1837
1916
  if (vfx[key2] !== void 0) {
@@ -2769,7 +2848,7 @@ var AssetDeriveSchema = z.object({
2769
2848
  /** scale: `nearest` (default) keeps hard edges; `box` averages the covered pixels. */
2770
2849
  mode: z.enum(["nearest", "box"]).optional()
2771
2850
  }).strict().superRefine((derive, context) => {
2772
- const issue = (message6, path63) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path63] });
2851
+ const issue = (message6, path65) => context.addIssue({ code: z.ZodIssueCode.custom, message: message6, path: [path65] });
2773
2852
  if (Boolean(derive.from) === Boolean(derive.file)) {
2774
2853
  issue("name exactly one source: `from` (an asset in this style) or `file` (a committed PNG)", derive.from ? "file" : "from");
2775
2854
  }
@@ -7261,6 +7340,53 @@ var ImportObjectSchema = z3.object({
7261
7340
  size: z3.object({ width: z3.number(), height: z3.number() }).passthrough(),
7262
7341
  image_url: z3.string()
7263
7342
  }).passthrough();
7343
+ var ImportTilesetSchema = z3.object({ tileset_id: z3.string().min(1), status: z3.string().default("completed") }).passthrough();
7344
+ var ImportTilesProSchema = z3.object({ tile_id: z3.string().min(1), status: z3.string().default("completed") }).passthrough();
7345
+ var SaveToAssetSchema = z3.object({
7346
+ action: z3.enum(["saved", "added", "unchanged"]),
7347
+ target: z3.string().min(1),
7348
+ kind: z3.string(),
7349
+ width: z3.number(),
7350
+ height: z3.number(),
7351
+ frame_count: z3.number(),
7352
+ changed_pixels: z3.number().default(0),
7353
+ previous_frames: z3.array(z3.object({ base64: z3.string().min(1) }).passthrough()).nullable().optional(),
7354
+ note: z3.string().nullable().optional(),
7355
+ maps: z3.string().nullable().optional()
7356
+ }).passthrough();
7357
+ var VocalAnimationSubmitSchema = z3.object({ background_job_id: z3.string().min(1), status: z3.string().default("processing") }).passthrough();
7358
+ var VocalAnimationJobSchema = z3.object({
7359
+ status: z3.string(),
7360
+ mood: z3.string().optional(),
7361
+ viseme_count: z3.number().optional(),
7362
+ character_id: z3.string().nullable().optional(),
7363
+ completed_visemes: z3.array(z3.string()).default([]),
7364
+ visemes: z3.record(z3.string(), z3.object({ base64: z3.string().min(1) }).passthrough()).nullable().optional(),
7365
+ moods_on_character: z3.array(z3.string()).nullable().optional(),
7366
+ grid_url: z3.string().nullable().optional(),
7367
+ viseme_order: z3.array(z3.string()).nullable().optional(),
7368
+ usage: z3.unknown().optional()
7369
+ }).passthrough();
7370
+ var TalkingGifSchema = z3.object({
7371
+ gif_base64: z3.string().min(1),
7372
+ frames: z3.number(),
7373
+ duration_ms: z3.number(),
7374
+ frame_ms: z3.number(),
7375
+ hold_ms: z3.number(),
7376
+ width: z3.number(),
7377
+ height: z3.number(),
7378
+ mood: z3.string().nullable().optional()
7379
+ }).passthrough();
7380
+ var LipSyncSchema = z3.object({
7381
+ text: z3.string(),
7382
+ total_ms: z3.number(),
7383
+ viseme_order: z3.array(z3.string()),
7384
+ frames: z3.array(z3.object({ viseme: z3.string(), column: z3.number(), duration_ms: z3.number(), text_offset: z3.number() }).passthrough()),
7385
+ mood: z3.string().nullable().optional(),
7386
+ grid_url: z3.string().nullable().optional(),
7387
+ row: z3.number().nullable().optional(),
7388
+ rows: z3.number().nullable().optional()
7389
+ }).passthrough();
7264
7390
  var ExpandRotationsSchema = z3.object({
7265
7391
  object_id: z3.string().min(1),
7266
7392
  background_job_id: z3.string().min(1),
@@ -7629,9 +7755,9 @@ var PixelLabClient = class {
7629
7755
  apiKey;
7630
7756
  http;
7631
7757
  /** Retries transport failures, 429, and 5xx; see http.ts for the policy. */
7632
- async request(path63, init) {
7758
+ async request(path65, init) {
7633
7759
  const auth = this.apiKey.startsWith("Bearer ") ? this.apiKey : `Bearer ${this.apiKey}`;
7634
- const res = await this.http(`${BASE}${path63}`, {
7760
+ const res = await this.http(`${BASE}${path65}`, {
7635
7761
  ...init,
7636
7762
  headers: {
7637
7763
  Authorization: auth,
@@ -7642,13 +7768,13 @@ var PixelLabClient = class {
7642
7768
  const text = await res.text();
7643
7769
  if (!res.ok) {
7644
7770
  const hint = res.status === 500 && text.includes("Failed to start any animation jobs") ? '; a skeleton-v3 loop needs a character with a stored 3D skeleton (a v3 base), use mode: "template" on a standard one' : "";
7645
- throw new PixelLabError(`${init?.method ?? "GET"} ${path63} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
7771
+ throw new PixelLabError(`${init?.method ?? "GET"} ${path65} \u2192 ${res.status}${hint}${refusalReason(res.status, text)}`, res.status, text);
7646
7772
  }
7647
7773
  if (!text) return {};
7648
7774
  try {
7649
7775
  return JSON.parse(text);
7650
7776
  } catch {
7651
- throw new Error(`${init?.method ?? "GET"} ${path63} returned invalid JSON`);
7777
+ throw new Error(`${init?.method ?? "GET"} ${path65} returned invalid JSON`);
7652
7778
  }
7653
7779
  }
7654
7780
  async balance() {
@@ -8026,6 +8152,9 @@ var PixelLabClient = class {
8026
8152
  body.init_image = { type: "base64", base64: args.initImage.base64, format: args.initImage.format };
8027
8153
  if (args.initImageStrength != null) body.init_image_strength = args.initImageStrength;
8028
8154
  }
8155
+ if (args.outline) body.outline = args.outline;
8156
+ if (args.shading) body.shading = args.shading;
8157
+ if (args.detail) body.detail = args.detail;
8029
8158
  if (args.seed != null) body.seed = args.seed;
8030
8159
  const res = validateResponse(
8031
8160
  PixfluxResponseSchema,
@@ -8185,10 +8314,10 @@ var PixelLabClient = class {
8185
8314
  const palette = args.paletteSwatchBase64 ? { color_image: { type: "base64", base64: args.paletteSwatchBase64, format: "png" }, force_colors: true } : {};
8186
8315
  const encode = (image) => ({ type: "base64", base64: image.base64, format: image.format });
8187
8316
  const south = args.reference?.south;
8188
- let path63;
8317
+ let path65;
8189
8318
  let body;
8190
8319
  if (args.mode === "v3") {
8191
- path63 = "/create-character-v3";
8320
+ path65 = "/create-character-v3";
8192
8321
  body = {
8193
8322
  description: args.description,
8194
8323
  image_size: imageSize,
@@ -8202,7 +8331,7 @@ var PixelLabClient = class {
8202
8331
  ...args.enhancePrompt ? { enhance_prompt: true } : {}
8203
8332
  };
8204
8333
  } else if (args.mode === "pro-flash") {
8205
- path63 = "/create-character-pro-flash";
8334
+ path65 = "/create-character-pro-flash";
8206
8335
  const traits = args.styleTraits;
8207
8336
  body = {
8208
8337
  description: args.description,
@@ -8226,7 +8355,7 @@ var PixelLabClient = class {
8226
8355
  } : {}
8227
8356
  };
8228
8357
  } else if (args.mode === "pro") {
8229
- path63 = "/create-character-pro";
8358
+ path65 = "/create-character-pro";
8230
8359
  body = {
8231
8360
  description: args.description,
8232
8361
  image_size: imageSize,
@@ -8240,7 +8369,7 @@ var PixelLabClient = class {
8240
8369
  ...!south && args.styleCharacterId ? { style_character_id: args.styleCharacterId } : {}
8241
8370
  };
8242
8371
  } else {
8243
- path63 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
8372
+ path65 = args.directions === 4 ? "/create-character-with-4-directions" : "/create-character-with-8-directions";
8244
8373
  body = {
8245
8374
  description: args.description,
8246
8375
  image_size: imageSize,
@@ -8258,8 +8387,8 @@ var PixelLabClient = class {
8258
8387
  };
8259
8388
  }
8260
8389
  if (args.mode === "pro" || args.mode === "pro-flash") Object.assign(body, targetPaletteBody(args.targetPalette));
8261
- const raw = await this.request(path63, { method: "POST", body: JSON.stringify(body) });
8262
- return validateResponse(CharacterSubmitSchema, raw, path63.slice(1));
8390
+ const raw = await this.request(path65, { method: "POST", body: JSON.stringify(body) });
8391
+ return validateResponse(CharacterSubmitSchema, raw, path65.slice(1));
8263
8392
  }
8264
8393
  /** A text edit of an existing character, applied to every direction and stored as a sibling. */
8265
8394
  async createCharacterState(args) {
@@ -8834,6 +8963,8 @@ var PixelLabClient = class {
8834
8963
  const body = { description: args.description };
8835
8964
  if (args.artist) body.artist = args.artist;
8836
8965
  if (args.sprite) body.sprite = { type: "base64", base64: args.sprite.base64, format: args.sprite.format };
8966
+ if (args.sprite && args.spriteFrames != null && args.spriteFrames > 1) body.sprite_frames = args.spriteFrames;
8967
+ if (args.sprite && args.spriteFps != null) body.sprite_fps = args.spriteFps;
8837
8968
  if (args.effectId) body.effect_id = args.effectId;
8838
8969
  if (args.conversation) body.conversation = args.conversation;
8839
8970
  if (args.name) body.name = args.name;
@@ -8978,6 +9109,108 @@ var PixelLabClient = class {
8978
9109
  "objects/import"
8979
9110
  );
8980
9111
  }
9112
+ /**
9113
+ * `POST /vocal-animation`: one expression's mouth positions for a portrait,
9114
+ * from an image (nothing stored; the frames come back inline) or from a
9115
+ * character's stored portrait (saved onto it). Paid; `pixminimax` costs 3
9116
+ * generations for 7 positions at any size, `v3` 3 to 24 by size.
9117
+ */
9118
+ async createVocalAnimation(args) {
9119
+ const body = {};
9120
+ if (args.portrait) body.portrait = { type: "base64", base64: args.portrait.base64, format: args.portrait.format };
9121
+ if (args.characterId) body.character_id = args.characterId;
9122
+ if (args.mood) body.mood = args.mood;
9123
+ if (args.visemeCount != null) body.viseme_count = args.visemeCount;
9124
+ if (args.engine) body.engine = args.engine;
9125
+ if (args.seed != null) body.seed = args.seed;
9126
+ return validateResponse(
9127
+ VocalAnimationSubmitSchema,
9128
+ await this.request("/vocal-animation", { method: "POST", body: JSON.stringify(body) }),
9129
+ "vocal-animation"
9130
+ );
9131
+ }
9132
+ /** `GET /vocal-animation/{job}`: the job's status, and its mouth positions once completed. Its bill is on `getBackgroundJob`. */
9133
+ async getVocalAnimation(jobId) {
9134
+ return validateResponse(VocalAnimationJobSchema, await this.request(`/vocal-animation/${encodeURIComponent(jobId)}`), "vocal-animation/{job}");
9135
+ }
9136
+ /** `POST /talking-gif`: a line of text lip-synced to a GIF from mouth positions already made. Free; answers at once. */
9137
+ async createTalkingGif(args) {
9138
+ const body = { text: args.text };
9139
+ if (args.visemes) {
9140
+ body.visemes = Object.fromEntries(Object.entries(args.visemes).map(([id, image]) => [id, { type: "base64", base64: image.base64, format: image.format }]));
9141
+ }
9142
+ if (args.characterId) body.character_id = args.characterId;
9143
+ if (args.mood) body.mood = args.mood;
9144
+ if (args.frameMs != null) body.frame_ms = args.frameMs;
9145
+ if (args.holdMs != null) body.hold_ms = args.holdMs;
9146
+ return validateResponse(TalkingGifSchema, await this.request("/talking-gif", { method: "POST", body: JSON.stringify(body) }), "talking-gif");
9147
+ }
9148
+ /** `POST /lip-sync`: which mouth position to show and for how long, for a line of text. Free; nothing is rendered. */
9149
+ async getLipSync(args) {
9150
+ const body = { text: args.text };
9151
+ if (args.characterId) body.character_id = args.characterId;
9152
+ if (args.mood) body.mood = args.mood;
9153
+ if (args.visemeCount != null) body.viseme_count = args.visemeCount;
9154
+ if (args.frameMs != null) body.frame_ms = args.frameMs;
9155
+ if (args.holdMs != null) body.hold_ms = args.holdMs;
9156
+ return validateResponse(LipSyncSchema, await this.request("/lip-sync", { method: "POST", body: JSON.stringify(body) }), "lip-sync");
9157
+ }
9158
+ /**
9159
+ * `POST /tilesets/import`: your own Wang sheet as a completed tileset, in
9160
+ * PixelLab's compact 4x4 layout or its 8-wide native one. Free. Send
9161
+ * `tileSize` whenever the sheet reads two ways: omitted, PixelLab takes the
9162
+ * 4x4 reading and cuts a native sheet into the wrong tiles.
9163
+ */
9164
+ async importTileset(args) {
9165
+ const body = {
9166
+ spritesheet: { type: "base64", base64: args.spritesheet.base64, format: args.spritesheet.format }
9167
+ };
9168
+ if (args.mode) body.tileset_mode = args.mode;
9169
+ if (args.tileSize != null) body.tile_size = { width: args.tileSize, height: args.tileSize };
9170
+ if (args.lowerDescription) body.lower_description = args.lowerDescription;
9171
+ if (args.upperDescription) body.upper_description = args.upperDescription;
9172
+ if (args.transitionDescription) body.transition_description = args.transitionDescription;
9173
+ if (args.name) body.name = args.name;
9174
+ return validateResponse(
9175
+ ImportTilesetSchema,
9176
+ await this.request("/tilesets/import", { method: "POST", body: JSON.stringify(body) }),
9177
+ "tilesets/import"
9178
+ );
9179
+ }
9180
+ /** `POST /tiles-pro/import`: 1 to 32 of your own tile PNGs as one completed tile group. Free. */
9181
+ async importTilesPro(args) {
9182
+ const body = {
9183
+ frames: args.frames.map((frame) => ({ type: "base64", base64: frame.base64, format: frame.format })),
9184
+ tile_type: args.tileType,
9185
+ tile_size: args.tileSize
9186
+ };
9187
+ if (args.description) body.description = args.description;
9188
+ if (args.tileView) body.tile_view = args.tileView;
9189
+ return validateResponse(
9190
+ ImportTilesProSchema,
9191
+ await this.request("/tiles-pro/import", { method: "POST", body: JSON.stringify(body) }),
9192
+ "tiles-pro/import"
9193
+ );
9194
+ }
9195
+ /**
9196
+ * `POST /save-to-asset`: write edited pixels back into a stored character
9197
+ * or object rotation, one direction of an animation, a gallery image or a
9198
+ * tileset sheet, or add a new gallery image (`gallery:new`). Free. The
9199
+ * image must match what it replaces in size and frame count. What was
9200
+ * there comes back as `previous_frames`; saving those again is the undo.
9201
+ */
9202
+ async saveToAsset(args) {
9203
+ const body = { target: args.target };
9204
+ if (args.image) body.image = { type: "base64", base64: args.image.base64, format: args.image.format };
9205
+ if (args.frames) body.frames = args.frames.map((frame) => ({ type: "base64", base64: frame.base64, format: frame.format }));
9206
+ if (args.name) body.name = args.name;
9207
+ if (args.description) body.description = args.description;
9208
+ return validateResponse(
9209
+ SaveToAssetSchema,
9210
+ await this.request("/save-to-asset", { method: "POST", body: JSON.stringify(body) }),
9211
+ "save-to-asset"
9212
+ );
9213
+ }
8981
9214
  /**
8982
9215
  * `POST /objects/{id}/expand-rotations`: draw the 7 missing directions of a
8983
9216
  * 1-direction object. The object then waits in `review-expansion` until
@@ -9522,27 +9755,64 @@ async function makeVfx(client2, opts) {
9522
9755
  }
9523
9756
  var VFX_ARTISTS = ["lite", "pro"];
9524
9757
  var VFX_ARTIST_MAX_SPRITE = 512;
9525
- function vfxArtistQuote(artist, sprite, change = false) {
9758
+ function vfxArtistQuote(artist, sprite, change = false, animated = false) {
9526
9759
  const table = {
9527
9760
  lite: { new: [1, 1, 3, 5], change: [1, 1, 2, 2] },
9528
9761
  pro: { new: [6, 8, 14, 28], change: [4, 4, 5, 8] }
9529
9762
  };
9530
9763
  const tier = sprite === "none" ? 0 : sprite === "unknown" ? 3 : sprite <= 128 ? 1 : sprite <= 256 ? 2 : 3;
9531
- return table[artist][change ? "change" : "new"][tier];
9764
+ const base = table[artist][change ? "change" : "new"][tier];
9765
+ return animated && tier > 0 ? base + VFX_ARTIST_ANIMATED_EXTRA[artist][tier - 1] : base;
9532
9766
  }
9767
+ var VFX_ARTIST_ANIMATED_EXTRA = { lite: [1, 1, 1], pro: [1, 2, 5] };
9768
+ var VFX_ARTIST_MAX_FRAMES = 32;
9769
+ var VFX_ARTIST_MAX_STRIP = 1024;
9533
9770
  function vfxArtistCeiling(quote) {
9534
9771
  return quote * 2;
9535
9772
  }
9536
- function vfxArtistSprite(bytes, label) {
9537
- const metadata = imageMetadata(bytes);
9538
- if (metadata?.format !== "png") throw new Error(`${label}: PixelLab's VFX artist takes a PNG sprite`);
9539
- const side = Math.max(metadata.width, metadata.height);
9773
+ function gifSize(bytes) {
9774
+ if (bytes.length < 10) return null;
9775
+ const magic = bytes.toString("ascii", 0, 6);
9776
+ if (magic !== "GIF87a" && magic !== "GIF89a") return null;
9777
+ return { width: bytes.readUInt16LE(6), height: bytes.readUInt16LE(8) };
9778
+ }
9779
+ function vfxArtistFrameSide(width, height, frames, label) {
9780
+ if (!Number.isInteger(frames) || frames < 1 || frames > VFX_ARTIST_MAX_FRAMES) {
9781
+ throw new Error(`${label}: a sprite strip holds 1 to ${VFX_ARTIST_MAX_FRAMES} frames, got ${frames}`);
9782
+ }
9783
+ if (width % frames !== 0) {
9784
+ throw new Error(`${label} is ${width}px wide, which does not divide into ${frames} equal frames`);
9785
+ }
9786
+ if (frames > 1 && width > VFX_ARTIST_MAX_STRIP) {
9787
+ throw new Error(
9788
+ `${label} is a ${width}px-wide strip; PixelLab's VFX artist takes a strip up to ${VFX_ARTIST_MAX_STRIP}px wide. Send fewer frames, or the animation as a GIF`
9789
+ );
9790
+ }
9791
+ const frameWidth = width / frames;
9792
+ const side = Math.max(frameWidth, height);
9540
9793
  if (side > VFX_ARTIST_MAX_SPRITE) {
9541
9794
  throw new Error(
9542
- `${label} is ${metadata.width}x${metadata.height}; PixelLab's VFX artist takes up to ${VFX_ARTIST_MAX_SPRITE}x${VFX_ARTIST_MAX_SPRITE} (crop or pad it; never rescale pixel art)`
9795
+ `${label} is ${frameWidth}x${height}${frames > 1 ? " a frame" : ""}; PixelLab's VFX artist takes up to ${VFX_ARTIST_MAX_SPRITE}x${VFX_ARTIST_MAX_SPRITE} (crop or pad it; never rescale pixel art)`
9543
9796
  );
9544
9797
  }
9545
- return { image: { base64: bytes.toString("base64"), format: "png" }, side };
9798
+ return side;
9799
+ }
9800
+ function vfxArtistSprite(bytes, label, frames = 1) {
9801
+ const gif = gifSize(bytes);
9802
+ if (gif) {
9803
+ if (frames !== 1) throw new Error(`${label} is a GIF, which brings its own frames; drop the frame count`);
9804
+ const side2 = Math.max(gif.width, gif.height);
9805
+ if (side2 > VFX_ARTIST_MAX_SPRITE) {
9806
+ throw new Error(
9807
+ `${label} is ${gif.width}x${gif.height}; PixelLab's VFX artist takes up to ${VFX_ARTIST_MAX_SPRITE}x${VFX_ARTIST_MAX_SPRITE} (crop or pad it; never rescale pixel art)`
9808
+ );
9809
+ }
9810
+ return { image: { base64: bytes.toString("base64"), format: "gif" }, side: side2, animated: true };
9811
+ }
9812
+ const metadata = imageMetadata(bytes);
9813
+ if (metadata?.format !== "png") throw new Error(`${label}: PixelLab's VFX artist takes a PNG or GIF sprite`);
9814
+ const side = vfxArtistFrameSide(metadata.width, metadata.height, frames, label);
9815
+ return { image: { base64: bytes.toString("base64"), format: "png" }, side, animated: frames > 1 };
9546
9816
  }
9547
9817
  function vfxArtistFiles(raw) {
9548
9818
  const urlOf = (value) => {
@@ -9627,7 +9897,7 @@ async function makeVfxWithArtist(client2, opts) {
9627
9897
  }
9628
9898
  const progress2 = opts.onProgress ?? (() => {
9629
9899
  });
9630
- const sprite = opts.sprite ? vfxArtistSprite(await readFile7(opts.sprite), opts.sprite).image : void 0;
9900
+ const sprite = opts.sprite ? vfxArtistSprite(await readFile7(opts.sprite), opts.sprite, opts.spriteFrames ?? 1).image : void 0;
9631
9901
  const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
9632
9902
  const interval = opts.intervalMs ?? 6e3;
9633
9903
  const timeout = opts.timeoutMs ?? 10 * 6e4;
@@ -9635,6 +9905,8 @@ async function makeVfxWithArtist(client2, opts) {
9635
9905
  description: opts.description,
9636
9906
  artist: opts.artist,
9637
9907
  sprite,
9908
+ spriteFrames: sprite ? opts.spriteFrames : void 0,
9909
+ spriteFps: sprite ? opts.spriteFps : void 0,
9638
9910
  effectId: opts.effect,
9639
9911
  conversation: opts.effect ? opts.conversation : void 0,
9640
9912
  name: opts.name,
@@ -9679,7 +9951,7 @@ async function makeVfxWithArtist(client2, opts) {
9679
9951
  written[key2] = target;
9680
9952
  }
9681
9953
  const facts = vfxArtistFrameFacts(result, atlas);
9682
- const usage = job.usage ?? null;
9954
+ const usage2 = job.usage ?? null;
9683
9955
  const provenance = {
9684
9956
  version: 1,
9685
9957
  provider: "pixellab",
@@ -9692,6 +9964,8 @@ async function makeVfxWithArtist(client2, opts) {
9692
9964
  message: result.message,
9693
9965
  source: {
9694
9966
  ...opts.sprite ? { sprite: path14.relative(path14.dirname(paths.provenance), path14.resolve(opts.sprite)).split(path14.sep).join("/") } : {},
9967
+ ...opts.sprite && opts.spriteFrames && opts.spriteFrames > 1 ? { spriteFrames: opts.spriteFrames } : {},
9968
+ ...opts.sprite && opts.spriteFps ? { spriteFps: opts.spriteFps } : {},
9695
9969
  ...opts.effect ? { changed: opts.effect } : {}
9696
9970
  },
9697
9971
  ...facts,
@@ -9703,7 +9977,7 @@ async function makeVfxWithArtist(client2, opts) {
9703
9977
  ["sheet", "gif", "atlas", "gamePack", "normals"].filter((key2) => written[key2]).map((key2) => [key2, path14.basename(written[key2])])
9704
9978
  ),
9705
9979
  quotedGenerations: submitted.quoted_generations ?? null,
9706
- usage,
9980
+ usage: usage2,
9707
9981
  conversation: result.conversation,
9708
9982
  exportedAt: (/* @__PURE__ */ new Date()).toISOString()
9709
9983
  };
@@ -9720,7 +9994,7 @@ async function makeVfxWithArtist(client2, opts) {
9720
9994
  loop: result.loop,
9721
9995
  anchor: result.anchor,
9722
9996
  quotedGenerations: submitted.quoted_generations ?? null,
9723
- usage,
9997
+ usage: usage2,
9724
9998
  paths: written
9725
9999
  };
9726
10000
  }
@@ -10034,8 +10308,9 @@ function pixelLabObjectUrl(generator, objectId) {
10034
10308
  }
10035
10309
  function vfxArtistSpecQuote(spec) {
10036
10310
  const sprite = spec.vfx?.sprite;
10037
- const side = !sprite ? "none" : "file" in sprite && sprite.width != null && sprite.height != null ? Math.max(sprite.width, sprite.height) : "unknown";
10038
- return vfxArtistQuote(spec.vfx?.artist ?? "lite", side);
10311
+ const frames = spec.vfx?.spriteFrames ?? 1;
10312
+ const side = !sprite ? "none" : "file" in sprite && sprite.width != null && sprite.height != null ? Math.max(Math.ceil(sprite.width / frames), sprite.height) : "unknown";
10313
+ return vfxArtistQuote(spec.vfx?.artist ?? "lite", side, false, frames > 1);
10039
10314
  }
10040
10315
  function workbenchVfxUrls(exported) {
10041
10316
  const sheetFile = exported.files.find((file) => /\.png$/i.test(file));
@@ -10046,12 +10321,12 @@ function workbenchVfxUrls(exported) {
10046
10321
  ...atlasFile ? { atlas: `${exported.downloadBase}${encodeURIComponent(atlasFile)}` } : {}
10047
10322
  };
10048
10323
  }
10049
- function billedFromUsage(usage) {
10050
- if (!usage) return null;
10051
- if (usage.type === "usd" || usage.type === void 0 && typeof usage.usd === "number") {
10052
- return typeof usage.usd === "number" ? { amount: usage.usd, unit: "usd" } : null;
10324
+ function billedFromUsage(usage2) {
10325
+ if (!usage2) return null;
10326
+ if (usage2.type === "usd" || usage2.type === void 0 && typeof usage2.usd === "number") {
10327
+ return typeof usage2.usd === "number" ? { amount: usage2.usd, unit: "usd" } : null;
10053
10328
  }
10054
- if (typeof usage.generations === "number") return { amount: usage.generations, unit: "generations" };
10329
+ if (typeof usage2.generations === "number") return { amount: usage2.generations, unit: "generations" };
10055
10330
  return null;
10056
10331
  }
10057
10332
  function characterCost(spec) {
@@ -10565,6 +10840,22 @@ var PixelLabProvider = class _PixelLabProvider {
10565
10840
  "high detail"
10566
10841
  ]);
10567
10842
  }
10843
+ if (spec.generator === "pixflux") {
10844
+ requirePixelLabOption("pixflux", "outline", spec.outline, [
10845
+ "single color black outline",
10846
+ "single color outline",
10847
+ "selective outline",
10848
+ "lineless"
10849
+ ]);
10850
+ requirePixelLabOption("pixflux", "shading", spec.shading, [
10851
+ "flat shading",
10852
+ "basic shading",
10853
+ "medium shading",
10854
+ "detailed shading",
10855
+ "highly detailed shading"
10856
+ ]);
10857
+ requirePixelLabOption("pixflux", "detail", spec.detail, ["low detail", "medium detail", "highly detailed"]);
10858
+ }
10568
10859
  if (spec.generator === "terrain") {
10569
10860
  if (spec.outline) {
10570
10861
  requirePixelLabOption("terrain", "outline", spec.outline, [
@@ -11536,6 +11827,9 @@ var PixelLabProvider = class _PixelLabProvider {
11536
11827
  height: spec.height,
11537
11828
  noBackground: spec.noBackground,
11538
11829
  paletteSwatchBase64: swatch,
11830
+ outline: spec.outline,
11831
+ shading: spec.shading,
11832
+ detail: spec.detail,
11539
11833
  seed: spec.seed,
11540
11834
  ...await initImageArgs(spec)
11541
11835
  });
@@ -11949,16 +12243,16 @@ var PixelLabProvider = class _PixelLabProvider {
11949
12243
  * member roles recorded so `pollCachedRevision` hands them back under the
11950
12244
  * same names the parent's set used.
11951
12245
  */
11952
- cacheCleanupResult(pngs, usage, roles, fps) {
12246
+ cacheCleanupResult(pngs, usage2, roles, fps) {
11953
12247
  const jobId = randomUUID3();
11954
12248
  if (!roles) {
11955
12249
  writeFileSync(path16.join(_PixelLabProvider.cacheDir(), `${jobId}.png`), pngs[0]);
11956
- return { jobId, metadata: { revisionUsage: usage } };
12250
+ return { jobId, metadata: { revisionUsage: usage2 } };
11957
12251
  }
11958
12252
  for (const [index, png] of pngs.entries()) {
11959
12253
  writeFileSync(path16.join(_PixelLabProvider.cacheDir(), `${jobId}-${index}.png`), png);
11960
12254
  }
11961
- return { jobId, metadata: { revisionUsage: usage, revisionMembers: roles, ...fps != null ? { revisionFps: fps } : {} } };
12255
+ return { jobId, metadata: { revisionUsage: usage2, revisionMembers: roles, ...fps != null ? { revisionFps: fps } : {} } };
11962
12256
  }
11963
12257
  /**
11964
12258
  * What a background job actually billed, once its own record is still
@@ -11971,8 +12265,8 @@ var PixelLabProvider = class _PixelLabProvider {
11971
12265
  try {
11972
12266
  const job = await this.client.getBackgroundJob(backgroundJobId);
11973
12267
  const nested = job.last_response?.billing_usage;
11974
- for (const usage of [job.usage, nested]) {
11975
- const billed = billedFromUsage(usage);
12268
+ for (const usage2 of [job.usage, nested]) {
12269
+ const billed = billedFromUsage(usage2);
11976
12270
  if (billed && !(billed.unit === "usd" && billed.amount === 0)) return billed;
11977
12271
  }
11978
12272
  return null;
@@ -12127,11 +12421,20 @@ var PixelLabProvider = class _PixelLabProvider {
12127
12421
  if (sha256(bytes) !== vfx.sprite.sha256) {
12128
12422
  throw new Error(`vfx sprite changed after the manifest was resolved: ${file}; run the command again`);
12129
12423
  }
12130
- sprite = vfxArtistSprite(bytes, `vfx sprite ${file}`).image;
12424
+ const taken = vfxArtistSprite(bytes, `vfx sprite ${file}`, vfx.spriteFrames ?? 1).image;
12425
+ if (taken.format !== "png") throw new Error(`vfx sprite must be a PNG: ${file}`);
12426
+ sprite = { base64: taken.base64, format: "png" };
12131
12427
  }
12132
12428
  const previous = context?.replacedMetadata?.vfx ?? context?.lastGenerationMetadata?.vfx;
12133
12429
  const artist = vfx.artist ?? "lite";
12134
- const submitted = await this.client.createVfx({ description: vfx.description, artist, sprite, name: vfx.name });
12430
+ const submitted = await this.client.createVfx({
12431
+ description: vfx.description,
12432
+ artist,
12433
+ sprite,
12434
+ spriteFrames: vfx.spriteFrames,
12435
+ spriteFps: vfx.spriteFps,
12436
+ name: vfx.name
12437
+ });
12135
12438
  return {
12136
12439
  jobId: submitted.background_job_id,
12137
12440
  metadata: {
@@ -12240,7 +12543,7 @@ var PixelLabProvider = class _PixelLabProvider {
12240
12543
  };
12241
12544
  }
12242
12545
  async pollCachedRevision(jobId, context) {
12243
- const usage = context?.metadata?.revisionUsage;
12546
+ const usage2 = context?.metadata?.revisionUsage;
12244
12547
  const roles = context?.metadata?.revisionMembers;
12245
12548
  const gone = {
12246
12549
  status: "failed",
@@ -12260,13 +12563,13 @@ var PixelLabProvider = class _PixelLabProvider {
12260
12563
  sourceUrl: sources[0].url,
12261
12564
  sources,
12262
12565
  ...frames && typeof fps === "number" ? { metadata: { frameSet: { fps, count: sources.length } } } : {},
12263
- billed: billedFromUsage(usage)
12566
+ billed: billedFromUsage(usage2)
12264
12567
  };
12265
12568
  }
12266
12569
  const file = path16.join(_PixelLabProvider.cacheDir(), `${jobId}.png`);
12267
12570
  if (!existsSync11(file)) return gone;
12268
12571
  const sourceUrl = `file://${file}`;
12269
- return { status: "ready", objectId: jobId, sourceUrl, sources: [{ url: sourceUrl }], billed: billedFromUsage(usage) };
12572
+ return { status: "ready", objectId: jobId, sourceUrl, sources: [{ url: sourceUrl }], billed: billedFromUsage(usage2) };
12270
12573
  }
12271
12574
  /**
12272
12575
  * A `normal-map` revision: a background job whose map is
@@ -12601,10 +12904,10 @@ var PixelLabProvider = class _PixelLabProvider {
12601
12904
  */
12602
12905
  async pollTerrain(tilesetId, context) {
12603
12906
  try {
12604
- const { tileset, usage, metadata } = await this.client.getTileset(tilesetId);
12907
+ const { tileset, usage: usage2, metadata } = await this.client.getTileset(tilesetId);
12605
12908
  const sidescroller = metadata.view === "side" || context?.spec?.terrainOrientation === "sidescroller";
12606
12909
  const backgroundJobId = context?.metadata?.backgroundJobId;
12607
- const billed = billedFromUsage(usage) ?? await this.billedForJob(backgroundJobId);
12910
+ const billed = billedFromUsage(usage2) ?? await this.billedForJob(backgroundJobId);
12608
12911
  const sources = [];
12609
12912
  const terrainTiles = [];
12610
12913
  for (const [index, tile] of tileset.tiles.entries()) {
@@ -12643,9 +12946,9 @@ var PixelLabProvider = class _PixelLabProvider {
12643
12946
  */
12644
12947
  async pollIsometricTile(tileId, context) {
12645
12948
  try {
12646
- const { image, usage } = await this.client.getIsometricTile(tileId);
12949
+ const { image, usage: usage2 } = await this.client.getIsometricTile(tileId);
12647
12950
  const backgroundJobId = context?.metadata?.backgroundJobId;
12648
- const billed = billedFromUsage(usage) ?? await this.billedForJob(backgroundJobId);
12951
+ const billed = billedFromUsage(usage2) ?? await this.billedForJob(backgroundJobId);
12649
12952
  const file = path16.join(_PixelLabProvider.cacheDir(), `${tileId}.png`);
12650
12953
  writeFileSync(file, Buffer.from(image.base64, "base64"));
12651
12954
  return {
@@ -13022,9 +13325,9 @@ var RetroDiffusionClient = class {
13022
13325
  if (!response.ok) throw new ProviderError("retrodiffusion", `Retro Diffusion download failed (${response.status})`, { status: response.status });
13023
13326
  return Buffer.from(await response.arrayBuffer());
13024
13327
  }
13025
- async call(path63, init = {}) {
13328
+ async call(path65, init = {}) {
13026
13329
  if (!this.token) throw new Error("RD_API_KEY is not set");
13027
- const response = await this.request(`${this.baseUrl}${path63}`, {
13330
+ const response = await this.request(`${this.baseUrl}${path65}`, {
13028
13331
  ...init,
13029
13332
  headers: {
13030
13333
  "Content-Type": "application/json",
@@ -15320,6 +15623,9 @@ async function resolveVfxShape(root, assetId, vfx, defaultName) {
15320
15623
  } else if (spriteRef) {
15321
15624
  const image = await optionalRevisionImage(spriteRef, `assets.${assetId}.vfx.sprite`, vfx.description ? "png" : void 0);
15322
15625
  sprite = { file: spriteRef, sha256: image?.hash ?? null, width: image?.width ?? null, height: image?.height ?? null, format: image?.format ?? null };
15626
+ if (image && vfx.description && (vfx.spriteFrames ?? 1) > 1) {
15627
+ vfxArtistFrameSide(image.width, image.height, vfx.spriteFrames, `assets.${assetId}.vfx.sprite`);
15628
+ }
15323
15629
  }
15324
15630
  return {
15325
15631
  ...vfx.preset ? { preset: vfx.preset } : {},
@@ -15329,7 +15635,10 @@ async function resolveVfxShape(root, assetId, vfx, defaultName) {
15329
15635
  ...vfx.fps !== void 0 ? { fps: vfx.fps } : {},
15330
15636
  // The artist caps a name at 80 characters; a long default is cut, not refused.
15331
15637
  name: vfx.name ?? (vfx.description ? defaultName.slice(0, 80) : defaultName),
15332
- ...vfx.description ? { description: vfx.description, artist: vfx.artist ?? "lite" } : {}
15638
+ ...vfx.description ? { description: vfx.description, artist: vfx.artist ?? "lite" } : {},
15639
+ // A strip of one frame is a still: it is sent, priced and hashed as one.
15640
+ ...vfx.spriteFrames !== void 0 && vfx.spriteFrames > 1 ? { spriteFrames: vfx.spriteFrames } : {},
15641
+ ...vfx.spriteFps !== void 0 ? { spriteFps: vfx.spriteFps } : {}
15333
15642
  };
15334
15643
  }
15335
15644
  async function optionalRevisionImage(file, label, requiredFormat) {
@@ -16172,10 +16481,10 @@ function isSha256Hash(value) {
16172
16481
  function parseCache(value) {
16173
16482
  return HashCacheSchema.parse(value);
16174
16483
  }
16175
- async function loadCache(path63) {
16176
- if (!existsSync17(path63)) return { version: 1, hashes: {} };
16484
+ async function loadCache(path65) {
16485
+ if (!existsSync17(path65)) return { version: 1, hashes: {} };
16177
16486
  try {
16178
- const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile12(path63, "utf8")));
16487
+ const parsed = HashCacheSchema.safeParse(JSON.parse(await readFile12(path65, "utf8")));
16179
16488
  if (!parsed.success) return { version: 1, hashes: {} };
16180
16489
  return {
16181
16490
  version: 1,
@@ -16187,18 +16496,18 @@ async function loadCache(path63) {
16187
16496
  return { version: 1, hashes: {} };
16188
16497
  }
16189
16498
  }
16190
- async function saveCache(path63, cache) {
16499
+ async function saveCache(path65, cache) {
16191
16500
  const sorted = {};
16192
16501
  for (const key2 of Object.keys(cache.hashes).sort()) {
16193
16502
  const hash = cache.hashes[key2];
16194
16503
  if (!isSha256Hash(hash)) throw new Error(`Refusing to cache invalid SHA-256 for ${key2}`);
16195
16504
  sorted[key2] = hash;
16196
16505
  }
16197
- await mkdir8(pathModule.dirname(pathModule.resolve(path63)), { recursive: true });
16198
- const tmp = `${path63}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
16506
+ await mkdir8(pathModule.dirname(pathModule.resolve(path65)), { recursive: true });
16507
+ const tmp = `${path65}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
16199
16508
  try {
16200
16509
  await writeFile8(tmp, JSON.stringify({ version: 1, hashes: sorted }, null, 2) + "\n");
16201
- await rename6(tmp, path63);
16510
+ await rename6(tmp, path65);
16202
16511
  } finally {
16203
16512
  await rm5(tmp, { force: true });
16204
16513
  }
@@ -19200,11 +19509,11 @@ function createGallerySkeletonHandlers(opts) {
19200
19509
  }
19201
19510
  };
19202
19511
  }
19203
- function billedAmount(usage) {
19204
- if (!usage || typeof usage !== "object") return null;
19205
- const { type } = usage;
19512
+ function billedAmount(usage2) {
19513
+ if (!usage2 || typeof usage2 !== "object") return null;
19514
+ const { type } = usage2;
19206
19515
  if (type !== "usd" && type !== "generations") return null;
19207
- const amount = usage[type];
19516
+ const amount = usage2[type];
19208
19517
  return typeof amount === "number" && Number.isFinite(amount) ? { unit: type, amount } : null;
19209
19518
  }
19210
19519
  async function createSkeletonAnimation(manifestPath, request) {
@@ -24866,6 +25175,9 @@ async function runVfx(args) {
24866
25175
  if (!args.out) throw new UsageError("vfx needs --out <base>: <base>.png, .gif, .json, and .vfx.json are written");
24867
25176
  if (args.description !== void 0) return runVfxArtist(args, args.out);
24868
25177
  if (args.artist) throw new UsageError("--artist picks who draws a vfx --description; add one");
25178
+ if (args.spriteFrames !== void 0 || args.spriteFps !== void 0) {
25179
+ throw new UsageError("--sprite-frames and --sprite-fps describe the sprite sent to PixelLab's VFX artist; add a --description");
25180
+ }
24869
25181
  const starts = [args.preset, args.recipe, args.effect].filter(Boolean);
24870
25182
  if (starts.length > 1) throw new UsageError("vfx takes one of --preset, --recipe, or --effect, not several");
24871
25183
  if (starts.length === 0 && args.parts.length === 0) {
@@ -24933,12 +25245,19 @@ async function runVfxArtist(args, out) {
24933
25245
  }
24934
25246
  if (args.name && args.name.length > 80) throw new UsageError("vfx --description takes a --name of at most 80 characters");
24935
25247
  const paths = vfxOutputPaths(out);
24936
- const side = args.sprite ? vfxArtistSprite(await readFile33(args.sprite), args.sprite).side : "none";
25248
+ if ((args.spriteFrames !== void 0 || args.spriteFps !== void 0) && !args.sprite) {
25249
+ throw new UsageError("--sprite-frames and --sprite-fps describe a --sprite; add one");
25250
+ }
25251
+ const taken = args.sprite ? vfxArtistSprite(await readFile33(args.sprite), args.sprite, args.spriteFrames ?? 1) : void 0;
25252
+ if (args.spriteFps !== void 0 && !taken?.animated) {
25253
+ throw new UsageError("--sprite-fps is the speed of an animated sprite: a GIF, or a PNG strip with --sprite-frames 2 or more");
25254
+ }
25255
+ const side = taken?.side ?? "none";
24937
25256
  const conversation = args.effect ? await readVfxConversation(paths.provenance, args.effect) : void 0;
24938
- const quote = vfxArtistQuote(artist, args.effect && !args.sprite ? "unknown" : side, Boolean(conversation));
25257
+ const quote = vfxArtistQuote(artist, args.effect && !args.sprite ? "unknown" : side, Boolean(conversation), Boolean(taken?.animated));
24939
25258
  const ceiling = vfxArtistCeiling(quote);
24940
25259
  log(
24941
- ` vfx by PixelLab's ${artist} artist: "${description}"${args.sprite ? ` around ${args.sprite}` : ""} \u2192 ${paths.sheet} (+ .gif, .json, .vfx.json${args.gamePack ? ", -game.zip" : ""})`
25260
+ ` vfx by PixelLab's ${artist} artist: "${description}"${args.sprite ? ` around ${args.sprite}` : ""}${taken?.animated ? taken.image.format === "gif" ? " (an animated GIF)" : ` (a strip of ${args.spriteFrames} frames)` : ""} \u2192 ${paths.sheet} (+ .gif, .json, .vfx.json${args.gamePack ? ", -game.zip" : ""})`
24942
25261
  );
24943
25262
  if (args.effect) {
24944
25263
  log(
@@ -24960,6 +25279,8 @@ async function runVfxArtist(args, out) {
24960
25279
  description,
24961
25280
  artist,
24962
25281
  sprite: args.sprite,
25282
+ spriteFrames: args.spriteFrames,
25283
+ spriteFps: args.spriteFps,
24963
25284
  effect: args.effect,
24964
25285
  conversation,
24965
25286
  name: args.name,
@@ -24982,8 +25303,8 @@ async function runVfxArtist(args, out) {
24982
25303
  for (const file of [res.paths.sheet, res.paths.gif, res.paths.atlas, res.paths.gamePack, res.paths.normals, res.paths.provenance]) {
24983
25304
  if (file) log(` wrote ${file}`);
24984
25305
  }
24985
- const usage = res.usage;
24986
- if (typeof usage?.generations === "number") log(` billed ${usage.generations} generations (quoted ${res.quotedGenerations ?? "?"})`);
25306
+ const usage2 = res.usage;
25307
+ if (typeof usage2?.generations === "number") log(` billed ${usage2.generations} generations (quoted ${res.quotedGenerations ?? "?"})`);
24987
25308
  if (res.editUrl) log(` tweak it with sliders: ${res.editUrl}`);
24988
25309
  log(` change it: pixelkiln vfx --description "<what to change>" --effect ${res.effectId} --out ${out} --force`);
24989
25310
  log(` render it again for free with the workbench: pixelkiln vfx --effect ${res.effectId} --out <base>`);
@@ -25105,7 +25426,7 @@ async function generateMusic(client2, opts) {
25105
25426
  if (!opts.force) {
25106
25427
  for (const file of writes) if (existsSync40(file)) throw new Error(`${file} already exists; pass --force to replace it`);
25107
25428
  }
25108
- const usage = [];
25429
+ const usage2 = [];
25109
25430
  let quoted = null;
25110
25431
  let takes = [];
25111
25432
  let source;
@@ -25128,7 +25449,7 @@ async function generateMusic(client2, opts) {
25128
25449
  const made = await collectTakes(client2, submitted.songs, paths.takes, "song", opts);
25129
25450
  takes = made.takes;
25130
25451
  source = made.finished[0];
25131
- usage.push(await billedUsage(client2, submitted.background_job_id));
25452
+ usage2.push(await billedUsage(client2, submitted.background_job_id));
25132
25453
  }
25133
25454
  let loops = [];
25134
25455
  const snapshot = () => ({
@@ -25139,7 +25460,7 @@ async function generateMusic(client2, opts) {
25139
25460
  instrumental: source?.instrumental ?? instrumental,
25140
25461
  lyrics: source?.lyrics ?? opts.lyrics ?? "",
25141
25462
  quotedGenerations: quoted,
25142
- usage
25463
+ usage: usage2
25143
25464
  });
25144
25465
  const relative = (take) => ({ ...take, file: path50.basename(take.file) });
25145
25466
  const writeRecord = async (result2) => {
@@ -25191,7 +25512,7 @@ async function generateMusic(client2, opts) {
25191
25512
  const made = await collectTakes(client2, submitted.songs, paths.loops, "loop", opts);
25192
25513
  loops = made.takes;
25193
25514
  source ??= made.finished[0];
25194
- usage.push(await billedUsage(client2, submitted.background_job_id));
25515
+ usage2.push(await billedUsage(client2, submitted.background_job_id));
25195
25516
  }
25196
25517
  const result = snapshot();
25197
25518
  await writeRecord(result);
@@ -25690,11 +26011,12 @@ async function runUi(args) {
25690
26011
  }
25691
26012
 
25692
26013
  // src/cli/commands/asset.ts
26014
+ import { readFile as readFile36 } from "fs/promises";
25693
26015
  import path55 from "path";
25694
26016
 
25695
26017
  // src/pixellab-assets.ts
25696
26018
  import { existsSync as existsSync42 } from "fs";
25697
- import { mkdir as mkdir18, readFile as readFile35, writeFile as writeFile23 } from "fs/promises";
26019
+ import { mkdir as mkdir18, readdir as readdir3, readFile as readFile35, stat as stat5, writeFile as writeFile23 } from "fs/promises";
25698
26020
  import path54 from "path";
25699
26021
  var ASSET_KINDS = ["object", "character"];
25700
26022
  var EXPORT_FORMATS = ["zip", "spritesheet", "aseprite", "gif"];
@@ -25753,13 +26075,13 @@ async function expandObject(client2, id, opts) {
25753
26075
  opts.onProgress?.(status);
25754
26076
  if (status === "failed") throw new Error(`PixelLab could not expand object ${id}`);
25755
26077
  if (status !== "expanding") {
25756
- let usage = null;
26078
+ let usage2 = null;
25757
26079
  try {
25758
- usage = (await client2.getBackgroundJob(submitted.background_job_id)).usage ?? null;
26080
+ usage2 = (await client2.getBackgroundJob(submitted.background_job_id)).usage ?? null;
25759
26081
  } catch {
25760
- usage = null;
26082
+ usage2 = null;
25761
26083
  }
25762
- return { objectId: id, jobId: submitted.background_job_id, minGenerations: submitted.min_generations, maxGenerations: submitted.max_generations, status, usage };
26084
+ return { objectId: id, jobId: submitted.background_job_id, minGenerations: submitted.min_generations, maxGenerations: submitted.max_generations, status, usage: usage2 };
25763
26085
  }
25764
26086
  if (Date.now() - started > timeout) {
25765
26087
  throw new Error(`object ${id} is still expanding after ${Math.round(timeout / 1e3)} s; it keeps running upstream, and asset expand --keep or --discard finishes it later`);
@@ -25787,6 +26109,171 @@ async function pullExpansionReview(client2, id, opts) {
25787
26109
  }
25788
26110
  return { dir, existingDirection: review.existing_direction ?? null, files };
25789
26111
  }
26112
+ var TILESET_MODES = ["topdown", "sidescroller"];
26113
+ var IMPORT_TILE_TYPES = ["square_topdown", "isometric", "oblique", "hex", "hex_pointy", "octagon"];
26114
+ var SHEET_TILE_SIZES = [16, 24, 32, 48, 64];
26115
+ var IMPORT_MAX_TILES = 32;
26116
+ function tilesetSheetReadings(width, height) {
26117
+ if (height !== width && height !== width * 2) return [];
26118
+ const readings = [];
26119
+ if (SHEET_TILE_SIZES.includes(width / 4)) readings.push({ tileSize: width / 4, layout: "compact" });
26120
+ if (SHEET_TILE_SIZES.includes(width / 8)) readings.push({ tileSize: width / 8, layout: "native" });
26121
+ return readings;
26122
+ }
26123
+ function chooseTilesetSheetReading(file, width, height, tileSize) {
26124
+ const readings = tilesetSheetReadings(width, height);
26125
+ const describe = (reading) => `${reading.tileSize}px tiles (${reading.layout === "compact" ? "4 wide" : "8 wide"})`;
26126
+ if (readings.length === 0) {
26127
+ throw new Error(
26128
+ `${file} is ${width}x${height}, not a PixelLab tileset sheet: it takes a square sheet 4 or 8 tiles wide (or twice as tall, for a set with transitions) of 16, 24, 32, 48 or 64px tiles`
26129
+ );
26130
+ }
26131
+ if (tileSize === void 0) {
26132
+ if (readings.length > 1) {
26133
+ throw new Error(
26134
+ `${file} is ${width}x${height}, which reads as ${readings.map(describe).join(" or ")}; say which with --size ${readings.map((reading) => reading.tileSize).join(" or --size ")}`
26135
+ );
26136
+ }
26137
+ return readings[0];
26138
+ }
26139
+ const chosen = readings.find((reading) => reading.tileSize === tileSize);
26140
+ if (!chosen) throw new Error(`${file} is ${width}x${height}, which holds ${readings.map(describe).join(" or ")}, not ${tileSize}px tiles`);
26141
+ return chosen;
26142
+ }
26143
+ function readPng(bytes, file) {
26144
+ const metadata = imageMetadata(bytes);
26145
+ if (!metadata || metadata.format !== "png") throw new Error(`${file} is not a PNG`);
26146
+ return metadata;
26147
+ }
26148
+ async function importTilesetFile(client2, file, opts = {}) {
26149
+ const bytes = await readFile35(file);
26150
+ const { width, height } = readPng(bytes, file);
26151
+ const reading = chooseTilesetSheetReading(file, width, height, opts.tileSize);
26152
+ const mode2 = opts.mode ?? "topdown";
26153
+ if (mode2 === "sidescroller" && opts.upperDescription) throw new Error("a sidescroller tileset has one terrain, the platform; drop the upper description");
26154
+ const res = await client2.importTileset({
26155
+ spritesheet: { base64: bytes.toString("base64"), format: "png" },
26156
+ mode: mode2,
26157
+ // PixelLab cannot be told 48, and a 4-wide reading is the one it takes unprompted.
26158
+ tileSize: reading.tileSize === 48 ? void 0 : reading.tileSize,
26159
+ lowerDescription: opts.lowerDescription,
26160
+ upperDescription: opts.upperDescription,
26161
+ transitionDescription: opts.transitionDescription,
26162
+ name: opts.name
26163
+ });
26164
+ return { tilesetId: res.tileset_id, mode: mode2, tileSize: reading.tileSize, layout: reading.layout };
26165
+ }
26166
+ async function pngFilesAt(from) {
26167
+ if (!existsSync42(from)) throw new Error(`${from} does not exist`);
26168
+ if (!(await stat5(from)).isDirectory()) return [from];
26169
+ const names = (await readdir3(from)).filter((name) => /\.png$/i.test(name)).sort((a, b) => a.localeCompare(b, void 0, { numeric: true }));
26170
+ if (names.length === 0) throw new Error(`${from} holds no PNG files`);
26171
+ return names.map((name) => path54.join(from, name));
26172
+ }
26173
+ function importTileHeights(tileType, tileSize) {
26174
+ if (tileType === "square_topdown" || tileType === "octagon") return { min: tileSize, max: tileSize };
26175
+ if (tileType === "oblique") return { min: tileSize, max: tileSize * 2 };
26176
+ return { min: tileSize / 2, max: tileSize * 2 };
26177
+ }
26178
+ async function importTilesFiles(client2, from, opts) {
26179
+ if (!IMPORT_TILE_TYPES.includes(opts.tileType)) throw new Error(`tile type must be one of ${IMPORT_TILE_TYPES.join(", ")}`);
26180
+ if (!Number.isInteger(opts.tileSize) || opts.tileSize < 16 || opts.tileSize > 256) throw new Error("tile size is a whole number from 16 to 256");
26181
+ const files = await pngFilesAt(from);
26182
+ if (files.length > IMPORT_MAX_TILES) throw new Error(`${from} holds ${files.length} PNGs; PixelLab imports at most ${IMPORT_MAX_TILES} tiles in one group`);
26183
+ const heights = importTileHeights(opts.tileType, opts.tileSize);
26184
+ const frames = [];
26185
+ for (const file of files) {
26186
+ const bytes = await readFile35(file);
26187
+ const { width, height } = readPng(bytes, file);
26188
+ if (width !== opts.tileSize || height < heights.min || height > heights.max) {
26189
+ const tall = heights.min === heights.max ? `${heights.min}` : `${heights.min} to ${heights.max}`;
26190
+ throw new Error(`${file} is ${width}x${height}; a ${opts.tileSize}px ${opts.tileType} tile is ${opts.tileSize} wide and ${tall} tall`);
26191
+ }
26192
+ frames.push({ base64: bytes.toString("base64"), format: "png" });
26193
+ }
26194
+ const res = await client2.importTilesPro({ frames, tileType: opts.tileType, tileSize: opts.tileSize, description: opts.description, tileView: opts.tileView });
26195
+ return { tileId: res.tile_id, tiles: files.length, files };
26196
+ }
26197
+ function checkSaveTarget(target) {
26198
+ if (!/^(character:[^:]+:[^:]+(:[^:]+)?|object:[^:]+(:[^:]+){0,2}|gallery:[^:]+|tileset:[^:]+)$/.test(target)) {
26199
+ throw new Error(
26200
+ `--target "${target}" is not a place PixelLab can save to. Use character:<id>:<direction>, object:<id>[:<direction>], either with :<animation group id> added, gallery:<id>, gallery:new, or tileset:<id>`
26201
+ );
26202
+ }
26203
+ }
26204
+ function saveUndoDir(target, now = /* @__PURE__ */ new Date()) {
26205
+ const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
26206
+ return path54.resolve("pixelkiln-undo", `${target.replace(/[^a-zA-Z0-9-]+/g, "_")}-${stamp}`);
26207
+ }
26208
+ async function writeUndo(frames, dir) {
26209
+ await mkdir18(dir, { recursive: true });
26210
+ const files = [];
26211
+ for (const [index, frame] of frames.entries()) {
26212
+ const file = path54.join(dir, frames.length === 1 ? "previous.png" : `previous-${String(index).padStart(2, "0")}.png`);
26213
+ await writeFile23(file, Buffer.from(frame.base64, "base64"));
26214
+ files.push(file);
26215
+ }
26216
+ return files;
26217
+ }
26218
+ async function saveToAssetFile(client2, target, from, opts = {}) {
26219
+ checkSaveTarget(target);
26220
+ if ((opts.name || opts.description) && target !== "gallery:new") throw new Error("a name and a description belong to a new gallery image: --target gallery:new");
26221
+ const files = await pngFilesAt(from).catch(async (error) => {
26222
+ if (existsSync42(from) && /\.gif$/i.test(from)) return [from];
26223
+ throw error;
26224
+ });
26225
+ let image;
26226
+ let frames;
26227
+ if (files.length === 1) {
26228
+ const bytes = await readFile35(files[0]);
26229
+ const gif = bytes.subarray(0, 4).toString("ascii") === "GIF8";
26230
+ if (!gif) readPng(bytes, files[0]);
26231
+ image = { base64: bytes.toString("base64"), format: gif ? "gif" : "png" };
26232
+ } else {
26233
+ if (files.length > 128) throw new Error(`${from} holds ${files.length} PNGs; PixelLab takes at most 128 frames`);
26234
+ let size;
26235
+ frames = [];
26236
+ for (const file of files) {
26237
+ const bytes = await readFile35(file);
26238
+ const { width, height } = readPng(bytes, file);
26239
+ if (size && size !== `${width}x${height}`) throw new Error(`${file} is ${width}x${height}, but the frames before it are ${size}; an animation's frames share one size`);
26240
+ size = `${width}x${height}`;
26241
+ frames.push({ base64: bytes.toString("base64"), format: "png" });
26242
+ }
26243
+ }
26244
+ const undoDir = opts.undoDir ? path54.resolve(opts.undoDir) : saveUndoDir(target);
26245
+ let res;
26246
+ try {
26247
+ res = await client2.saveToAsset({ target, image, frames, name: opts.name, description: opts.description });
26248
+ } catch (error) {
26249
+ if (error instanceof PixelLabError && error.body.startsWith("{")) {
26250
+ let previous;
26251
+ try {
26252
+ previous = JSON.parse(error.body).detail?.previous_frames;
26253
+ } catch {
26254
+ previous = void 0;
26255
+ }
26256
+ if (Array.isArray(previous) && previous.length && previous.every((frame) => typeof frame?.base64 === "string")) {
26257
+ const written = await writeUndo(previous, undoDir);
26258
+ throw new Error(`${error.message}. The save failed partway; what was stored before is in ${undoDir} (${written.length} frame(s)). Save it back to ${target} to restore it`);
26259
+ }
26260
+ }
26261
+ throw error;
26262
+ }
26263
+ const undo = res.action === "saved" && res.previous_frames?.length ? await writeUndo(res.previous_frames, undoDir) : [];
26264
+ return {
26265
+ action: res.action,
26266
+ target: res.target,
26267
+ kind: res.kind,
26268
+ width: res.width,
26269
+ height: res.height,
26270
+ frames: res.frame_count,
26271
+ changedPixels: res.changed_pixels,
26272
+ undo,
26273
+ note: res.note ?? null,
26274
+ maps: res.maps ?? null
26275
+ };
26276
+ }
25790
26277
 
25791
26278
  // src/cli/commands/asset.ts
25792
26279
  function loadKeys4(args) {
@@ -25804,7 +26291,16 @@ function requireId2(args) {
25804
26291
  }
25805
26292
  async function runAsset(args) {
25806
26293
  const emit = (value) => log(JSON.stringify({ version: 1, ...value }, null, 2));
26294
+ if (args.subcommand === "import" && (args.kind === "tileset" || args.kind === "tiles")) {
26295
+ await runTileImport(args, emit);
26296
+ return;
26297
+ }
26298
+ if (args.subcommand === "save") {
26299
+ await runSave(args, emit);
26300
+ return;
26301
+ }
25807
26302
  if (args.subcommand === "import") {
26303
+ if (args.kind && args.kind !== "object") throw new UsageError(`asset import takes --kind object (the default), tileset or tiles, got "${args.kind}"`);
25808
26304
  if (!args.from) throw new UsageError("asset import needs --from <png>: your own sprite, at most 256x256");
25809
26305
  if (args.dryRun) {
25810
26306
  log(` would import ${args.from} as a 1-direction object; nothing sent`);
@@ -25925,21 +26421,447 @@ async function runAsset(args) {
25925
26421
  if (args.json) emit({ ...res, format });
25926
26422
  else log(` wrote ${res.out} (${format}, ${res.bytes} bytes, free)`);
25927
26423
  }
26424
+ function tileSizeOf(args) {
26425
+ if (args.size === void 0) return void 0;
26426
+ if (!/^\d+$/.test(args.size.trim())) throw new UsageError(`--size is the tile size in pixels for a tile import, e.g. --size 32; got "${args.size}"`);
26427
+ return Number(args.size);
26428
+ }
26429
+ async function usage(work) {
26430
+ try {
26431
+ return await work();
26432
+ } catch (error) {
26433
+ if (error instanceof Error && !(error instanceof UsageError) && error.name === "Error") throw new UsageError(error.message);
26434
+ throw error;
26435
+ }
26436
+ }
26437
+ async function runTileImport(args, emit) {
26438
+ const tileSize = tileSizeOf(args);
26439
+ if (args.kind === "tileset") {
26440
+ if (!args.from) throw new UsageError("asset import --kind tileset needs --from <png>: a Wang sheet in PixelLab's layout");
26441
+ const mode2 = args.mode ?? "topdown";
26442
+ if (!TILESET_MODES.includes(mode2)) throw new UsageError(`--mode must be ${TILESET_MODES.join(" or ")} for a tileset import, got "${args.mode}"`);
26443
+ if (args.tileType) throw new UsageError("--tile-type belongs to --kind tiles; a tileset is a Wang sheet");
26444
+ const opts2 = { mode: mode2, tileSize, lowerDescription: args.lower, upperDescription: args.upper, transitionDescription: args.transition, name: args.name };
26445
+ if (args.dryRun) {
26446
+ const metadata = imageMetadata(await readFile36(args.from));
26447
+ if (!metadata || metadata.format !== "png") throw new UsageError(`${args.from} is not a PNG`);
26448
+ const reading = await usage(() => chooseTilesetSheetReading(args.from, metadata.width, metadata.height, tileSize));
26449
+ log(` would import ${args.from} as a ${mode2} tileset of ${reading.tileSize}px tiles (${reading.layout === "compact" ? "4 wide" : "8 wide"}); nothing sent`);
26450
+ return;
26451
+ }
26452
+ loadKeys4(args);
26453
+ const client3 = clientFromEnv();
26454
+ const res2 = await usage(() => importTilesetFile(client3, args.from, opts2));
26455
+ if (args.json) emit(res2);
26456
+ else log(` imported ${args.from} as ${mode2} tileset ${res2.tilesetId} (${res2.tileSize}px tiles, ${res2.layout === "compact" ? "4 wide" : "8 wide"}, free)`);
26457
+ return;
26458
+ }
26459
+ if (!args.from) throw new UsageError("asset import --kind tiles needs --from <png or directory>: one PNG per tile, up to 32");
26460
+ if (!args.tileType || !IMPORT_TILE_TYPES.includes(args.tileType)) {
26461
+ throw new UsageError(`asset import --kind tiles needs --tile-type, one of ${IMPORT_TILE_TYPES.join(", ")}`);
26462
+ }
26463
+ if (tileSize === void 0) throw new UsageError("asset import --kind tiles needs --size <pixels>: the tiles' width, 16 to 256");
26464
+ if (args.lower || args.upper || args.transition) throw new UsageError("--lower, --upper and --transition describe a tileset; describe tiles with --description");
26465
+ const opts = { tileType: args.tileType, tileSize, description: args.description };
26466
+ if (args.dryRun) {
26467
+ const res2 = await usage(() => importTilesFiles({ importTilesPro: async () => ({ tile_id: "dry-run", status: "completed" }) }, args.from, opts));
26468
+ log(` would import ${res2.tiles} ${args.tileType} tile(s) of ${tileSize}px from ${args.from} as one group; nothing sent`);
26469
+ return;
26470
+ }
26471
+ loadKeys4(args);
26472
+ const client2 = clientFromEnv();
26473
+ const res = await usage(() => importTilesFiles(client2, args.from, opts));
26474
+ if (args.json) emit(res);
26475
+ else log(` imported ${res.tiles} tile(s) from ${args.from} as tile group ${res.tileId} (${args.tileType}, ${tileSize}px, free)`);
26476
+ }
26477
+ async function runSave(args, emit) {
26478
+ const target = args.saveTarget;
26479
+ if (!target) {
26480
+ throw new UsageError("asset save needs --target: character:<id>:<direction>, object:<id>[:<direction>], gallery:<id>, gallery:new, or tileset:<id>");
26481
+ }
26482
+ if (!args.from) throw new UsageError("asset save needs --from: a PNG, an animated GIF, or a directory of PNG frames");
26483
+ await usage(() => checkSaveTarget(target));
26484
+ const adding = target === "gallery:new";
26485
+ const undoDir = args.out ? path55.resolve(args.out) : saveUndoDir(target);
26486
+ if (adding) log(` add ${args.from} to your PixelLab gallery as a new image (free)`);
26487
+ else {
26488
+ log(` save ${args.from} over ${target} on PixelLab (free)`);
26489
+ log(` it must match what is stored in size and frame count; what it replaces is written to ${undoDir}`);
26490
+ }
26491
+ if (args.dryRun) {
26492
+ log(" dry run: nothing sent");
26493
+ return;
26494
+ }
26495
+ if (!adding && !await confirm(` Replace the stored pixels of ${target}?`, args.yes)) return;
26496
+ loadKeys4(args);
26497
+ const client2 = clientFromEnv();
26498
+ const res = await usage(() => saveToAssetFile(client2, target, args.from, { name: args.name, description: args.description, undoDir }));
26499
+ if (args.json) {
26500
+ emit({ ...res });
26501
+ return;
26502
+ }
26503
+ if (res.action === "unchanged") log(` ${res.target}: no pixel differed, nothing written`);
26504
+ else if (res.action === "added") log(` added as ${res.target} (${res.width}x${res.height})`);
26505
+ else {
26506
+ log(` ${res.target}: ${res.kind} saved, ${res.width}x${res.height}, ${res.frames} frame(s), ${res.changedPixels} pixel(s) changed`);
26507
+ for (const file of res.undo) log(` kept the old pixels: ${file}`);
26508
+ if (res.undo.length) log(` undo: pixelkiln asset save --target ${res.target} --from ${res.undo.length === 1 ? res.undo[0] : path55.dirname(res.undo[0])} --yes`);
26509
+ }
26510
+ if (res.note) log(` ${res.note}`);
26511
+ if (res.maps) log(` ${res.maps}`);
26512
+ }
25928
26513
 
25929
- // src/cli/commands/quality.ts
26514
+ // src/cli/commands/talk.ts
26515
+ import { existsSync as existsSync44 } from "fs";
26516
+ import { mkdir as mkdir20, readFile as readFile38, writeFile as writeFile25 } from "fs/promises";
25930
26517
  import path57 from "path";
25931
- import { readFile as readFile37 } from "fs/promises";
25932
26518
 
25933
- // src/pipeline/quality-regression.ts
25934
- import path56 from "path";
26519
+ // src/pixellab-talk.ts
25935
26520
  import { existsSync as existsSync43 } from "fs";
25936
- import { readFile as readFile36 } from "fs/promises";
26521
+ import { mkdir as mkdir19, readFile as readFile37, writeFile as writeFile24 } from "fs/promises";
26522
+ import path56 from "path";
26523
+ var TALK_MOODS = ["neutral", "happy", "angry", "sad", "surprised"];
26524
+ var VISEME_COUNTS = [3, 5, 7, 12];
26525
+ var VISEME_ENGINES = ["v3", "pixminimax"];
26526
+ var PORTRAIT_MAX_SIDE = 256;
26527
+ var TALK_MAX_TEXT = 500;
26528
+ function visemeCost(engine, side, count) {
26529
+ const forSeven = engine === "pixminimax" ? 3 : side === "unknown" || side > 128 ? 24 : side > 64 ? 6 : 3;
26530
+ return Math.ceil(forSeven * count / 7);
26531
+ }
26532
+ function talkOutputPaths(out) {
26533
+ const base = path56.resolve(out.replace(/\.(png|json)$/i, "").replace(/\.(talk|visemes)$/i, ""));
26534
+ return { strip: `${base}.visemes.png`, record: `${base}.talk.json` };
26535
+ }
26536
+ function readPortrait(bytes, label) {
26537
+ const metadata = imageMetadata(bytes);
26538
+ if (metadata?.format !== "png") throw new Error(`${label} is not a PNG`);
26539
+ const side = Math.max(metadata.width, metadata.height);
26540
+ if (side > PORTRAIT_MAX_SIDE) {
26541
+ throw new Error(`${label} is ${metadata.width}x${metadata.height}; a portrait is at most ${PORTRAIT_MAX_SIDE}x${PORTRAIT_MAX_SIDE} (crop it; never rescale pixel art)`);
26542
+ }
26543
+ return { base64: bytes.toString("base64"), side };
26544
+ }
26545
+ function joinStrip(cells) {
26546
+ const decoded = cells.map((cell) => decodePng(cell));
26547
+ const { width, height } = decoded[0];
26548
+ if (decoded.some((cell) => cell.width !== width || cell.height !== height)) throw new Error("PixelLab's mouth positions came back in different sizes");
26549
+ const out = Buffer.alloc(width * decoded.length * height * 4);
26550
+ for (const [index, cell] of decoded.entries()) {
26551
+ for (let y = 0; y < height; y++) {
26552
+ Buffer.from(cell.pixels.buffer, cell.pixels.byteOffset + y * width * 4, width * 4).copy(out, (y * width * decoded.length + index * width) * 4);
26553
+ }
26554
+ }
26555
+ return { png: encodeRgbaPng(width * decoded.length, height, out), width, height };
26556
+ }
26557
+ function cutStrip(strip, columns, cell, row = 0) {
26558
+ const sheet = decodePng(strip);
26559
+ if (sheet.width !== cell.width * columns || sheet.height < cell.height * (row + 1)) {
26560
+ throw new Error(`the mouth-position strip is ${sheet.width}x${sheet.height}, not ${columns} cells of ${cell.width}x${cell.height}; it was changed after it was made`);
26561
+ }
26562
+ const pixels = Buffer.from(sheet.pixels.buffer, sheet.pixels.byteOffset, sheet.pixels.byteLength);
26563
+ return Array.from({ length: columns }, (_, index) => {
26564
+ const out = Buffer.alloc(cell.width * cell.height * 4);
26565
+ for (let y = 0; y < cell.height; y++) {
26566
+ pixels.copy(out, y * cell.width * 4, ((row * cell.height + y) * sheet.width + index * cell.width) * 4, ((row * cell.height + y) * sheet.width + (index + 1) * cell.width) * 4);
26567
+ }
26568
+ return encodeRgbaPng(cell.width, cell.height, out);
26569
+ });
26570
+ }
26571
+ async function makeVisemes(client2, opts) {
26572
+ if (Boolean(opts.portrait) === Boolean(opts.characterId)) throw new Error("give a portrait file or a character id, not both");
26573
+ const paths = talkOutputPaths(opts.out);
26574
+ if (!opts.force) {
26575
+ for (const file of [paths.strip, paths.record]) if (existsSync43(file)) throw new Error(`${file} already exists; pass --force to replace it`);
26576
+ }
26577
+ const progress2 = opts.onProgress ?? (() => {
26578
+ });
26579
+ const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
26580
+ const interval = opts.intervalMs ?? 8e3;
26581
+ const timeout = opts.timeoutMs ?? 10 * 6e4;
26582
+ const portrait = opts.portrait ? readPortrait(await readFile37(opts.portrait), opts.portrait) : void 0;
26583
+ const engine = opts.engine ?? "v3";
26584
+ const visemeCount = opts.visemeCount ?? 7;
26585
+ const submitted = await client2.createVocalAnimation({
26586
+ portrait: portrait ? { base64: portrait.base64, format: "png" } : void 0,
26587
+ characterId: opts.characterId,
26588
+ mood: opts.mood,
26589
+ visemeCount,
26590
+ engine,
26591
+ seed: opts.seed
26592
+ });
26593
+ const jobId = submitted.background_job_id;
26594
+ progress2(`submitted job ${jobId}`);
26595
+ const started = Date.now();
26596
+ let job;
26597
+ for (; ; ) {
26598
+ job = await client2.getVocalAnimation(jobId);
26599
+ if (job.status === "completed") break;
26600
+ if (job.status === "failed") throw new Error(`PixelLab vocal-animation job ${jobId} failed upstream`);
26601
+ if (Date.now() - started > timeout) {
26602
+ throw new Error(`PixelLab vocal-animation job ${jobId} is still ${job.status} after ${Math.round(timeout / 1e3)} s; it keeps running upstream, but this command has stopped waiting`);
26603
+ }
26604
+ progress2(`${job.completed_visemes.length} of ${visemeCount} mouth positions`);
26605
+ await sleep3(interval);
26606
+ }
26607
+ let strip;
26608
+ let visemeOrder;
26609
+ let cell;
26610
+ if (job.visemes) {
26611
+ visemeOrder = job.completed_visemes.filter((id) => job.visemes[id]);
26612
+ if (visemeOrder.length !== Object.keys(job.visemes).length) visemeOrder = Object.keys(job.visemes);
26613
+ const joined = joinStrip(visemeOrder.map((id) => Buffer.from(job.visemes[id].base64, "base64")));
26614
+ strip = joined.png;
26615
+ cell = { width: joined.width, height: joined.height };
26616
+ } else if (job.grid_url && job.viseme_order?.length) {
26617
+ strip = await client2.download(job.grid_url);
26618
+ visemeOrder = job.viseme_order;
26619
+ const sheet = imageMetadata(strip);
26620
+ if (!sheet) throw new Error(`PixelLab's mouth-position sheet for job ${jobId} is not a readable image`);
26621
+ const rows = Math.max(1, job.moods_on_character?.length ?? 1);
26622
+ cell = { width: sheet.width / visemeOrder.length, height: sheet.height / rows };
26623
+ } else {
26624
+ throw new Error(`PixelLab vocal-animation job ${jobId} finished with no mouth positions and no spritesheet`);
26625
+ }
26626
+ const usage2 = (await client2.getBackgroundJob(jobId).catch(() => null))?.usage ?? job.usage ?? null;
26627
+ await mkdir19(path56.dirname(paths.strip), { recursive: true });
26628
+ await writeFile24(paths.strip, strip);
26629
+ const record = {
26630
+ version: 1,
26631
+ provider: "pixellab",
26632
+ tool: "vocal-animation",
26633
+ engine,
26634
+ mood: job.mood ?? opts.mood ?? "neutral",
26635
+ visemeCount,
26636
+ visemeOrder,
26637
+ cell,
26638
+ strip: path56.basename(paths.strip),
26639
+ source: opts.portrait ? { portrait: path56.relative(path56.dirname(paths.record), path56.resolve(opts.portrait)).split(path56.sep).join("/") } : { characterId: opts.characterId },
26640
+ ...job.moods_on_character ? { moodsOnCharacter: job.moods_on_character } : {},
26641
+ jobId,
26642
+ usage: usage2,
26643
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
26644
+ };
26645
+ await writeFile24(paths.record, `${JSON.stringify(record, null, 2)}
26646
+ `);
26647
+ return { ...record, paths };
26648
+ }
26649
+ async function readTalkRecord(file) {
26650
+ let record;
26651
+ try {
26652
+ record = JSON.parse(await readFile37(file, "utf8"));
26653
+ } catch (error) {
26654
+ throw new Error(`${file} is not a readable .talk.json record: ${error instanceof Error ? error.message : String(error)}`);
26655
+ }
26656
+ if (record?.tool !== "vocal-animation" || !Array.isArray(record.visemeOrder) || !record.cell || !record.strip) {
26657
+ throw new Error(`${file} is not a .talk.json record from pixelkiln talk visemes`);
26658
+ }
26659
+ const stripFile = path56.resolve(path56.dirname(path56.resolve(file)), record.strip);
26660
+ if (!existsSync43(stripFile)) throw new Error(`${file} names ${record.strip}, which is missing beside it`);
26661
+ const row = Math.max(0, record.moodsOnCharacter?.indexOf(record.mood) ?? 0);
26662
+ const cells = cutStrip(await readFile37(stripFile), record.visemeOrder.length, record.cell, row);
26663
+ const visemes = Object.fromEntries(record.visemeOrder.map((id, index) => [id, { base64: cells[index].toString("base64"), format: "png" }]));
26664
+ return { record, visemes };
26665
+ }
26666
+ function checkText(text) {
26667
+ const line = text.trim();
26668
+ if (!line) throw new Error("the line of dialogue is empty");
26669
+ if (line.length > TALK_MAX_TEXT) throw new Error(`the line is ${line.length} characters; PixelLab lip-syncs at most ${TALK_MAX_TEXT}. Split it into shorter lines`);
26670
+ return line;
26671
+ }
26672
+ async function makeTalkingGif(client2, text, source, opts) {
26673
+ if (Boolean(source.record) === Boolean(source.characterId)) throw new Error("give a .talk.json record or a character id, not both");
26674
+ if (source.record && source.mood) throw new Error("a record holds one expression; --mood picks among a character's stored ones");
26675
+ const out = path56.extname(opts.out) ? path56.resolve(opts.out) : path56.resolve(`${opts.out}.gif`);
26676
+ if (existsSync43(out) && !opts.force) throw new Error(`${out} already exists; pass --force to replace it`);
26677
+ const line = checkText(text);
26678
+ const visemes = source.record ? (await readTalkRecord(source.record)).visemes : void 0;
26679
+ const res = await client2.createTalkingGif({ text: line, visemes, characterId: source.characterId, mood: source.mood, frameMs: opts.frameMs, holdMs: opts.holdMs });
26680
+ const bytes = Buffer.from(res.gif_base64, "base64");
26681
+ if (bytes.subarray(0, 4).toString("ascii") !== "GIF8") throw new Error(`PixelLab's talking GIF was not a GIF (${bytes.length} bytes)`);
26682
+ await mkdir19(path56.dirname(out), { recursive: true });
26683
+ await writeFile24(out, bytes);
26684
+ return { out, frames: res.frames, durationMs: res.duration_ms, frameMs: res.frame_ms, holdMs: res.hold_ms, width: res.width, height: res.height, bytes: bytes.length };
26685
+ }
26686
+ async function planLipSync(client2, text, source, opts = {}) {
26687
+ const given = [source.record, source.characterId, source.visemeCount].filter((value) => value !== void 0).length;
26688
+ if (given !== 1) throw new Error("give one of a .talk.json record, a character id, or a mouth-position count");
26689
+ const line = checkText(text);
26690
+ const record = source.record ? (await readTalkRecord(source.record)).record : void 0;
26691
+ const res = await client2.getLipSync({
26692
+ text: line,
26693
+ characterId: source.characterId,
26694
+ mood: source.characterId ? source.mood : void 0,
26695
+ visemeCount: record?.visemeCount ?? source.visemeCount,
26696
+ frameMs: opts.frameMs,
26697
+ holdMs: opts.holdMs
26698
+ });
26699
+ const column = record ? (id, fallback) => record.visemeOrder.includes(id) ? record.visemeOrder.indexOf(id) : fallback : (_id, fallback) => fallback;
26700
+ return {
26701
+ version: 1,
26702
+ text: res.text,
26703
+ totalMs: res.total_ms,
26704
+ visemeOrder: record?.visemeOrder ?? res.viseme_order,
26705
+ frames: res.frames.map((frame) => ({ viseme: frame.viseme, column: column(frame.viseme, frame.column), durationMs: frame.duration_ms, textOffset: frame.text_offset })),
26706
+ mood: record?.mood ?? res.mood ?? null,
26707
+ strip: record ? record.strip : res.grid_url ?? null,
26708
+ row: record ? Math.max(0, record.moodsOnCharacter?.indexOf(record.mood) ?? 0) : res.row ?? 0,
26709
+ cell: record?.cell ?? null
26710
+ };
26711
+ }
26712
+
26713
+ // src/cli/commands/talk.ts
26714
+ function loadKeys5(args) {
26715
+ loadEnvFiles(path57.dirname(path57.resolve(args.manifest)));
26716
+ loadEnvFiles(process.cwd());
26717
+ }
26718
+ function moodOf(args) {
26719
+ if (args.mood === void 0) return void 0;
26720
+ if (!TALK_MOODS.includes(args.mood)) throw new UsageError(`--mood must be one of ${TALK_MOODS.join(", ")}, got "${args.mood}"`);
26721
+ return args.mood;
26722
+ }
26723
+ function countOf(args) {
26724
+ if (args.visemes !== void 0 && !VISEME_COUNTS.includes(args.visemes)) {
26725
+ throw new UsageError(`--visemes must be ${VISEME_COUNTS.join(", ")}, got ${args.visemes}`);
26726
+ }
26727
+ return args.visemes;
26728
+ }
26729
+ function textOf(args) {
26730
+ const text = args.text?.trim();
26731
+ if (!text) throw new UsageError(`talk ${args.subcommand} needs --text "<the line of dialogue>"`);
26732
+ if (text.length > TALK_MAX_TEXT) throw new UsageError(`--text is ${text.length} characters; PixelLab lip-syncs at most ${TALK_MAX_TEXT}. Split it into shorter lines`);
26733
+ return text;
26734
+ }
26735
+ function sourceOf(args) {
26736
+ if (args.from && args.id) throw new UsageError("pass --from <record.talk.json> or --id <character id>, not both");
26737
+ if (args.from && !existsSync44(args.from)) throw new UsageError(`${args.from} does not exist; --from is the .talk.json record talk visemes wrote`);
26738
+ return { record: args.from, characterId: args.id };
26739
+ }
26740
+ async function runVisemes(args) {
26741
+ if (Boolean(args.from) === Boolean(args.id)) {
26742
+ throw new UsageError("talk visemes needs --from <portrait.png> (nothing is stored on PixelLab) or --id <character id> (saved onto the character), one of them");
26743
+ }
26744
+ if (!args.out) throw new UsageError("talk visemes needs --out <base>: it writes <base>.visemes.png and <base>.talk.json");
26745
+ if (args.text) throw new UsageError("talk visemes draws the mouth positions; lip-sync a line to them with talk gif --text");
26746
+ const engine = args.engine ?? "v3";
26747
+ if (!VISEME_ENGINES.includes(engine)) throw new UsageError(`--engine must be ${VISEME_ENGINES.join(" or ")}, got "${args.engine}"`);
26748
+ const mood = moodOf(args);
26749
+ const count = countOf(args) ?? 7;
26750
+ const paths = talkOutputPaths(args.out);
26751
+ let side = "unknown";
26752
+ if (args.from) {
26753
+ if (!existsSync44(args.from)) throw new UsageError(`${args.from} does not exist`);
26754
+ try {
26755
+ side = readPortrait(await readFile38(args.from), args.from).side;
26756
+ } catch (error) {
26757
+ throw new UsageError(error instanceof Error ? error.message : String(error));
26758
+ }
26759
+ }
26760
+ const cost = visemeCost(engine, side, count);
26761
+ log(
26762
+ ` ${count} mouth positions, ${mood ?? "neutral"}, by ${engine}, from ${args.from ?? `character ${args.id}'s stored portrait`} \u2192 ${paths.strip} (+ .talk.json)`
26763
+ );
26764
+ log(
26765
+ ` cost: about ${cost} generations` + (count === 7 ? " (PixelLab's published price)" : " (scaled from PixelLab's price for 7 positions; an estimate)") + (side === "unknown" && engine === "v3" ? "; priced as a 256px portrait, since the stored one's size is not known here" : "")
26766
+ );
26767
+ if (args.id) log(" the set is saved onto the character; every expression on one character must use the same --visemes");
26768
+ if (args.budget !== void 0 && args.budget < cost) throw new Error(`--budget ${args.budget} is below the ${cost} generations these mouth positions can cost`);
26769
+ if (args.dryRun) {
26770
+ log(" dry run: nothing sent");
26771
+ return;
26772
+ }
26773
+ if (!await confirm(` Spend about ${cost} generations on these mouth positions?`, args.yes)) return;
26774
+ loadKeys5(args);
26775
+ let last = "";
26776
+ const res = await makeVisemes(clientFromEnv(), {
26777
+ portrait: args.from,
26778
+ characterId: args.id,
26779
+ mood,
26780
+ visemeCount: count,
26781
+ engine,
26782
+ seed: args.seed,
26783
+ out: args.out,
26784
+ force: args.force,
26785
+ onProgress: (status) => {
26786
+ if (status !== last) log(` ${status}\u2026`);
26787
+ last = status;
26788
+ }
26789
+ });
26790
+ if (args.json) {
26791
+ log(JSON.stringify(res, null, 2));
26792
+ return;
26793
+ }
26794
+ log(` wrote ${res.paths.strip} (${res.visemeOrder.length} cells of ${res.cell.width}x${res.cell.height}: ${res.visemeOrder.join(", ")})`);
26795
+ log(` wrote ${res.paths.record}`);
26796
+ const usage2 = res.usage;
26797
+ if (typeof usage2?.generations === "number") log(` billed ${usage2.generations} generations`);
26798
+ log(` now free: pixelkiln talk gif --from ${res.paths.record} --text "<a line>" --out <file>`);
26799
+ }
26800
+ async function runGif(args) {
26801
+ const text = textOf(args);
26802
+ const source = sourceOf(args);
26803
+ if (!source.record && !source.characterId) throw new UsageError("talk gif needs --from <record.talk.json> or --id <character id>");
26804
+ if (!args.out) throw new UsageError("talk gif needs --out <file.gif>");
26805
+ if (args.visemes !== void 0) throw new UsageError("--visemes belongs to talk visemes and talk plan; a GIF uses the positions already made");
26806
+ const mood = moodOf(args);
26807
+ if (source.record && mood) throw new UsageError("a record holds one expression; --mood picks among a character's stored ones (--id)");
26808
+ if (args.dryRun) {
26809
+ log(` would lip-sync ${text.length} characters to a GIF (free); nothing sent`);
26810
+ return;
26811
+ }
26812
+ loadKeys5(args);
26813
+ const res = await makeTalkingGif(clientFromEnv(), text, { ...source, mood }, { out: args.out, frameMs: args.frameMs, holdMs: args.holdMs, force: args.force });
26814
+ if (args.json) log(JSON.stringify({ version: 1, ...res }, null, 2));
26815
+ else log(` wrote ${res.out} (${res.width}x${res.height}, ${res.frames} frames, ${(res.durationMs / 1e3).toFixed(2)} s, ${res.frameMs} ms a frame, free)`);
26816
+ }
26817
+ async function runPlan2(args) {
26818
+ const text = textOf(args);
26819
+ const source = sourceOf(args);
26820
+ const count = countOf(args);
26821
+ if ([source.record, source.characterId, count].filter((value) => value !== void 0).length !== 1) {
26822
+ throw new UsageError("talk plan needs one of --from <record.talk.json>, --id <character id>, or --visemes <n> for a bare preset");
26823
+ }
26824
+ const mood = moodOf(args);
26825
+ if (mood && !source.characterId) throw new UsageError("--mood picks among a character's stored expressions (--id)");
26826
+ if (args.dryRun) {
26827
+ log(` would plan ${text.length} characters of lip-sync (free); nothing sent`);
26828
+ return;
26829
+ }
26830
+ loadKeys5(args);
26831
+ const plan = await planLipSync(clientFromEnv(), text, { ...source, mood, visemeCount: count }, { frameMs: args.frameMs, holdMs: args.holdMs });
26832
+ const json = `${JSON.stringify(plan, null, 2)}
26833
+ `;
26834
+ if (!args.out) {
26835
+ log(json.trimEnd());
26836
+ return;
26837
+ }
26838
+ const out = path57.extname(args.out) ? path57.resolve(args.out) : path57.resolve(`${args.out}.json`);
26839
+ if (existsSync44(out) && !args.force) throw new Error(`${out} already exists; pass --force to replace it`);
26840
+ await mkdir20(path57.dirname(out), { recursive: true });
26841
+ await writeFile25(out, json);
26842
+ if (args.json) log(json.trimEnd());
26843
+ else log(` wrote ${out} (${plan.frames.length} frames, ${(plan.totalMs / 1e3).toFixed(2)} s, free)`);
26844
+ }
26845
+ async function runTalk(args) {
26846
+ if (args.subcommand === "visemes") return runVisemes(args);
26847
+ if (args.subcommand === "gif") return runGif(args);
26848
+ return runPlan2(args);
26849
+ }
26850
+
26851
+ // src/cli/commands/quality.ts
26852
+ import path59 from "path";
26853
+ import { readFile as readFile40 } from "fs/promises";
26854
+
26855
+ // src/pipeline/quality-regression.ts
26856
+ import path58 from "path";
26857
+ import { existsSync as existsSync45 } from "fs";
26858
+ import { readFile as readFile39 } from "fs/promises";
25937
26859
  import { z as z13 } from "zod";
25938
26860
  var SHA256_RE = /^[0-9a-f]{64}$/;
25939
26861
  var HEX_RE = /^#[0-9a-f]{6}$/;
25940
26862
  var MAX_REDMEAN_DISTANCE = 765;
25941
26863
  var QualityPathSchema = z13.string().min(1).refine(
25942
- (value) => !path56.posix.isAbsolute(value) && !value.includes("\\"),
26864
+ (value) => !path58.posix.isAbsolute(value) && !value.includes("\\"),
25943
26865
  "expected a portable relative path"
25944
26866
  );
25945
26867
  var DEFAULT_QUALITY_TOLERANCES = {
@@ -26086,10 +27008,10 @@ function measureDecodedImageQuality(png, digest2) {
26086
27008
  };
26087
27009
  }
26088
27010
  async function measureImageQuality(file) {
26089
- const absolute = path56.resolve(file);
27011
+ const absolute = path58.resolve(file);
26090
27012
  let bytes;
26091
27013
  try {
26092
- bytes = await readFile36(absolute);
27014
+ bytes = await readFile39(absolute);
26093
27015
  } catch (error) {
26094
27016
  throw new Error(`Cannot read quality image ${absolute}: ${message4(error)}`, { cause: error });
26095
27017
  }
@@ -26108,11 +27030,11 @@ function resolveQualityInputs(raw, inputsFilePath) {
26108
27030
  }
26109
27031
  const ids = parsed.data.map((entry) => entry.id);
26110
27032
  if (new Set(ids).size !== ids.length) throw new Error("--inputs contains a duplicate quality case id.");
26111
- const root = path56.dirname(path56.resolve(inputsFilePath));
27033
+ const root = path58.dirname(path58.resolve(inputsFilePath));
26112
27034
  return parsed.data.map((entry) => ({
26113
27035
  id: entry.id,
26114
- file: path56.resolve(root, entry.path),
26115
- ...entry.record ? { record: path56.resolve(root, entry.record) } : {},
27036
+ file: path58.resolve(root, entry.path),
27037
+ ...entry.record ? { record: path58.resolve(root, entry.record) } : {},
26116
27038
  tolerances: QualityToleranceSchema.parse({
26117
27039
  ...DEFAULT_QUALITY_TOLERANCES,
26118
27040
  ...entry.tolerances
@@ -26120,7 +27042,7 @@ function resolveQualityInputs(raw, inputsFilePath) {
26120
27042
  }));
26121
27043
  }
26122
27044
  function portableRelative2(from, to) {
26123
- return path56.relative(from, path56.resolve(to)).split(path56.sep).join("/") || ".";
27045
+ return path58.relative(from, path58.resolve(to)).split(path58.sep).join("/") || ".";
26124
27046
  }
26125
27047
  async function verifyRecordForImage(recordPath, imagePath) {
26126
27048
  const verification = await verifyArtifactBundle(recordPath);
@@ -26135,20 +27057,20 @@ async function verifyRecordForImage(recordPath, imagePath) {
26135
27057
  if (record.kind !== "refine" || options === null || typeof options !== "object" || options.schema !== "pixelkiln-quality") {
26136
27058
  throw new Error(`Quality record ${recordPath} is not a PixelKiln refinement record.`);
26137
27059
  }
26138
- const outputs = record.outputs.map((output) => path56.resolve(path56.dirname(recordPath), output.path));
26139
- if (!outputs.includes(path56.resolve(imagePath))) {
27060
+ const outputs = record.outputs.map((output) => path58.resolve(path58.dirname(recordPath), output.path));
27061
+ if (!outputs.includes(path58.resolve(imagePath))) {
26140
27062
  throw new Error(`Quality record ${recordPath} does not own ${imagePath}.`);
26141
27063
  }
26142
27064
  }
26143
27065
  async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
26144
27066
  if (!inputs.length) throw new Error("Cannot snapshot an empty quality baseline.");
26145
- const absolute = path56.resolve(baselinePath);
27067
+ const absolute = path58.resolve(baselinePath);
26146
27068
  for (const input of inputs) {
26147
- if (path56.resolve(input.file) === absolute || input.record && path56.resolve(input.record) === absolute) {
27069
+ if (path58.resolve(input.file) === absolute || input.record && path58.resolve(input.record) === absolute) {
26148
27070
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
26149
27071
  }
26150
27072
  }
26151
- const root = path56.dirname(absolute);
27073
+ const root = path58.dirname(absolute);
26152
27074
  const cases = [];
26153
27075
  for (const input of [...inputs].sort((a, b) => a.id.localeCompare(b.id))) {
26154
27076
  const expected = await measureImageQuality(input.file);
@@ -26175,8 +27097,8 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
26175
27097
  cases
26176
27098
  });
26177
27099
  const data = Buffer.from(JSON.stringify(baseline, null, 2) + "\n");
26178
- if (existsSync43(absolute) && !options.force) {
26179
- const current = await readFile36(absolute);
27100
+ if (existsSync45(absolute) && !options.force) {
27101
+ const current = await readFile39(absolute);
26180
27102
  if (!current.equals(data)) {
26181
27103
  throw new OverwriteRefusedError(
26182
27104
  `Quality baseline already exists with different content: ${absolute}. Pass --force to replace it.`,
@@ -26188,13 +27110,13 @@ async function snapshotQualityBaseline(inputs, baselinePath, options = {}) {
26188
27110
  return { baseline, path: absolute, changed: result.changed.length > 0 };
26189
27111
  }
26190
27112
  async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
26191
- const absolute = path56.resolve(baselinePath);
26192
- if (!existsSync43(absolute)) {
27113
+ const absolute = path58.resolve(baselinePath);
27114
+ if (!existsSync45(absolute)) {
26193
27115
  throw new Error(`quality snapshot --only updates an existing baseline; ${absolute} does not exist. Run a full snapshot first.`);
26194
27116
  }
26195
27117
  let raw;
26196
27118
  try {
26197
- raw = JSON.parse(await readFile36(absolute, "utf8"));
27119
+ raw = JSON.parse(await readFile39(absolute, "utf8"));
26198
27120
  } catch (error) {
26199
27121
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
26200
27122
  }
@@ -26204,12 +27126,12 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
26204
27126
  if (unknown.length) {
26205
27127
  throw new Error(`--only names ${unknown.join(", ")}, which the quality inputs do not list. Known: ${[...byId.keys()].sort().join(", ")}`);
26206
27128
  }
26207
- const root = path56.dirname(absolute);
27129
+ const root = path58.dirname(absolute);
26208
27130
  const cases = [...raw.cases];
26209
27131
  const report = [];
26210
27132
  for (const id of only) {
26211
27133
  const input = byId.get(id);
26212
- if (path56.resolve(input.file) === absolute || input.record && path56.resolve(input.record) === absolute) {
27134
+ if (path58.resolve(input.file) === absolute || input.record && path58.resolve(input.record) === absolute) {
26213
27135
  throw new Error(`Quality baseline output would overwrite an input: ${absolute}.`);
26214
27136
  }
26215
27137
  const expected = await measureImageQuality(input.file);
@@ -26239,16 +27161,16 @@ async function snapshotQualityCases(inputs, baselinePath, only, options = {}) {
26239
27161
  }
26240
27162
  const baseline = QualityBaselineSchema.parse({ ...raw, cases });
26241
27163
  const data = Buffer.from(JSON.stringify({ ...raw, cases }, null, 2) + "\n");
26242
- const current = await readFile36(absolute);
27164
+ const current = await readFile39(absolute);
26243
27165
  const changed = !current.equals(data);
26244
27166
  if (changed && !options.dryRun) await writeArtifactBundle([{ path: absolute, data }]);
26245
27167
  return { baseline, path: absolute, changed, cases: report };
26246
27168
  }
26247
27169
  async function readQualityBaseline(baselinePath) {
26248
- const absolute = path56.resolve(baselinePath);
27170
+ const absolute = path58.resolve(baselinePath);
26249
27171
  let raw;
26250
27172
  try {
26251
- raw = JSON.parse(await readFile36(absolute, "utf8"));
27173
+ raw = JSON.parse(await readFile39(absolute, "utf8"));
26252
27174
  } catch (error) {
26253
27175
  throw new Error(`Could not read quality baseline ${absolute}: ${message4(error)}`, { cause: error });
26254
27176
  }
@@ -26270,7 +27192,7 @@ async function readQualityBaseline(baselinePath) {
26270
27192
  throw new Error(
26271
27193
  `Invalid quality baseline ${absolute}:
26272
27194
  ` + parsed.error.issues.map((issue) => ` ${where(issue.path)}: ${issue.message}`).join("\n") + (missing.length ? `
26273
- Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${path56.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
27195
+ Entries missing fields: re-measure them with \`pixelkiln quality snapshot --inputs <inputs> --out ${path58.basename(absolute)} --only ${missing.join(",")}\` rather than editing the JSON by hand.` : "")
26274
27196
  );
26275
27197
  }
26276
27198
  return parsed.data;
@@ -26332,12 +27254,12 @@ function regressionViolations(expected, actual, tolerances) {
26332
27254
  return { violations, warnings };
26333
27255
  }
26334
27256
  async function checkQualityBaseline(baselinePath) {
26335
- const absolute = path56.resolve(baselinePath);
27257
+ const absolute = path58.resolve(baselinePath);
26336
27258
  const baseline = await readQualityBaseline(absolute);
26337
- const root = path56.dirname(absolute);
27259
+ const root = path58.dirname(absolute);
26338
27260
  const cases = [];
26339
27261
  for (const entry of baseline.cases) {
26340
- const file = path56.resolve(root, entry.file);
27262
+ const file = path58.resolve(root, entry.file);
26341
27263
  let actual = null;
26342
27264
  const violations = [];
26343
27265
  const warnings = [];
@@ -26350,7 +27272,7 @@ async function checkQualityBaseline(baselinePath) {
26350
27272
  violations.push(message4(error));
26351
27273
  }
26352
27274
  if (entry.record) {
26353
- const recordPath = path56.resolve(root, entry.record.path);
27275
+ const recordPath = path58.resolve(root, entry.record.path);
26354
27276
  try {
26355
27277
  const recordHash = await sha256File(recordPath);
26356
27278
  if (recordHash !== entry.record.sha256) violations.push("quality record hash changed");
@@ -26392,15 +27314,15 @@ async function runQuality(args) {
26392
27314
  if (!args.out) throw new Error("quality snapshot needs --out <pixelkiln.quality.json>.");
26393
27315
  let raw;
26394
27316
  try {
26395
- raw = JSON.parse(await readFile37(path57.resolve(args.inputs), "utf8"));
27317
+ raw = JSON.parse(await readFile40(path59.resolve(args.inputs), "utf8"));
26396
27318
  } catch (error) {
26397
27319
  throw new Error(
26398
- `Could not read quality inputs ${path57.resolve(args.inputs)}: ${error instanceof Error ? error.message : String(error)}`,
27320
+ `Could not read quality inputs ${path59.resolve(args.inputs)}: ${error instanceof Error ? error.message : String(error)}`,
26399
27321
  { cause: error }
26400
27322
  );
26401
27323
  }
26402
27324
  const inputs = resolveQualityInputs(raw, args.inputs);
26403
- if (path57.resolve(args.inputs) === path57.resolve(args.out)) {
27325
+ if (path59.resolve(args.inputs) === path59.resolve(args.out)) {
26404
27326
  throw new Error("quality snapshot --out must not overwrite its --inputs file.");
26405
27327
  }
26406
27328
  if (args.assets.length) {
@@ -26415,7 +27337,7 @@ async function runQuality(args) {
26415
27337
  }
26416
27338
  log(
26417
27339
  `
26418
- ${result2.changed ? args.dryRun ? "would write" : "wrote" : "no changes to"} ${path57.relative(process.cwd(), result2.path)}; other cases left as they were.`
27340
+ ${result2.changed ? args.dryRun ? "would write" : "wrote" : "no changes to"} ${path59.relative(process.cwd(), result2.path)}; other cases left as they were.`
26419
27341
  );
26420
27342
  return;
26421
27343
  }
@@ -26430,7 +27352,7 @@ async function runQuality(args) {
26430
27352
  }, null, 2));
26431
27353
  } else {
26432
27354
  log(
26433
- ` ${result.changed ? "wrote" : "unchanged"} ${path57.relative(process.cwd(), result.path)} (${result.baseline.cases.length} case(s))`
27355
+ ` ${result.changed ? "wrote" : "unchanged"} ${path59.relative(process.cwd(), result.path)} (${result.baseline.cases.length} case(s))`
26434
27356
  );
26435
27357
  log(` Review the tolerances, commit the baseline, then run quality check in CI.`);
26436
27358
  }
@@ -26456,12 +27378,12 @@ async function runQuality(args) {
26456
27378
  }
26457
27379
 
26458
27380
  // src/cli/commands/recipe.ts
26459
- import path59 from "path";
27381
+ import path61 from "path";
26460
27382
 
26461
27383
  // src/recipes.ts
26462
- import path58 from "path";
26463
- import { existsSync as existsSync44 } from "fs";
26464
- import { readdir as readdir3, readFile as readFile38 } from "fs/promises";
27384
+ import path60 from "path";
27385
+ import { existsSync as existsSync46 } from "fs";
27386
+ import { readdir as readdir4, readFile as readFile41 } from "fs/promises";
26465
27387
  import { fileURLToPath as fileURLToPath2 } from "url";
26466
27388
  import { z as z14 } from "zod";
26467
27389
  var SHA256_RE2 = /^[0-9a-f]{64}$/;
@@ -26470,7 +27392,7 @@ var VERSION_RE = /^\d+\.\d+\.\d+$/;
26470
27392
  var RECIPE_FILE = "pixelkiln.recipe.json";
26471
27393
  var RECIPE_DIR_TOKEN = "{{recipeDir}}";
26472
27394
  var PortablePathSchema = z14.string().min(1).refine((value) => {
26473
- if (value.includes("\\") || path58.posix.isAbsolute(value)) return false;
27395
+ if (value.includes("\\") || path60.posix.isAbsolute(value)) return false;
26474
27396
  const parts = value.split("/");
26475
27397
  return !parts.includes("") && !parts.includes(".") && !parts.includes("..");
26476
27398
  }, "expected a portable relative path without '.', '..', or backslashes");
@@ -26646,10 +27568,10 @@ function message5(error) {
26646
27568
  return error instanceof Error ? error.message : String(error);
26647
27569
  }
26648
27570
  async function readRecipeFile(recipePath, bundled) {
26649
- const absolute = path58.resolve(recipePath);
27571
+ const absolute = path60.resolve(recipePath);
26650
27572
  let raw;
26651
27573
  try {
26652
- raw = JSON.parse(await readFile38(absolute, "utf8"));
27574
+ raw = JSON.parse(await readFile41(absolute, "utf8"));
26653
27575
  } catch (error) {
26654
27576
  throw new Error(`Could not read recipe ${absolute}: ${message5(error)}`, { cause: error });
26655
27577
  }
@@ -26660,13 +27582,13 @@ async function readRecipeFile(recipePath, bundled) {
26660
27582
  ` + parsed.error.issues.map((issue) => ` ${issue.path.join(".") || "$"}: ${issue.message}`).join("\n")
26661
27583
  );
26662
27584
  }
26663
- return { recipe: parsed.data, authored: raw, path: absolute, dir: path58.dirname(absolute), bundled };
27585
+ return { recipe: parsed.data, authored: raw, path: absolute, dir: path60.dirname(absolute), bundled };
26664
27586
  }
26665
27587
  async function walkRecipeFiles(root) {
26666
- if (!existsSync44(root)) return [];
27588
+ if (!existsSync46(root)) return [];
26667
27589
  const out = [];
26668
- for (const entry of await readdir3(root, { withFileTypes: true })) {
26669
- const resolved = path58.join(root, entry.name);
27590
+ for (const entry of await readdir4(root, { withFileTypes: true })) {
27591
+ const resolved = path60.join(root, entry.name);
26670
27592
  if (entry.isDirectory()) out.push(...await walkRecipeFiles(resolved));
26671
27593
  else if (entry.isFile() && entry.name === RECIPE_FILE) out.push(resolved);
26672
27594
  }
@@ -26677,7 +27599,7 @@ function bundledRecipeRoot() {
26677
27599
  }
26678
27600
  async function listBundledRecipes(root = bundledRecipeRoot()) {
26679
27601
  const recipes = await Promise.all(
26680
- (await walkRecipeFiles(path58.resolve(root))).map((file) => readRecipeFile(file, true))
27602
+ (await walkRecipeFiles(path60.resolve(root))).map((file) => readRecipeFile(file, true))
26681
27603
  );
26682
27604
  return recipes.sort(
26683
27605
  (a, b) => a.recipe.id.localeCompare(b.recipe.id) || compareVersions(b.recipe.version, a.recipe.version)
@@ -26700,9 +27622,9 @@ function parseSelector(selector) {
26700
27622
  return { id: match[1], version: match[2] };
26701
27623
  }
26702
27624
  async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
26703
- const local = path58.resolve(target);
26704
- if (existsSync44(local)) {
26705
- const recipePath = path58.basename(local) === RECIPE_FILE ? local : path58.join(local, RECIPE_FILE);
27625
+ const local = path60.resolve(target);
27626
+ if (existsSync46(local)) {
27627
+ const recipePath = path60.basename(local) === RECIPE_FILE ? local : path60.join(local, RECIPE_FILE);
26706
27628
  return readRecipeFile(recipePath, false);
26707
27629
  }
26708
27630
  if (target.startsWith(".") || target.startsWith("/") || target.includes("\\")) {
@@ -26716,8 +27638,8 @@ async function resolveRecipe(target, bundledRoot = bundledRecipeRoot()) {
26716
27638
  return matches[0];
26717
27639
  }
26718
27640
  async function verifyFile(root, file) {
26719
- const absolute = path58.resolve(root, ...file.path.split("/"));
26720
- if (!existsSync44(absolute)) {
27641
+ const absolute = path60.resolve(root, ...file.path.split("/"));
27642
+ if (!existsSync46(absolute)) {
26721
27643
  return { path: file.path, expectedSha256: file.sha256, actualSha256: null, status: "missing" };
26722
27644
  }
26723
27645
  const actualSha256 = await sha256File(absolute);
@@ -26732,7 +27654,7 @@ async function verifyRecipe(target, options = {}) {
26732
27654
  const loaded = await resolveRecipe(target, options.bundledRoot);
26733
27655
  const actualIntegrity = recipeDigest(loaded.authored);
26734
27656
  const files = await Promise.all(loaded.recipe.files.map((file) => verifyFile(loaded.dir, file)));
26735
- const modelRoot = options.modelRoot ? path58.resolve(options.modelRoot) : null;
27657
+ const modelRoot = options.modelRoot ? path60.resolve(options.modelRoot) : null;
26736
27658
  const models = modelRoot ? await Promise.all(loaded.recipe.models.map(async (model) => ({
26737
27659
  ...await verifyFile(modelRoot, model),
26738
27660
  source: model.source,
@@ -26766,7 +27688,7 @@ async function verifyRecipe(target, options = {}) {
26766
27688
  };
26767
27689
  }
26768
27690
  function renderStyle(style, destination, cwd) {
26769
- const portableDir = path58.relative(cwd, destination).split(path58.sep).join("/") || ".";
27691
+ const portableDir = path60.relative(cwd, destination).split(path60.sep).join("/") || ".";
26770
27692
  const replace = (value) => {
26771
27693
  if (typeof value === "string") return value.replaceAll(RECIPE_DIR_TOKEN, portableDir);
26772
27694
  if (Array.isArray(value)) return value.map(replace);
@@ -26778,25 +27700,25 @@ function renderStyle(style, destination, cwd) {
26778
27700
  return replace(style);
26779
27701
  }
26780
27702
  async function installRecipe(target, options = {}) {
26781
- const cwd = path58.resolve(options.cwd ?? process.cwd());
27703
+ const cwd = path60.resolve(options.cwd ?? process.cwd());
26782
27704
  const loaded = await resolveRecipe(target, options.bundledRoot);
26783
27705
  const verification = await verifyRecipe(loaded.path);
26784
27706
  if (!verification.ok) {
26785
27707
  throw new Error(`Recipe ${loaded.recipe.id}@${loaded.recipe.version} failed integrity verification.`);
26786
27708
  }
26787
- const destination = options.out ? path58.resolve(cwd, options.out) : path58.join(cwd, "pixelkiln-recipes", ...loaded.recipe.id.split("/"), loaded.recipe.version);
27709
+ const destination = options.out ? path60.resolve(cwd, options.out) : path60.join(cwd, "pixelkiln-recipes", ...loaded.recipe.id.split("/"), loaded.recipe.version);
26788
27710
  const sources = [
26789
27711
  { path: RECIPE_FILE, source: loaded.path },
26790
- ...loaded.recipe.files.map((file) => ({ path: file.path, source: path58.join(loaded.dir, ...file.path.split("/")) }))
27712
+ ...loaded.recipe.files.map((file) => ({ path: file.path, source: path60.join(loaded.dir, ...file.path.split("/")) }))
26791
27713
  ];
26792
27714
  const files = await Promise.all(sources.map(async (file) => ({
26793
- path: path58.join(destination, ...file.path.split("/")),
26794
- data: await readFile38(file.source)
27715
+ path: path60.join(destination, ...file.path.split("/")),
27716
+ data: await readFile41(file.source)
26795
27717
  })));
26796
27718
  if (!options.force) {
26797
27719
  for (const file of files) {
26798
- if (!existsSync44(file.path)) continue;
26799
- const current = await readFile38(file.path);
27720
+ if (!existsSync46(file.path)) continue;
27721
+ const current = await readFile41(file.path);
26800
27722
  if (!current.equals(file.data)) {
26801
27723
  throw new OverwriteRefusedError(
26802
27724
  `Recipe destination has local changes: ${file.path}. Choose another --out or pass --force to replace declared recipe files.`,
@@ -26890,14 +27812,14 @@ async function runRecipe(args) {
26890
27812
  }, null, 2));
26891
27813
  } else {
26892
27814
  log(` installed ${result.recipe.id}@${result.recipe.version}`);
26893
- log(` ${path59.relative(process.cwd(), result.destination) || "."}`);
27815
+ log(` ${path61.relative(process.cwd(), result.destination) || "."}`);
26894
27816
  log(`
26895
27817
  Add this entry under your manifest's styles object:`);
26896
27818
  log(JSON.stringify({ [result.styleId]: result.style }, null, 2));
26897
27819
  if (result.recipe.models.length) {
26898
27820
  log(`
26899
27821
  Models are not downloaded automatically. Verify them with:`);
26900
- log(` pixelkiln recipe verify ${path59.relative(process.cwd(), result.destination)} --model-root <ComfyUI/models>`);
27822
+ log(` pixelkiln recipe verify ${path61.relative(process.cwd(), result.destination)} --model-root <ComfyUI/models>`);
26901
27823
  }
26902
27824
  }
26903
27825
  return;
@@ -26905,7 +27827,7 @@ async function runRecipe(args) {
26905
27827
  }
26906
27828
 
26907
27829
  // src/cli/commands/refine.ts
26908
- import path60 from "path";
27830
+ import path62 from "path";
26909
27831
  async function runRefine(args) {
26910
27832
  if (args.from || args.subcommand === "approve") {
26911
27833
  if (!args.from) {
@@ -26935,12 +27857,12 @@ async function runRefine(args) {
26935
27857
  ` recovered ${result3.detection.columns}x${result3.detection.rows} native grid (${result3.detection.confidence}: ${result3.detection.consensus})`
26936
27858
  );
26937
27859
  log(` enforced ${result3.palette.length}-color palette without dithering`);
26938
- log(` wrote ${path60.relative(process.cwd(), result3.output)}`);
26939
- log(` quality record: ${path60.relative(process.cwd(), result3.record)}`);
27860
+ log(` wrote ${path62.relative(process.cwd(), result3.output)}`);
27861
+ log(` quality record: ${path62.relative(process.cwd(), result3.record)}`);
26940
27862
  log(`
26941
27863
  Automated checks passed. Human 1\xD7 review is still required:`);
26942
27864
  log(
26943
- ` pixelkiln refine approve --from ${path60.relative(process.cwd(), result3.record)} --reviewer "Your Name"`
27865
+ ` pixelkiln refine approve --from ${path62.relative(process.cwd(), result3.record)} --reviewer "Your Name"`
26944
27866
  );
26945
27867
  }
26946
27868
  return;
@@ -26968,7 +27890,7 @@ async function runRefine(args) {
26968
27890
  if (args.json) log(JSON.stringify(result3, null, 2));
26969
27891
  else {
26970
27892
  log(
26971
- result3.options.frameSet ? ` approved ${result3.outputs.length} frames in ${path60.relative(process.cwd(), result3.record)} by ${args.reviewer.trim()}` : ` approved ${path60.relative(process.cwd(), result3.output)} by ${args.reviewer.trim()}`
27893
+ result3.options.frameSet ? ` approved ${result3.outputs.length} frames in ${path62.relative(process.cwd(), result3.record)} by ${args.reviewer.trim()}` : ` approved ${path62.relative(process.cwd(), result3.output)} by ${args.reviewer.trim()}`
26972
27894
  );
26973
27895
  }
26974
27896
  return;
@@ -26977,7 +27899,7 @@ async function runRefine(args) {
26977
27899
  if (args.json) {
26978
27900
  log(JSON.stringify(result2, null, 2));
26979
27901
  } else {
26980
- log(` ${result2.safe ? "release-ready" : "not release-ready"}: ${path60.relative(process.cwd(), result2.output || result2.record)}`);
27902
+ log(` ${result2.safe ? "release-ready" : "not release-ready"}: ${path62.relative(process.cwd(), result2.output || result2.record)}`);
26981
27903
  for (const reason of result2.reasons) log(` ${reason}`);
26982
27904
  }
26983
27905
  if (!result2.safe) process.exitCode = 1;
@@ -27023,7 +27945,7 @@ async function runRefine(args) {
27023
27945
  log(` ${item.state.padEnd(16)} ${item.key} ${item.reason}`);
27024
27946
  if (item.state === "needs-approval") {
27025
27947
  log(
27026
- ` pixelkiln refine approve --from ${path60.relative(process.cwd(), item.record)} --reviewer "Your Name"`
27948
+ ` pixelkiln refine approve --from ${path62.relative(process.cwd(), item.record)} --reviewer "Your Name"`
27027
27949
  );
27028
27950
  }
27029
27951
  }
@@ -27034,9 +27956,9 @@ async function runRefine(args) {
27034
27956
  }
27035
27957
 
27036
27958
  // src/cli/commands/skeleton.ts
27037
- import path61 from "path";
27038
- import { existsSync as existsSync45 } from "fs";
27039
- import { readFile as readFile39, writeFile as writeFile24 } from "fs/promises";
27959
+ import path63 from "path";
27960
+ import { existsSync as existsSync47 } from "fs";
27961
+ import { readFile as readFile42, writeFile as writeFile26 } from "fs/promises";
27040
27962
 
27041
27963
  // src/skeleton-preview.ts
27042
27964
  var RIGHT = [255, 140, 40, 255];
@@ -27147,12 +28069,12 @@ var Canvas = class {
27147
28069
  async function runEstimateSkeleton(args) {
27148
28070
  const image = args.target;
27149
28071
  if (!image) throw new UsageError("estimate-skeleton needs an image path: pixelkiln estimate-skeleton <image> [--out keypoints.json]");
27150
- if (args.out && existsSync45(path61.resolve(args.out)) && !args.force) {
28072
+ if (args.out && existsSync47(path63.resolve(args.out)) && !args.force) {
27151
28073
  throw new UsageError(`${args.out} already exists; pass --force to replace it`);
27152
28074
  }
27153
- loadEnvFiles(path61.dirname(path61.resolve(args.manifest)));
28075
+ loadEnvFiles(path63.dirname(path63.resolve(args.manifest)));
27154
28076
  loadEnvFiles(process.cwd());
27155
- const bytes = await readFile39(path61.resolve(image));
28077
+ const bytes = await readFile42(path63.resolve(image));
27156
28078
  const metadata = imageMetadata(bytes);
27157
28079
  if (!metadata) throw new UsageError(`${image} is not a readable PNG or JPEG`);
27158
28080
  const sizeProblem = estimateSkeletonSizeProblem(metadata.width, metadata.height);
@@ -27164,7 +28086,7 @@ async function runEstimateSkeleton(args) {
27164
28086
  const frames = args.frames ?? DEFAULT_SCAFFOLD_FRAMES;
27165
28087
  const json = JSON.stringify(scaffoldSkeletonSet(res.keypoints, frames), null, 2);
27166
28088
  if (args.out) {
27167
- await writeFile24(path61.resolve(args.out), json + "\n");
28089
+ await writeFile26(path63.resolve(args.out), json + "\n");
27168
28090
  log(` wrote ${args.out}: the estimated pose and ${frames} frames to edit`);
27169
28091
  log(` preview it with: pixelkiln skeleton-preview ${args.out} --from ${image}`);
27170
28092
  } else {
@@ -27177,8 +28099,8 @@ async function runSkeletonPreview(args) {
27177
28099
  let sourceFile2;
27178
28100
  let label;
27179
28101
  if (target.endsWith(".json")) {
27180
- keypointsFile = path61.resolve(target);
27181
- sourceFile2 = args.from ? path61.resolve(args.from) : void 0;
28102
+ keypointsFile = path63.resolve(target);
28103
+ sourceFile2 = args.from ? path63.resolve(args.from) : void 0;
27182
28104
  label = target;
27183
28105
  } else {
27184
28106
  const loaded = await loadManifest(args.manifest);
@@ -27190,31 +28112,31 @@ async function runSkeletonPreview(args) {
27190
28112
  );
27191
28113
  }
27192
28114
  keypointsFile = spec.revision.keypointsFile;
27193
- sourceFile2 = args.from ? path61.resolve(args.from) : spec.revision.sourceFile;
28115
+ sourceFile2 = args.from ? path63.resolve(args.from) : spec.revision.sourceFile;
27194
28116
  label = `${spec.styleId}/${spec.assetId}`;
27195
28117
  }
27196
- if (!existsSync45(keypointsFile)) throw new UsageError(`Keypoints file does not exist yet: ${keypointsFile}`);
28118
+ if (!existsSync47(keypointsFile)) throw new UsageError(`Keypoints file does not exist yet: ${keypointsFile}`);
27197
28119
  let json;
27198
28120
  try {
27199
- json = JSON.parse(await readFile39(keypointsFile, "utf8"));
28121
+ json = JSON.parse(await readFile42(keypointsFile, "utf8"));
27200
28122
  } catch (error) {
27201
28123
  throw new UsageError(`${keypointsFile} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
27202
28124
  }
27203
28125
  const set = parseSkeletonSet(json, keypointsFile);
27204
28126
  let source;
27205
28127
  if (sourceFile2) {
27206
- if (!existsSync45(sourceFile2)) {
28128
+ if (!existsSync47(sourceFile2)) {
27207
28129
  log(` source image does not exist yet, drawing on a plain ground: ${sourceFile2}`);
27208
28130
  } else {
27209
- const bytes = await readFile39(sourceFile2);
28131
+ const bytes = await readFile42(sourceFile2);
27210
28132
  if (imageMetadata(bytes)?.format !== "png") throw new UsageError(`${sourceFile2} must be a PNG to preview over`);
27211
28133
  source = decodePng(bytes);
27212
28134
  }
27213
28135
  }
27214
- const out = path61.resolve(args.out ?? keypointsFile.replace(/\.json$/, "") + ".preview.png");
27215
- await writeFile24(out, renderSkeletonSheet(set, { source }));
28136
+ const out = path63.resolve(args.out ?? keypointsFile.replace(/\.json$/, "") + ".preview.png");
28137
+ await writeFile26(out, renderSkeletonSheet(set, { source }));
27216
28138
  log(` ${label}: ${set.frames.length} frames after the starting pose`);
27217
- const shown = path61.relative(process.cwd(), out);
28139
+ const shown = path63.relative(process.cwd(), out);
27218
28140
  log(` wrote ${shown.startsWith("..") ? out : shown}`);
27219
28141
  }
27220
28142
 
@@ -27260,15 +28182,15 @@ async function runTools(args) {
27260
28182
  }
27261
28183
 
27262
28184
  // src/cli/commands/workspace.ts
27263
- import path62 from "path";
27264
- import { existsSync as existsSync46 } from "fs";
28185
+ import path64 from "path";
28186
+ import { existsSync as existsSync48 } from "fs";
27265
28187
  async function runWorkspace(args) {
27266
- const workspacePath = path62.resolve(args.workspace ?? "pixelkiln.workspace.json");
27267
- const dir = path62.dirname(workspacePath);
28188
+ const workspacePath = path64.resolve(args.workspace ?? "pixelkiln.workspace.json");
28189
+ const dir = path64.dirname(workspacePath);
27268
28190
  if (args.subcommand === "add") {
27269
- const manifestPath = path62.resolve(args.target);
28191
+ const manifestPath = path64.resolve(args.target);
27270
28192
  const loadedTarget = await loadManifest(manifestPath);
27271
- const lockPath = args.explicitLock ? path62.resolve(args.explicitLock) : path62.join(path62.dirname(manifestPath), "pixelkiln.lock.json");
28193
+ const lockPath = args.explicitLock ? path64.resolve(args.explicitLock) : path64.join(path64.dirname(manifestPath), "pixelkiln.lock.json");
27272
28194
  const ws = await loadWorkspace(workspacePath);
27273
28195
  const id = args.name ?? loadedTarget.manifest.name;
27274
28196
  if (ws.projects.some((p) => p.id === id)) {
@@ -27288,10 +28210,10 @@ async function runWorkspace(args) {
27288
28210
  ...args.account ? { account: args.account } : {}
27289
28211
  };
27290
28212
  await saveWorkspace(workspacePath, { version: 1, projects: [...ws.projects, project] });
27291
- log(` registered "${id}" in ${path62.relative(process.cwd(), workspacePath)}`);
28213
+ log(` registered "${id}" in ${path64.relative(process.cwd(), workspacePath)}`);
27292
28214
  log(` manifest: ${project.manifest}`);
27293
28215
  log(` lock: ${project.lock}`);
27294
- if (!existsSync46(lockPath)) {
28216
+ if (!existsSync48(lockPath)) {
27295
28217
  log(
27296
28218
  ` warning: no lockfile there yet; this project contributes no claims until one is generated`
27297
28219
  );
@@ -27300,7 +28222,7 @@ async function runWorkspace(args) {
27300
28222
  }
27301
28223
  if (args.subcommand === "remove") {
27302
28224
  const ws = await loadWorkspace(workspacePath);
27303
- const resolvedTarget = path62.resolve(args.target);
28225
+ const resolvedTarget = path64.resolve(args.target);
27304
28226
  const match = ws.projects.find(
27305
28227
  (p) => p.id === args.target || resolveProject(dir, p).manifestPath === resolvedTarget
27306
28228
  );
@@ -27311,11 +28233,11 @@ async function runWorkspace(args) {
27311
28233
  version: 1,
27312
28234
  projects: ws.projects.filter((p) => p !== match)
27313
28235
  });
27314
- log(` removed "${match.id}" from ${path62.relative(process.cwd(), workspacePath)}`);
28236
+ log(` removed "${match.id}" from ${path64.relative(process.cwd(), workspacePath)}`);
27315
28237
  return;
27316
28238
  }
27317
28239
  if (args.subcommand === "list") {
27318
- if (!existsSync46(workspacePath)) {
28240
+ if (!existsSync48(workspacePath)) {
27319
28241
  throw new Error(`Workspace catalog not found: ${workspacePath}`);
27320
28242
  }
27321
28243
  const ws = await loadWorkspace(workspacePath);
@@ -27323,9 +28245,9 @@ async function runWorkspace(args) {
27323
28245
  if (args.json) {
27324
28246
  log(JSON.stringify({ version: 1, workspace: workspacePath, projects: ws.projects, diagnostics }, null, 2));
27325
28247
  } else if (!ws.projects.length) {
27326
- log(` no projects registered in ${path62.relative(process.cwd(), workspacePath)}`);
28248
+ log(` no projects registered in ${path64.relative(process.cwd(), workspacePath)}`);
27327
28249
  } else {
27328
- log(` ${ws.projects.length} project(s) in ${path62.relative(process.cwd(), workspacePath)}:`);
28250
+ log(` ${ws.projects.length} project(s) in ${path64.relative(process.cwd(), workspacePath)}:`);
27329
28251
  for (const p of ws.projects) {
27330
28252
  log(` ${p.id.padEnd(24)} ${p.manifest.padEnd(40)} (${p.provider}${p.account ? `, ${p.account}` : ""})`);
27331
28253
  }
@@ -27335,7 +28257,7 @@ async function runWorkspace(args) {
27335
28257
  return;
27336
28258
  }
27337
28259
  if (args.subcommand === "status") {
27338
- if (!existsSync46(workspacePath)) {
28260
+ if (!existsSync48(workspacePath)) {
27339
28261
  throw new Error(`Workspace catalog not found: ${workspacePath}`);
27340
28262
  }
27341
28263
  const ws = await loadWorkspace(workspacePath);
@@ -27343,7 +28265,7 @@ async function runWorkspace(args) {
27343
28265
  if (args.json) {
27344
28266
  log(JSON.stringify({ ...report, workspace: workspacePath }, null, 2));
27345
28267
  } else {
27346
- log(` workspace: ${path62.relative(process.cwd(), workspacePath)}`);
28268
+ log(` workspace: ${path64.relative(process.cwd(), workspacePath)}`);
27347
28269
  for (const p of report.projects) {
27348
28270
  if (p.error) {
27349
28271
  log(`
@@ -27397,8 +28319,8 @@ async function runHelp() {
27397
28319
  async function runVersion() {
27398
28320
  for (const up of ["../package.json", "../../package.json"]) {
27399
28321
  const url = new URL(up, import.meta.url);
27400
- if (!existsSync47(url)) continue;
27401
- const pkg = JSON.parse(await readFile40(url, "utf8"));
28322
+ if (!existsSync49(url)) continue;
28323
+ const pkg = JSON.parse(await readFile43(url, "utf8"));
27402
28324
  if (pkg.name === "pixelkiln") {
27403
28325
  log(`${pkg.name} ${pkg.version}`);
27404
28326
  return;
@@ -27453,7 +28375,8 @@ var RUNNERS = {
27453
28375
  music: runMusic,
27454
28376
  sfx: runSfx,
27455
28377
  ui: runUi,
27456
- asset: runAsset
28378
+ asset: runAsset,
28379
+ talk: runTalk
27457
28380
  };
27458
28381
  async function main(argv = process.argv.slice(2)) {
27459
28382
  const args = parseArgs(argv);