@sogni-ai/sogni-creative-agent-skill 3.35.4 → 3.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/sogni-agent.mjs CHANGED
@@ -10,6 +10,7 @@
10
10
  import './node-version-check.mjs';
11
11
  import JSON5 from 'json5';
12
12
  import { createHash, randomBytes } from 'crypto';
13
+ import { execFileSync } from 'child_process';
13
14
  import { createRequire } from 'module';
14
15
  import { readFileSync, writeFileSync, existsSync, mkdirSync, mkdtempSync, statSync, readdirSync, realpathSync, lstatSync, unlinkSync, rmdirSync, rmSync, renameSync } from 'fs';
15
16
  import { join, dirname, basename, extname, sep, resolve } from 'path';
@@ -2125,7 +2126,11 @@ const MINIMAX_H3_MODEL_MODES = new Map([
2125
2126
  ['minimax-h3-fl2va-fp8_t2v_turbo', 't2v'],
2126
2127
  ['minimax-h3-fl2va-fp8_i2v_turbo', 'i2v'],
2127
2128
  ['minimax-h3-fl2va-fp8_flf2v_turbo', 'flf2v'],
2128
- ['minimax-h3-ref2va-fp8_r2v_turbo', 'r2v']
2129
+ ['minimax-h3-ref2va-fp8_r2v_turbo', 'r2v'],
2130
+ ['minimax-h3-fl2va-fp8_t2v_balanced', 't2v'],
2131
+ ['minimax-h3-fl2va-fp8_i2v_balanced', 'i2v'],
2132
+ ['minimax-h3-fl2va-fp8_flf2v_balanced', 'flf2v'],
2133
+ ['minimax-h3-ref2va-fp8_r2v_balanced', 'r2v']
2129
2134
  ]);
2130
2135
  const MINIMAX_H3_MODEL_IDS = new Set(MINIMAX_H3_MODEL_MODES.keys());
2131
2136
  const MINIMAX_H3_TURBO_MODEL_IDS = new Set([
@@ -2138,6 +2143,7 @@ const MINIMAX_H3_TURBO_SAMPLERS = Object.freeze(['euler', 'er_sde', 'sa_solver']
2138
2143
  const MINIMAX_H3_TURBO_SAMPLER_SET = new Set(MINIMAX_H3_TURBO_SAMPLERS);
2139
2144
  const MINIMAX_H3_R2V_MODEL_ID = 'minimax-h3-ref2va-fp8_r2v';
2140
2145
  const MINIMAX_H3_R2V_TURBO_MODEL_ID = 'minimax-h3-ref2va-fp8_r2v_turbo';
2146
+ const MINIMAX_H3_R2V_BALANCED_MODEL_ID = 'minimax-h3-ref2va-fp8_r2v_balanced';
2141
2147
  const MINIMAX_H3_REFERENCE_LIMITS = Object.freeze({
2142
2148
  images: 9,
2143
2149
  videos: 3,
@@ -2238,6 +2244,29 @@ function resolveSkillVideoModelAlias(
2238
2244
  if (normalized === 'minimax-h3-flf2v-turbo') {
2239
2245
  return 'minimax-h3-fl2va-fp8_flf2v_turbo';
2240
2246
  }
2247
+ if (normalized === 'minimax-h3-balanced' && workflow) {
2248
+ if (workflow === 'r2v') {
2249
+ return MINIMAX_H3_R2V_BALANCED_MODEL_ID;
2250
+ }
2251
+ if (workflow === 'i2v') {
2252
+ return hasStartFrame && hasEndFrame
2253
+ ? 'minimax-h3-fl2va-fp8_flf2v_balanced'
2254
+ : 'minimax-h3-fl2va-fp8_i2v_balanced';
2255
+ }
2256
+ return 'minimax-h3-fl2va-fp8_t2v_balanced';
2257
+ }
2258
+ if (normalized === 'minimax-h3-t2v-balanced') {
2259
+ return 'minimax-h3-fl2va-fp8_t2v_balanced';
2260
+ }
2261
+ if (normalized === 'minimax-h3-i2v-balanced') {
2262
+ return 'minimax-h3-fl2va-fp8_i2v_balanced';
2263
+ }
2264
+ if (normalized === 'minimax-h3-flf2v-balanced') {
2265
+ return 'minimax-h3-fl2va-fp8_flf2v_balanced';
2266
+ }
2267
+ if (normalized === 'minimax-h3-r2v-balanced') {
2268
+ return MINIMAX_H3_R2V_BALANCED_MODEL_ID;
2269
+ }
2241
2270
  return normalized === '10eros' || normalized === 'ltx23-eros'
2242
2271
  ? LTX23_10EROS_MODEL_ID
2243
2272
  : modelId;
@@ -2253,7 +2282,9 @@ function isMiniMaxH3TurboModel(modelId) {
2253
2282
 
2254
2283
  function isMiniMaxH3R2vModel(modelId) {
2255
2284
  const normalized = String(modelId || '').trim().toLowerCase();
2256
- return normalized === MINIMAX_H3_R2V_MODEL_ID || normalized === MINIMAX_H3_R2V_TURBO_MODEL_ID;
2285
+ return normalized === MINIMAX_H3_R2V_MODEL_ID
2286
+ || normalized === MINIMAX_H3_R2V_TURBO_MODEL_ID
2287
+ || normalized === MINIMAX_H3_R2V_BALANCED_MODEL_ID;
2257
2288
  }
2258
2289
 
2259
2290
  function isMiniMaxH3R2vTurboSelectionLocal(modelId, workflow = null) {
@@ -2275,6 +2306,11 @@ function isMiniMaxH3ModelSelectionLocal(modelId) {
2275
2306
  || normalized === 'minimax-h3-i2v-turbo'
2276
2307
  || normalized === 'minimax-h3-flf2v-turbo'
2277
2308
  || normalized === 'minimax-h3-r2v-turbo'
2309
+ || normalized === 'minimax-h3-balanced'
2310
+ || normalized === 'minimax-h3-t2v-balanced'
2311
+ || normalized === 'minimax-h3-i2v-balanced'
2312
+ || normalized === 'minimax-h3-flf2v-balanced'
2313
+ || normalized === 'minimax-h3-r2v-balanced'
2278
2314
  || isMiniMaxH3Model(normalized);
2279
2315
  }
2280
2316
 
@@ -2298,6 +2334,10 @@ function miniMaxH3ModeFromModelId(modelId) {
2298
2334
  if (normalized === 'minimax-h3-i2v-turbo') return 'i2v';
2299
2335
  if (normalized === 'minimax-h3-flf2v-turbo') return 'flf2v';
2300
2336
  if (normalized === 'minimax-h3-r2v-turbo') return 'r2v';
2337
+ if (normalized === 'minimax-h3-t2v-balanced') return 't2v';
2338
+ if (normalized === 'minimax-h3-i2v-balanced') return 'i2v';
2339
+ if (normalized === 'minimax-h3-flf2v-balanced') return 'flf2v';
2340
+ if (normalized === 'minimax-h3-r2v-balanced') return 'r2v';
2301
2341
  return MINIMAX_H3_MODEL_MODES.get(normalized) || null;
2302
2342
  }
2303
2343
 
@@ -2622,6 +2662,10 @@ const options = {
2622
2662
  extractFrameAt: null, // --extract-frame-at <video> <seconds> <image>
2623
2663
  extractFrameAtSeconds: null,
2624
2664
  extractFrameAtOutput: null,
2665
+ trimVideo: null, // --trim-video <video> <start> <duration> <output>
2666
+ trimVideoStart: null,
2667
+ trimVideoDuration: null,
2668
+ trimVideoOutput: null,
2625
2669
  verifyVideo: null, // --verify-video <video>: probe streams and decode the full file
2626
2670
  sourceReelDir: null, // --source-reel <image-folder>: animate folder images into a stitched video
2627
2671
  sourceReelImageSeconds: 3,
@@ -3302,6 +3346,25 @@ for (let i = 0; i < args.length; i++) {
3302
3346
  options.extractFrameAt = videoArg;
3303
3347
  options.extractFrameAtSeconds = parseNonNegativeNumberValue(secondsRaw, arg + ' (seconds)');
3304
3348
  options.extractFrameAtOutput = imageArg;
3349
+ } else if (arg === '--trim-video') {
3350
+ const videoArg = requireFlagValue(args, i, arg);
3351
+ i++;
3352
+ const startRaw = requireFlagValue(args, i, arg + ' (start seconds)');
3353
+ i++;
3354
+ const durationRaw = requireFlagValue(args, i, arg + ' (duration seconds)');
3355
+ i++;
3356
+ const outputArg = requireFlagValue(args, i, arg + ' (output video)');
3357
+ i++;
3358
+ options.trimVideo = videoArg;
3359
+ options.trimVideoStart = parseNonNegativeNumberValue(startRaw, arg + ' (start seconds)');
3360
+ options.trimVideoDuration = parseNumberValue(durationRaw, arg + ' (duration seconds)');
3361
+ if (options.trimVideoDuration <= 0) {
3362
+ fatalCliError('--trim-video duration must be greater than zero.', {
3363
+ code: 'INVALID_ARGUMENT',
3364
+ details: { flag: '--trim-video', duration: options.trimVideoDuration }
3365
+ });
3366
+ }
3367
+ options.trimVideoOutput = outputArg;
3305
3368
  } else if (arg === '--verify-video') {
3306
3369
  const raw = requireFlagValue(args, i, arg);
3307
3370
  i++;
@@ -3962,6 +4025,7 @@ General:
3962
4025
  --extract-last-frame <video> <image> Extract last frame from a video (safe ffmpeg wrapper)
3963
4026
  --extract-first-frame <video> <image> Extract first frame from a video (safe ffmpeg wrapper)
3964
4027
  --extract-frame-at <video> <sec> <image> Extract a timestamped frame (safe ffmpeg wrapper)
4028
+ --trim-video <video> <start> <duration> <output> Create a frame-accurate H.264/AAC clip
3965
4029
  --verify-video <video> Verify streams and fully decode a video (safe ffmpeg/ffprobe wrapper)
3966
4030
  --concat-videos <out> <clips...> Concatenate video clips (safe ffmpeg wrapper, min 2 clips).
3967
4031
  Normalizes fps/size and fills silent audio so mismatched clips stitch cleanly.
@@ -4062,7 +4126,7 @@ HappyHorse 1.1 Video Model Selectors (3-15s, fixed 24fps, native audio, 720P/108
4062
4126
  happyhorse-1.1-r2v Reference-to-video from 1-9 reference images (-c/--context)
4063
4127
 
4064
4128
  MiniMax H3 Video Model Selectors (fixed 24fps, native 32kHz stereo audio + dialogue,
4065
- frames 124+n*17 = 5.17-15.08s, sizes /32 up to 1,032,192px. FL2VA/Turbo and
4129
+ frames 124+n*17 = 5.17-15.08s, sizes /32 up to 1,032,192px. FL2VA/Balanced/Turbo and
4066
4130
  image-only R2V need 32GB-class workers; video-conditioned R2V needs above 40GB.
4067
4131
  Prompts use MiniMax's exact ordered-field contracts and [Shot N] notation; see
4068
4132
  references/video-prompting.md "MiniMax H3 Prompting". No negative prompt field:
@@ -4072,6 +4136,11 @@ state negatives in the structured prompt.):
4072
4136
  minimax-h3-flf2v First-frame -> last-frame transition (--ref plus --ref-end)
4073
4137
  minimax-h3-r2v Multi-reference video: --ref/-c images, repeatable --ref-video/--ref-audio
4074
4138
  (9 images / 3 videos / 3 audios / 12 files total; requires an image or video)
4139
+ minimax-h3-balanced Fixed 8-step Euler/simple PDD tier; infers T2VA/I2VA/L2VA/FL2VA
4140
+ minimax-h3-t2v-balanced Balanced text-to-video
4141
+ minimax-h3-i2v-balanced Balanced I2VA (--ref) or L2VA (--ref-end)
4142
+ minimax-h3-flf2v-balanced Balanced first-frame -> last-frame (--ref plus --ref-end)
4143
+ minimax-h3-r2v-balanced Balanced Ref2VA with loose image/video/audio references
4075
4144
  minimax-h3-turbo 4-step Turbo; --ref selects I2VA, --ref-end L2VA, and both FL2VA
4076
4145
  minimax-h3-t2v-turbo 4-step Turbo text-to-video
4077
4146
  minimax-h3-i2v-turbo 4-step Turbo I2VA (--ref) or L2VA (--ref-end)
@@ -4528,30 +4597,97 @@ if (options.music && options.loras.length > 0) {
4528
4597
  }
4529
4598
 
4530
4599
  if (options.video && options.loras.length > 0) {
4531
- const unsupportedVideoLoras = options.loras.filter(loraId => loraId !== DR34ML4Y_LORA_ID);
4532
- if (unsupportedVideoLoras.length > 0) {
4533
- fatalCliError(
4534
- `Video LoRA "${unsupportedVideoLoras[0]}" is not supported. ` +
4535
- `The supported video LoRA is "${DR34ML4Y_LORA_ID}".`,
4536
- { code: 'INVALID_ARGUMENT' }
4537
- );
4538
- }
4539
- if (!DR34ML4Y_SUPPORTED_MODEL_IDS.has(options.model)) {
4540
- fatalCliError(
4541
- `"${DR34ML4Y_LORA_ID}" requires a supported LTX-2.3 I2V model: ` +
4542
- 'ltx23-22b-fp8_i2v, ltx23-22b-fp8_i2v_dev, or 10eros. ' +
4543
- 'The separately trained WAN DR34ML4Y artifact is not installed on Sogni.',
4544
- { code: 'INVALID_ARGUMENT' }
4545
- );
4600
+ if (options.loras.length > 8) {
4601
+ fatalCliError('Video generation supports at most 8 LoRAs per render.', {
4602
+ code: 'INVALID_ARGUMENT',
4603
+ details: { loras: options.loras.length, maximum: 8 }
4604
+ });
4546
4605
  }
4547
- if (!options.noFilter) {
4548
- fatalCliError(
4549
- `"${DR34ML4Y_LORA_ID}" is an opt-in mature-theme LoRA and requires --no-filter.`,
4550
- { code: 'INVALID_ARGUMENT' }
4606
+
4607
+ if (options.loras.includes(DR34ML4Y_LORA_ID)) {
4608
+ // dr34ml4y is worker-internal: it ships no public catalog row, so it cannot
4609
+ // be checked against the catalog and keeps the hardcoded gate it has always
4610
+ // had. Mixing it with a catalogued adapter is a model conflict either way.
4611
+ const foreignLoras = options.loras.filter(loraId => loraId !== DR34ML4Y_LORA_ID);
4612
+ if (foreignLoras.length > 0) {
4613
+ fatalCliError(
4614
+ `"${DR34ML4Y_LORA_ID}" cannot be stacked with "${foreignLoras[0]}"; ` +
4615
+ 'they belong to different model families.',
4616
+ { code: 'INVALID_ARGUMENT' }
4617
+ );
4618
+ }
4619
+ if (!DR34ML4Y_SUPPORTED_MODEL_IDS.has(options.model)) {
4620
+ fatalCliError(
4621
+ `"${DR34ML4Y_LORA_ID}" requires a supported LTX-2.3 I2V model: ` +
4622
+ 'ltx23-22b-fp8_i2v, ltx23-22b-fp8_i2v_dev, or 10eros. ' +
4623
+ 'The separately trained WAN DR34ML4Y artifact is not installed on Sogni.',
4624
+ { code: 'INVALID_ARGUMENT' }
4625
+ );
4626
+ }
4627
+ if (!options.noFilter) {
4628
+ fatalCliError(
4629
+ `"${DR34ML4Y_LORA_ID}" is an opt-in mature-theme LoRA and requires --no-filter.`,
4630
+ { code: 'INVALID_ARGUMENT' }
4631
+ );
4632
+ }
4633
+ if (options.loraStrengths.length === 0) {
4634
+ options.loraStrengths = options.loras.map(() => DR34ML4Y_DEFAULT_STRENGTH);
4635
+ }
4636
+ } else {
4637
+ // Every publicly catalogued video LoRA — the MiniMax H3 adapters today — is
4638
+ // checked against the live catalog for the RESOLVED model id. Keying on the
4639
+ // catalog rather than a hardcoded list means an adapter published later
4640
+ // works without a CLI release, and a wrong id fails here instead of being
4641
+ // dropped server-side and rendering as if no LoRA had been asked for.
4642
+ let videoLoraCatalog;
4643
+ try {
4644
+ videoLoraCatalog = await fetchLoraCatalog(options.model);
4645
+ } catch (cause) {
4646
+ fatalCliError(
4647
+ `Could not read the LoRA catalog for "${options.model}": ${cause?.message || cause}`,
4648
+ { code: cause?.code || 'LORA_CATALOG_UNAVAILABLE' }
4649
+ );
4650
+ }
4651
+ const videoLoraEntries = new Map(
4652
+ (videoLoraCatalog?.loras || [])
4653
+ .map(loraCatalogEntryFromPayload)
4654
+ .filter(entry => entry.loraId)
4655
+ .map(entry => [entry.loraId, entry])
4551
4656
  );
4552
- }
4553
- if (options.loraStrengths.length === 0) {
4554
- options.loraStrengths = options.loras.map(() => DR34ML4Y_DEFAULT_STRENGTH);
4657
+ const unknownVideoLoras = options.loras.filter(loraId => !videoLoraEntries.has(loraId));
4658
+ if (unknownVideoLoras.length > 0) {
4659
+ const availableIds = [...videoLoraEntries.keys()];
4660
+ const isUnresolvedH3Alias = /^minimax-h3(-turbo)?$/.test(String(options.model || ''));
4661
+ fatalCliError(
4662
+ `Video LoRA "${unknownVideoLoras[0]}" is not published for model "${options.model}". ` +
4663
+ (availableIds.length > 0
4664
+ ? `Available for this model: ${availableIds.join(', ')}.`
4665
+ : isUnresolvedH3Alias
4666
+ ? 'Name an explicit H3 mode (for example -m minimax-h3-i2v); LoRA availability differs per mode.'
4667
+ : 'That model loads no LoRAs.') +
4668
+ ' Run --list-loras --lora-model <id> for the live catalog.',
4669
+ { code: 'INVALID_ARGUMENT' }
4670
+ );
4671
+ }
4672
+ const matureVideoLoras = options.loras.filter(loraId => {
4673
+ const entry = videoLoraEntries.get(loraId);
4674
+ return Boolean(entry?.nsfw || entry?.sexual);
4675
+ });
4676
+ if (matureVideoLoras.length > 0 && !options.noFilter) {
4677
+ fatalCliError(
4678
+ `"${matureVideoLoras[0]}" is an opt-in mature-theme LoRA and requires --no-filter.`,
4679
+ { code: 'INVALID_ARGUMENT' }
4680
+ );
4681
+ }
4682
+ if (options.loraStrengths.length === 0) {
4683
+ // The catalog default, not 1.0: the worker falls back to 1.0 for any LoRA
4684
+ // sent without a strength, which for h3-realism-people is already the top
4685
+ // of its usable band.
4686
+ options.loraStrengths = options.loras.map(loraId => {
4687
+ const entry = videoLoraEntries.get(loraId);
4688
+ return Number.isFinite(entry?.default) ? entry.default : 1;
4689
+ });
4690
+ }
4555
4691
  }
4556
4692
  }
4557
4693
 
@@ -4666,11 +4802,12 @@ if (options.video) {
4666
4802
  options.model = WAN3_MODEL_ID;
4667
4803
  }
4668
4804
 
4669
- // MiniMax H3 has four concrete worker selectors and five prompt shapes. The
4670
- // FL2VA checkpoint covers t2v, first-frame i2v, last-frame-only l2v, and
4671
- // first/last-frame (represented by the CLI's i2v workflow); Ref2VA is a
4672
- // separate r2v checkpoint and is never inferred from loose references alone.
4673
- // Selecting minimax-h3-r2v or explicitly passing --workflow r2v is required.
4805
+ // Each MiniMax H3 tier has four concrete worker selectors and five prompt
4806
+ // shapes. The FL2VA checkpoint covers t2v, first-frame i2v, last-frame-only
4807
+ // l2v, and first/last-frame (represented by the CLI's i2v workflow); Ref2VA
4808
+ // is a separate r2v checkpoint and is never inferred from loose references.
4809
+ // Selecting the tier's minimax-h3-r2v* alias or explicitly passing
4810
+ // --workflow r2v with its bare tier selector is required.
4674
4811
  if (isMiniMaxH3ModelSelectionLocal(options.model)) {
4675
4812
  const pinnedMode = miniMaxH3ModeFromModelId(options.model);
4676
4813
  const pinnedWorkflow = pinnedMode === 'flf2v' ? 'i2v' : pinnedMode;
@@ -5032,6 +5169,7 @@ const commandUsesGenerationSeed = !options.apiChat &&
5032
5169
  !options.extractFrameAt &&
5033
5170
  !options.verifyVideo &&
5034
5171
  !options.concatVideos &&
5172
+ !options.trimVideo &&
5035
5173
  !options.sourceReelDir &&
5036
5174
  !options.remixAudio &&
5037
5175
  !options.upscaleImage &&
@@ -5073,7 +5211,7 @@ const wan3HasMediaInput = isWan3ModelLocal(options.model) && Boolean(
5073
5211
  || options.wan3ReferenceFileUrl
5074
5212
  || options.wan3ReferenceLinkUrl
5075
5213
  );
5076
- if (!options.prompt && !wan3HasMediaInput && !options.upscaleImage && !options.apiChat && !apiWorkflowUtilityAction && !apiWorkflowStartAction && !apiModelUtilityAction && !liveModelUtilityAction && !loraCatalogUtilityAction && !apiReplayUtilityAction && !contractUtilityAction && !storyboardPlanUtilityAction && !options.estimateVideoCost && !options.multiAngle && !options.showBalance && !options.showVersion && !options.doctor && !options.extractLastFrame && !options.extractFirstFrame && !options.extractFrameAt && !options.verifyVideo && !options.concatVideos && !options.sourceReelDir && !options.remixAudio && !options.listMedia && !options.memoryAction && !options.personalityAction && !personaUtilityAction) {
5214
+ if (!options.prompt && !wan3HasMediaInput && !options.upscaleImage && !options.apiChat && !apiWorkflowUtilityAction && !apiWorkflowStartAction && !apiModelUtilityAction && !liveModelUtilityAction && !loraCatalogUtilityAction && !apiReplayUtilityAction && !contractUtilityAction && !storyboardPlanUtilityAction && !options.estimateVideoCost && !options.multiAngle && !options.showBalance && !options.showVersion && !options.doctor && !options.extractLastFrame && !options.extractFirstFrame && !options.extractFrameAt && !options.trimVideo && !options.verifyVideo && !options.concatVideos && !options.sourceReelDir && !options.remixAudio && !options.listMedia && !options.memoryAction && !options.personalityAction && !personaUtilityAction) {
5077
5215
  fatalCliError('No prompt provided. Use --help for usage.', { code: 'INVALID_ARGUMENT' });
5078
5216
  }
5079
5217
 
@@ -5465,6 +5603,25 @@ if (options.video) {
5465
5603
  if (options.refImageEnd) {
5466
5604
  fatalCliError('MiniMax H3 r2v has no end-frame anchor; use -c/--context for another loose image or minimax-h3-flf2v for first/last frames.', { code: 'INVALID_ARGUMENT' });
5467
5605
  }
5606
+ const localVideoReferences = [options.refVideo, ...options.refVideos]
5607
+ .filter((reference) => reference && !isHttpUrl(reference) && existsSync(reference));
5608
+ for (const reference of localVideoReferences) {
5609
+ const frameRate = probeLocalVideoFrameRate(reference);
5610
+ if (!frameRate) {
5611
+ fatalCliError(
5612
+ `MiniMax H3 r2v could not verify the reference-video frame rate for "${reference}". ` +
5613
+ 'Install ffprobe or provide a readable 24fps file before generation.',
5614
+ { code: 'INVALID_ARGUMENT', details: { reference, fps: null } },
5615
+ );
5616
+ }
5617
+ if (Math.abs(frameRate - 24) > 0.001) {
5618
+ fatalCliError(
5619
+ `MiniMax H3 r2v reference video must be exactly 24fps; "${reference}" is ${frameRate.toFixed(3)}fps. ` +
5620
+ 'Normalize it to 24fps without changing duration before generation, or choreography and soundtrack timing will drift.',
5621
+ { code: 'INVALID_ARGUMENT', details: { reference, fps: frameRate } },
5622
+ );
5623
+ }
5624
+ }
5468
5625
  } else {
5469
5626
  // HappyHorse reference-to-video: 1-9 loose image references via -c/--context.
5470
5627
  if (!Array.isArray(options.contextImages) || options.contextImages.length === 0) {
@@ -9812,6 +9969,29 @@ function parseFrameRate(raw) {
9812
9969
  return Number.isFinite(v) && v > 0 ? v : null;
9813
9970
  }
9814
9971
 
9972
+ function probeLocalVideoFrameRate(filePath) {
9973
+ const ffprobePath = getEnv('FFPROBE_PATH') || 'ffprobe';
9974
+ sanitizePath(ffprobePath, 'FFPROBE_PATH');
9975
+ try {
9976
+ const stdout = execFileSync(
9977
+ ffprobePath,
9978
+ [
9979
+ '-v', 'error',
9980
+ '-select_streams', 'v:0',
9981
+ '-show_entries', 'stream=avg_frame_rate,r_frame_rate',
9982
+ '-of', 'default=noprint_wrappers=1:nokey=1',
9983
+ filePath,
9984
+ ],
9985
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
9986
+ );
9987
+ for (const candidate of String(stdout || '').trim().split(/\s+/)) {
9988
+ const frameRate = parseFrameRate(candidate);
9989
+ if (frameRate) return frameRate;
9990
+ }
9991
+ } catch {}
9992
+ return null;
9993
+ }
9994
+
9815
9995
  // Probe a media file's primary video stream + whether it has any audio.
9816
9996
  // Fields are null when the probe fails (e.g. ffprobe missing); callers fall
9817
9997
  // back to safe defaults unless they explicitly require verification.
@@ -9890,6 +10070,45 @@ async function verifyVideoFile(videoPath) {
9890
10070
  return { ...info, decodable: true };
9891
10071
  }
9892
10072
 
10073
+ async function trimVideoClip(inputPath, startSeconds, durationSeconds, outputPath) {
10074
+ sanitizePath(inputPath, 'trim input video');
10075
+ sanitizePath(outputPath, 'trim output video');
10076
+ const ffmpegPath = await ensureFfmpegAvailable();
10077
+ const result = await runCommand(ffmpegPath, [
10078
+ '-hide_banner',
10079
+ '-loglevel', 'error',
10080
+ '-y',
10081
+ '-i', inputPath,
10082
+ '-ss', String(startSeconds),
10083
+ '-t', String(durationSeconds),
10084
+ '-map', '0:v:0',
10085
+ '-map', '0:a?',
10086
+ '-c:v', 'libx264',
10087
+ '-preset', 'medium',
10088
+ '-crf', '16',
10089
+ '-pix_fmt', 'yuv420p',
10090
+ '-c:a', 'aac',
10091
+ '-b:a', '192k',
10092
+ '-movflags', '+faststart',
10093
+ outputPath
10094
+ ], { captureOutput: true });
10095
+ if (result.error || result.status !== 0 || !isNonEmptyFile(outputPath)) {
10096
+ const err = new Error('Failed to trim video clip.');
10097
+ err.code = 'FFMPEG_TRIM_VIDEO_FAILED';
10098
+ err.details = {
10099
+ inputPath,
10100
+ outputPath,
10101
+ startSeconds,
10102
+ durationSeconds,
10103
+ stderr: result.stderr || '',
10104
+ stdout: result.stdout || '',
10105
+ status: result.status
10106
+ };
10107
+ throw err;
10108
+ }
10109
+ return verifyVideoFile(outputPath);
10110
+ }
10111
+
9893
10112
  // Concatenate clips using the concat *filter* (not the concat demuxer). The
9894
10113
  // demuxer corrupts timestamps when clips differ in fps/timebase and desyncs
9895
10114
  // audio when a clip has no audio track. Here we probe each clip, normalize every
@@ -9915,6 +10134,13 @@ async function buildConcatVideoFromClips(outputPath, clips, { audioPath = null,
9915
10134
  : (fpsList.length ? Math.max(...fpsList) : 24);
9916
10135
  fps = Math.max(1, Math.round(fps));
9917
10136
  const totalDuration = infos.reduce((sum, x) => sum + (x.duration || 0), 0);
10137
+ if (audioPath && !(totalDuration > 0)) {
10138
+ const err = new Error('Cannot replace concatenated audio without readable clip durations.');
10139
+ err.code = 'FFPROBE_VERIFY_FAILED';
10140
+ err.hint = 'Install ffprobe, confirm every clip is playable, and retry.';
10141
+ err.details = { clips, audioPath };
10142
+ throw err;
10143
+ }
9918
10144
 
9919
10145
  const filterParts = [];
9920
10146
  const concatInputs = [];
@@ -9923,15 +10149,21 @@ async function buildConcatVideoFromClips(outputPath, clips, { audioPath = null,
9923
10149
  `[${idx}:v]fps=${fps},scale=${targetW}:${targetH}:force_original_aspect_ratio=decrease,` +
9924
10150
  `pad=${targetW}:${targetH}:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p[v${idx}]`
9925
10151
  );
9926
- if (info.hasAudio) {
9927
- filterParts.push(`[${idx}:a]aresample=async=1:first_pts=0,aformat=sample_rates=44100:channel_layouts=stereo[a${idx}]`);
9928
- } else {
9929
- const dur = info.duration && info.duration > 0 ? info.duration : (1 / fps);
9930
- filterParts.push(`anullsrc=channel_layout=stereo:sample_rate=44100,atrim=duration=${dur.toFixed(6)},asetpts=PTS-STARTPTS[a${idx}]`);
10152
+ if (!audioPath) {
10153
+ if (info.hasAudio) {
10154
+ filterParts.push(`[${idx}:a]aresample=async=1:first_pts=0,aformat=sample_rates=44100:channel_layouts=stereo[a${idx}]`);
10155
+ } else {
10156
+ const dur = info.duration && info.duration > 0 ? info.duration : (1 / fps);
10157
+ filterParts.push(`anullsrc=channel_layout=stereo:sample_rate=44100,atrim=duration=${dur.toFixed(6)},asetpts=PTS-STARTPTS[a${idx}]`);
10158
+ }
9931
10159
  }
9932
- concatInputs.push(`[v${idx}][a${idx}]`);
10160
+ concatInputs.push(audioPath ? `[v${idx}]` : `[v${idx}][a${idx}]`);
9933
10161
  });
9934
- filterParts.push(`${concatInputs.join('')}concat=n=${infos.length}:v=1:a=1[cv][ca]`);
10162
+ filterParts.push(
10163
+ audioPath
10164
+ ? `${concatInputs.join('')}concat=n=${infos.length}:v=1:a=0[cv]`
10165
+ : `${concatInputs.join('')}concat=n=${infos.length}:v=1:a=1[cv][ca]`
10166
+ );
9935
10167
 
9936
10168
  const args = ['-y'];
9937
10169
  clips.forEach((clip) => { args.push('-i', clip); });
@@ -11611,6 +11843,39 @@ async function main() {
11611
11843
  return;
11612
11844
  }
11613
11845
 
11846
+ if (options.trimVideo) {
11847
+ const inputPath = sanitizePath(options.trimVideo, '--trim-video input');
11848
+ const outputPath = sanitizePath(options.trimVideoOutput, '--trim-video output');
11849
+ if (!existsSync(inputPath)) {
11850
+ const err = new Error(`Video file not found: ${inputPath}`);
11851
+ err.code = 'FILE_NOT_FOUND';
11852
+ throw err;
11853
+ }
11854
+ const verification = await trimVideoClip(
11855
+ inputPath,
11856
+ options.trimVideoStart,
11857
+ options.trimVideoDuration,
11858
+ outputPath
11859
+ );
11860
+ if (options.json || JSON_ERROR_MODE) {
11861
+ console.log(JSON.stringify({
11862
+ success: true,
11863
+ type: 'trim-video',
11864
+ inputPath,
11865
+ outputPath,
11866
+ start: options.trimVideoStart,
11867
+ duration: options.trimVideoDuration,
11868
+ ...verification,
11869
+ timestamp: new Date().toISOString()
11870
+ }));
11871
+ } else {
11872
+ console.log(
11873
+ `Trimmed ${options.trimVideoDuration}s from ${options.trimVideoStart}s to: ${outputPath}`
11874
+ );
11875
+ }
11876
+ return;
11877
+ }
11878
+
11614
11879
  if (options.verifyVideo) {
11615
11880
  const videoPath = sanitizePath(options.verifyVideo, '--verify-video input');
11616
11881
  if (!existsSync(videoPath)) {
@@ -12221,6 +12486,33 @@ async function main() {
12221
12486
  const additionalVideoBuffers = isMiniMaxH3R2v
12222
12487
  ? await Promise.all(options.refVideos.map((reference) => fetchMediaBuffer(reference)))
12223
12488
  : [];
12489
+ const miniMaxH3ReferenceVideoDurations = isMiniMaxH3R2v
12490
+ ? await Promise.all(
12491
+ [
12492
+ ...(videoBuffer ? [{ buffer: videoBuffer, source: options.refVideo }] : []),
12493
+ ...additionalVideoBuffers.map((buffer, index) => ({
12494
+ buffer,
12495
+ source: options.refVideos[index]
12496
+ }))
12497
+ ].map(async ({ buffer, source }, index) => {
12498
+ const duration = await probeLocalMediaDurationSeconds(source)
12499
+ ?? await probeMediaBufferDurationSeconds(
12500
+ buffer,
12501
+ mediaFilenameFromSource(source, `h3-reference-video-${index + 1}.mp4`)
12502
+ );
12503
+ if (!Number.isFinite(duration) || duration < 2 || duration > 15) {
12504
+ fatalCliError(
12505
+ `MiniMax H3 reference video ${index + 1} must be between 2 and 15 seconds.`,
12506
+ {
12507
+ code: 'INVALID_ARGUMENT',
12508
+ details: { source, duration: duration ?? null }
12509
+ }
12510
+ );
12511
+ }
12512
+ return duration;
12513
+ })
12514
+ )
12515
+ : [];
12224
12516
  let pretrimmedMiniMaxH3ReferenceAudio = false;
12225
12517
  if (audioBuffer) {
12226
12518
  audioBuffer = await prepareReferenceAudioForVideoBuffer(audioBuffer, options.refAudio);
@@ -12485,6 +12777,9 @@ async function main() {
12485
12777
  if (additionalVideoBuffers.length > 0) {
12486
12778
  projectConfig.referenceVideos = additionalVideoBuffers;
12487
12779
  }
12780
+ if (miniMaxH3ReferenceVideoDurations.length > 0) {
12781
+ projectConfig.referenceVideoDurations = miniMaxH3ReferenceVideoDurations;
12782
+ }
12488
12783
  if (seedanceReferenceImageUrls.length > 0) {
12489
12784
  projectConfig.referenceImageUrls = seedanceReferenceImageUrls;
12490
12785
  }
package/version.mjs CHANGED
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '3.35.4';
1
+ export const PACKAGE_VERSION = '3.37.0';