@sogni-ai/sogni-creative-agent-skill 3.16.1 → 3.17.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/sogni-agent.mjs CHANGED
@@ -11,7 +11,7 @@ import './node-version-check.mjs';
11
11
  import JSON5 from 'json5';
12
12
  import { createHash, randomBytes } from 'crypto';
13
13
  import { createRequire } from 'module';
14
- import { readFileSync, writeFileSync, existsSync, mkdirSync, mkdtempSync, statSync, readdirSync, realpathSync, lstatSync, unlinkSync, rmdirSync, rmSync } from 'fs';
14
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, mkdtempSync, statSync, readdirSync, realpathSync, lstatSync, unlinkSync, rmdirSync, rmSync, renameSync } from 'fs';
15
15
  import { join, dirname, basename, extname, sep, resolve } from 'path';
16
16
  import { homedir, tmpdir } from 'os';
17
17
  import sharp from 'sharp';
@@ -49,7 +49,7 @@ import {
49
49
  dimensionsForAspectRatio,
50
50
  dimensionsWithShortSide,
51
51
  dispatchPublicSkillToolCall,
52
- getModelDefaults,
52
+ getModelDefaults as getSharedModelDefaults,
53
53
  getVideoPromptGuardrailPlan,
54
54
  inferVideoWorkflowFromAssets,
55
55
  inferVideoWorkflowFromModel,
@@ -99,7 +99,6 @@ const SPARK_PACKS_PURCHASE_URL = 'https://docs.sogni.ai/pricing/#spark-packs';
99
99
  const SPARK_PACKS_PURCHASE_HINT = `Buy Spark Packs to continue: ${SPARK_PACKS_PURCHASE_URL}`;
100
100
 
101
101
  const UNLIMITED_PLAN_URL = 'https://docs.sogni.ai/pricing/unlimited-plan-details';
102
- const SOGNI_MODEL_CATALOG_URL = 'https://www.sogni.ai/models';
103
102
  const SOGNI_MODEL_CATALOG_MAX_BYTES = 5 * 1024 * 1024;
104
103
  const SOGNI_MODEL_CATALOG_TIMEOUT_MS = 10000;
105
104
  const KNOWN_MODEL_CATALOG_TAGS = new Set([
@@ -240,6 +239,7 @@ function sanitizePath(p, label) {
240
239
 
241
240
  const DEFAULT_CREDENTIALS_PATH = join(homedir(), '.config', 'sogni', 'credentials');
242
241
  const DEFAULT_LAST_RENDER_PATH = join(homedir(), '.config', 'sogni', 'last-render.json');
242
+ const DEFAULT_MODEL_CATALOG_CACHE_PATH = join(homedir(), '.config', 'sogni', 'model-catalog-cache.json');
243
243
  const DEFAULT_OPENCLAW_CONFIG_PATH = join(homedir(), '.openclaw', 'openclaw.json');
244
244
  // Current OpenClaw home, with a fallback to the legacy clawdbot-era directory
245
245
  // for installs that predate the rename. Only used when neither
@@ -376,6 +376,169 @@ const MUSIC_MODEL_DEFAULTS = {
376
376
  scheduler: { allowed: ['simple', 'linear_quadratic'], default: 'linear_quadratic' }
377
377
  }
378
378
  };
379
+ const DEFAULT_MODEL_CATALOG_URL = 'https://api.sogni.ai/v1/model-catalog';
380
+ const MODEL_CATALOG_CACHE_TTL_MS = 5 * 60 * 1000;
381
+ let liveModelDefaults = null;
382
+
383
+ function getModelDefaults(modelId, config) {
384
+ const sharedDefaults = getSharedModelDefaults(modelId, config);
385
+ const catalogDefaults = liveModelDefaults?.[modelId];
386
+ if (!catalogDefaults) return sharedDefaults;
387
+ const configuredDefaults = config?.modelDefaults?.[modelId];
388
+ // The live catalog supersedes bundled registry data. Explicit user config
389
+ // remains the final override.
390
+ return { ...(sharedDefaults || {}), ...catalogDefaults, ...(configuredDefaults || {}) };
391
+ }
392
+
393
+ function defaultsFromModelTier(card) {
394
+ const defaults = {};
395
+ if (Number.isFinite(card?.steps?.default)) defaults.steps = card.steps.default;
396
+ if (Number.isFinite(card?.guidance?.default)) defaults.guidance = card.guidance.default;
397
+ if (card?.comfySampler?.default) defaults.sampler = card.comfySampler.default;
398
+ if (card?.comfyScheduler?.default) defaults.scheduler = card.comfyScheduler.default;
399
+ if (Number.isFinite(card?.width?.default)) defaults.defaultWidth = card.width.default;
400
+ if (Number.isFinite(card?.height?.default)) defaults.defaultHeight = card.height.default;
401
+ if (Number.isFinite(card?.width?.min)) defaults.minDimension = card.width.min;
402
+ if (Number.isFinite(card?.width?.max)) defaults.maxDimension = card.width.max;
403
+ if (Number.isFinite(card?.width?.step)) defaults.dimensionMultiple = card.width.step;
404
+ return defaults;
405
+ }
406
+
407
+ function validateModelTierSelections(modelId, card) {
408
+ const validateRange = (source, value, range) => {
409
+ if (value === null || value === undefined || !range) return;
410
+ if (
411
+ (Number.isFinite(range.min) && value < range.min) ||
412
+ (Number.isFinite(range.max) && value > range.max)
413
+ ) {
414
+ const error = new Error(
415
+ `${source} ${value} is outside the live catalog range for "${modelId}" ` +
416
+ `(${range.min}–${range.max}).`
417
+ );
418
+ error.code = 'INVALID_MODEL_PARAMETER';
419
+ error.hint = `Use a value between ${range.min} and ${range.max}. Catalog: ${MODEL_CATALOG_URL}`;
420
+ throw error;
421
+ }
422
+ };
423
+ validateRange('--steps', options.steps, card.steps);
424
+ validateRange('--guidance', options.guidance, card.guidance);
425
+ const configuredDefaults = openclawConfig?.modelDefaults?.[modelId];
426
+ validateRange('Configured steps', configuredDefaults?.steps, card.steps);
427
+ validateRange('Configured guidance', configuredDefaults?.guidance, card.guidance);
428
+ }
429
+
430
+ function persistModelCatalogCache(catalog, cachePath = MODEL_CATALOG_CACHE_PATH) {
431
+ const tempPath = `${cachePath}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
432
+ try {
433
+ mkdirSync(dirname(cachePath), { recursive: true });
434
+ writeFileSync(tempPath, JSON.stringify(catalog), { mode: 0o600 });
435
+ renameSync(tempPath, cachePath);
436
+ } catch (error) {
437
+ if (!options.quiet) {
438
+ console.error(`Warning: could not persist model catalog cache (${error?.message || error}).`);
439
+ }
440
+ } finally {
441
+ try {
442
+ if (existsSync(tempPath)) unlinkSync(tempPath);
443
+ } catch {
444
+ // Cache cleanup is best-effort and must never block generation.
445
+ }
446
+ }
447
+ }
448
+
449
+ async function loadLiveModelDefaults(modelId) {
450
+ // Existing CLI tests mock the SDK rather than the public catalog API.
451
+ // A supplied JSON fixture opts a test into exercising this lookup.
452
+ const testFixture = getEnv('SOGNI_AGENT_TEST_MODEL_TIERS_JSON');
453
+ let cachedCatalog = null;
454
+ try {
455
+ if (existsSync(MODEL_CATALOG_CACHE_PATH)) {
456
+ const cached = JSON.parse(readFileSync(MODEL_CATALOG_CACHE_PATH, 'utf8'));
457
+ const cacheAge = Date.now() - cached?.fetchedAt;
458
+ if (
459
+ Number.isFinite(cached?.fetchedAt) &&
460
+ cacheAge >= 0 &&
461
+ cached?.modelId === modelId &&
462
+ cached?.descriptor?.parameters &&
463
+ typeof cached.descriptor.parameters === 'object'
464
+ ) {
465
+ cachedCatalog = cached;
466
+ if (cacheAge < MODEL_CATALOG_CACHE_TTL_MS) {
467
+ const card = cached.descriptor.parameters;
468
+ validateModelTierSelections(modelId, card);
469
+ liveModelDefaults = { [modelId]: defaultsFromModelTier(card) };
470
+ return;
471
+ }
472
+ }
473
+ }
474
+ } catch {
475
+ // A corrupt cache is treated as a miss and replaced by the live response.
476
+ }
477
+
478
+ if (
479
+ !testFixture &&
480
+ getEnv('SOGNI_AGENT_TEST_STATE_PATH') &&
481
+ !getEnv('SOGNI_MODEL_CATALOG_URL')
482
+ ) return;
483
+
484
+ let catalog;
485
+ try {
486
+ if (testFixture) {
487
+ const fixture = JSON.parse(testFixture);
488
+ const descriptor = fixture?.data?.model || fixture?.model || (() => {
489
+ const model = fixture?.models?.find?.((entry) => entry?.id === modelId);
490
+ const tierId = model?.tier || modelId;
491
+ const parameters = fixture?.tiers?.[tierId] || (!fixture?.tiers ? fixture?.[tierId] : null);
492
+ return parameters ? { id: modelId, parameters } : null;
493
+ })();
494
+ catalog = { fetchedAt: Date.now(), modelId, etag: null, descriptor };
495
+ } else {
496
+ const url = `${MODEL_CATALOG_URL}/${encodeURIComponent(modelId)}`;
497
+ const headers = { accept: 'application/json' };
498
+ if (cachedCatalog?.etag) headers['if-none-match'] = cachedCatalog.etag;
499
+ const response = await fetch(url, {
500
+ headers,
501
+ signal: AbortSignal.timeout(10_000)
502
+ });
503
+ if (response.status === 304 && cachedCatalog) {
504
+ catalog = { ...cachedCatalog, fetchedAt: Date.now() };
505
+ } else {
506
+ if (response.status === 404) {
507
+ const error = new Error(`Model "${modelId}" is not present in the live Sogni model catalog.`);
508
+ error.code = 'MODEL_NOT_FOUND';
509
+ error.hint = `Choose a model currently listed by ${MODEL_CATALOG_URL}`;
510
+ throw error;
511
+ }
512
+ if (!response.ok) throw new Error(`${url} returned HTTP ${response.status}`);
513
+ const payload = await response.json();
514
+ catalog = {
515
+ fetchedAt: Date.now(),
516
+ modelId,
517
+ etag: response.headers.get('etag'),
518
+ descriptor: payload?.data?.model
519
+ };
520
+ }
521
+ }
522
+ persistModelCatalogCache(catalog);
523
+ } catch (cause) {
524
+ if (cause?.code === 'MODEL_NOT_FOUND') throw cause;
525
+ const error = new Error(`Could not load the live Sogni model catalog (${cause?.message || cause}).`);
526
+ error.code = 'MODEL_CATALOG_UNAVAILABLE';
527
+ error.hint = `Check Sogni platform status and retry. Catalog: ${MODEL_CATALOG_URL}`;
528
+ throw error;
529
+ }
530
+
531
+ const card = catalog?.descriptor?.parameters;
532
+ if (!card || typeof card !== 'object') {
533
+ const error = new Error(`Model "${modelId}" is not present in the live Sogni model catalog.`);
534
+ error.code = 'MODEL_NOT_FOUND';
535
+ error.hint = `Choose a model currently listed by ${MODEL_CATALOG_URL}`;
536
+ throw error;
537
+ }
538
+ validateModelTierSelections(modelId, card);
539
+ liveModelDefaults = { [modelId]: defaultsFromModelTier(card) };
540
+ }
541
+
379
542
  const MUSIC_DURATION_LIMITS = { min: 10, max: 600, default: 30 };
380
543
  const MUSIC_BPM_LIMITS = { min: 30, max: 300, default: 120 };
381
544
  const MUSIC_PROMPT_STRENGTH_LIMITS = { min: 0, max: 10 };
@@ -1243,8 +1406,23 @@ const DEFAULT_VIDEO_DIMENSION_RULES = {
1243
1406
  };
1244
1407
  const WRAPPER_MAX_VIDEO_DIMENSION = 2048;
1245
1408
  const WRAPPER_MAX_WAN_VIDEO_DIMENSION = 1536;
1409
+
1410
+ // SogniClientWrapper.normalizeVideoDimensions in @sogni-ai/sogni-intelligence-client clamps to
1411
+ // MAX_VIDEO_DIMENSION = 1536 for every model before it resizes a reference image and overwrites
1412
+ // the project dimensions with the resized reference's. So on any reference-bearing workflow a
1413
+ // larger ceiling is not reachable: the CLI waves 1600x896 through as "valid", the wrapper then
1414
+ // clamps to 1536x848 and hands the model a 1514x848 reference that is off-divisor — the exact
1415
+ // failure the i2v sizing logic exists to prevent. Applied only to reference-bearing workflows;
1416
+ // t2v never goes through the reference resize. Keep in sync with the pinned client version.
1417
+ const WRAPPER_MAX_REF_VIDEO_DIMENSION = 1536;
1246
1418
  const VIDEO_DIMENSION_MULTIPLE = DEFAULT_VIDEO_DIMENSION_RULES.dimensionMultiple;
1247
1419
 
1420
+ // i2v reference sizing: when an exact-aspect bounding box would cost more than this share of
1421
+ // the pixel budget, pre-resize the reference to the model cap instead. The aspect ceiling keeps
1422
+ // the swap invisible — a 25:14 source becoming 16:9 drifts 0.44%, far under the limit.
1423
+ const VIDEO_REF_PRERESIZE_MIN_AREA_GAIN = 1.1;
1424
+ const VIDEO_REF_PRERESIZE_MAX_ASPECT_DRIFT = 0.02;
1425
+
1248
1426
  function isWanVideoModelId(modelId) {
1249
1427
  return typeof modelId === 'string' && modelId.startsWith('wan_');
1250
1428
  }
@@ -1400,33 +1578,48 @@ function videoDimensionRulesFromDefaults(modelDefaults, modelId) {
1400
1578
  }
1401
1579
 
1402
1580
  /**
1403
- * Resizes an image buffer to model-compatible dimensions while maintaining aspect ratio.
1404
- * Uses sharp's fit:inside to preserve aspect, then rounds to the model divisor.
1581
+ * Predicts the dimensions `resizeImageBufferForVideo` will produce for a reference image.
1582
+ *
1583
+ * Scales the reference up to the model's max dimension (preserving aspect via fit:inside),
1584
+ * then rounds each side to the nearest model divisor. Unlike an exact-aspect bounding box,
1585
+ * this always reaches the model cap — at the cost of a sub-pixel-percent aspect adjustment.
1586
+ *
1587
+ * `resizeImageBufferForVideo` delegates to this so the prediction can never drift from the
1588
+ * actual resize.
1405
1589
  */
1406
- async function resizeImageBufferForVideo(buffer, originalWidth, originalHeight, rules = DEFAULT_VIDEO_DIMENSION_RULES) {
1590
+ function predictVideoRefPreResizeDims(refWidth, refHeight, rules = DEFAULT_VIDEO_DIMENSION_RULES) {
1591
+ const rw = Number(refWidth);
1592
+ const rh = Number(refHeight);
1593
+ if (!Number.isFinite(rw) || !Number.isFinite(rh) || rw <= 0 || rh <= 0) return null;
1594
+
1407
1595
  const multiple = rules.dimensionMultiple || VIDEO_DIMENSION_MULTIPLE;
1596
+ const minDimension = rules.minDimension || DEFAULT_VIDEO_DIMENSION_RULES.minDimension;
1597
+ const maxDimension = rules.maxDimension || DEFAULT_VIDEO_DIMENSION_RULES.maxDimension;
1408
1598
  const roundToMultiple = (n) => Math.max(multiple, Math.round(n / multiple) * multiple);
1409
- const targetWidth = Math.max(rules.minDimension, Math.min(rules.maxDimension, roundToMultiple(originalWidth)));
1410
- const targetHeight = Math.max(rules.minDimension, Math.min(rules.maxDimension, roundToMultiple(originalHeight)));
1599
+ // Never round past the model's hard limits.
1600
+ const floorMultiple = Math.floor(maxDimension / multiple) * multiple;
1601
+ const ceilMultiple = Math.ceil(minDimension / multiple) * multiple;
1602
+ const clamp = (n) => Math.min(floorMultiple, Math.max(ceilMultiple, roundToMultiple(n)));
1411
1603
 
1412
- // Resize using sharp with fit:inside (maintains aspect ratio)
1413
- const resizedBuffer = await sharp(buffer)
1414
- .resize(targetWidth, targetHeight, { fit: 'inside', withoutEnlargement: false })
1415
- .toBuffer();
1604
+ const boxWidth = Math.max(minDimension, Math.min(maxDimension, roundToMultiple(rw)));
1605
+ const boxHeight = Math.max(minDimension, Math.min(maxDimension, roundToMultiple(rh)));
1606
+ const fitted = predictSharpInsideResizeDims(rw, rh, boxWidth, boxHeight);
1607
+ if (!fitted) return null;
1416
1608
 
1417
- // Get actual dimensions after resize
1418
- const metadata = await sharp(resizedBuffer).metadata();
1419
- const actualWidth = roundToMultiple(metadata.width);
1420
- const actualHeight = roundToMultiple(metadata.height);
1609
+ return { width: clamp(fitted.width), height: clamp(fitted.height) };
1610
+ }
1421
1611
 
1422
- // If dimensions aren't exactly model-compatible, do a final resize/crop.
1423
- if (metadata.width !== actualWidth || metadata.height !== actualHeight) {
1424
- return await sharp(resizedBuffer)
1425
- .resize(actualWidth, actualHeight, { fit: 'cover' })
1426
- .toBuffer();
1427
- }
1612
+ /**
1613
+ * Resizes an image buffer to model-compatible dimensions while maintaining aspect ratio.
1614
+ * Uses sharp's fit:inside to preserve aspect, then rounds to the model divisor.
1615
+ */
1616
+ async function resizeImageBufferForVideo(buffer, originalWidth, originalHeight, rules = DEFAULT_VIDEO_DIMENSION_RULES) {
1617
+ const target = predictVideoRefPreResizeDims(originalWidth, originalHeight, rules);
1618
+ if (!target) return buffer;
1428
1619
 
1429
- return resizedBuffer;
1620
+ return await sharp(buffer)
1621
+ .resize(target.width, target.height, { fit: 'cover', withoutEnlargement: false })
1622
+ .toBuffer();
1430
1623
  }
1431
1624
 
1432
1625
  function normalizeVideoDimensionsLikeWrapper(width, height, rules = DEFAULT_VIDEO_DIMENSION_RULES) {
@@ -1611,6 +1804,19 @@ const OUTPAINT_POSITION_SET = new Set(OUTPAINT_POSITIONS);
1611
1804
  const LTX_TRANSITION_LORA_ID = 'transition';
1612
1805
  const LTX_TRANSITION_TRIGGER = 'zhuanchang';
1613
1806
  const LTX_TRANSITION_DEFAULT_STRENGTH = 1.0;
1807
+ const LTX23_10EROS_MODEL_ID = 'ltx23-22b-10eros-v1.4-fp8mixed_i2v';
1808
+ const DR34ML4Y_LORA_ID = 'dr34ml4y-v3';
1809
+ const DR34ML4Y_DEFAULT_STRENGTH = 1.0;
1810
+ const DR34ML4Y_SUPPORTED_MODEL_IDS = new Set([
1811
+ 'ltx23-22b-fp8_i2v',
1812
+ 'ltx23-22b-fp8_i2v_dev',
1813
+ LTX23_10EROS_MODEL_ID
1814
+ ]);
1815
+
1816
+ function resolveSkillVideoModelAlias(modelId) {
1817
+ const normalized = String(modelId || '').trim().toLowerCase();
1818
+ return normalized === '10eros' ? LTX23_10EROS_MODEL_ID : modelId;
1819
+ }
1614
1820
 
1615
1821
  function normalizeMultiAngleValue(value, aliases, allowedKeys, label) {
1616
1822
  if (!value) return null;
@@ -1661,7 +1867,12 @@ function isLtx23V2VModelId(modelId) {
1661
1867
  }
1662
1868
 
1663
1869
  function isLtxI2vTransitionModelId(modelId) {
1664
- return !!modelId && modelId.includes('ltx') && /_i2v(_|$)/.test(modelId);
1870
+ return (
1871
+ !!modelId &&
1872
+ modelId !== LTX23_10EROS_MODEL_ID &&
1873
+ modelId.includes('ltx') &&
1874
+ /_i2v(_|$)/.test(modelId)
1875
+ );
1665
1876
  }
1666
1877
 
1667
1878
  function applyLtxTransitionLora(projectConfig, modelId, hasStartFrame, hasEndFrame) {
@@ -1785,6 +1996,13 @@ const LAST_RENDER_PATH = resolveConfiguredPath(
1785
1996
  DEFAULT_LAST_RENDER_PATH,
1786
1997
  'SOGNI last render path'
1787
1998
  );
1999
+ const MODEL_CATALOG_CACHE_PATH = resolveConfiguredPath(
2000
+ getEnv('SOGNI_MODEL_CATALOG_CACHE_PATH'),
2001
+ DEFAULT_MODEL_CATALOG_CACHE_PATH,
2002
+ 'Sogni model catalog cache path'
2003
+ );
2004
+ const MODEL_CATALOG_LIST_CACHE_PATH = `${MODEL_CATALOG_CACHE_PATH}.models`;
2005
+ const MODEL_CATALOG_URL = (getEnv('SOGNI_MODEL_CATALOG_URL') || DEFAULT_MODEL_CATALOG_URL).replace(/\/+$/, '');
1788
2006
  const MEDIA_INBOUND_DIR = resolveConfiguredPath(
1789
2007
  getEnv('SOGNI_MEDIA_INBOUND_DIR') || openclawConfig?.mediaInboundDir,
1790
2008
  DEFAULT_MEDIA_INBOUND_DIR,
@@ -3179,6 +3397,7 @@ Recommended LTX 2.3 Video Models:
3179
3397
  ltx23-22b-fp8_ia2v_distilled Image+audio-to-video
3180
3398
  ltx23-22b-fp8_a2v_distilled Audio-to-video
3181
3399
  ltx23-22b-fp8_v2v_distilled Video-to-video with ControlNet
3400
+ ltx23-22b-10eros-v1.4-fp8mixed_i2v Private mature-theme I2V; first and/or last frame; requires --no-filter
3182
3401
 
3183
3402
  Music Models:
3184
3403
  ace_step_1.5_xl_turbo Default direct music generation
@@ -3602,6 +3821,16 @@ if (options.outputFormat) {
3602
3821
  }
3603
3822
  }
3604
3823
 
3824
+ if (options.video) {
3825
+ options.model = resolveSkillVideoModelAlias(options.model);
3826
+ if (options.model === LTX23_10EROS_MODEL_ID && !options.noFilter) {
3827
+ fatalCliError(
3828
+ `LTX-2.3 10Eros is an opt-in mature-theme model and requires --no-filter.`,
3829
+ { code: 'INVALID_ARGUMENT' }
3830
+ );
3831
+ }
3832
+ }
3833
+
3605
3834
  if (options.loraStrengths.length > 0 && options.loras.length === 0) {
3606
3835
  fatalCliError('--lora-strength requires at least one --lora.', { code: 'INVALID_ARGUMENT' });
3607
3836
  }
@@ -3614,8 +3843,36 @@ if (options.loraStrengths.length > 0 && options.loras.length > 0 &&
3614
3843
  });
3615
3844
  }
3616
3845
 
3617
- if ((options.video || options.music) && options.loras.length > 0) {
3618
- fatalCliError('--lora options are image-only.', { code: 'INVALID_ARGUMENT' });
3846
+ if (options.music && options.loras.length > 0) {
3847
+ fatalCliError('--lora options are not supported for music.', { code: 'INVALID_ARGUMENT' });
3848
+ }
3849
+
3850
+ if (options.video && options.loras.length > 0) {
3851
+ const unsupportedVideoLoras = options.loras.filter(loraId => loraId !== DR34ML4Y_LORA_ID);
3852
+ if (unsupportedVideoLoras.length > 0) {
3853
+ fatalCliError(
3854
+ `Video LoRA "${unsupportedVideoLoras[0]}" is not supported. ` +
3855
+ `The supported video LoRA is "${DR34ML4Y_LORA_ID}".`,
3856
+ { code: 'INVALID_ARGUMENT' }
3857
+ );
3858
+ }
3859
+ if (!DR34ML4Y_SUPPORTED_MODEL_IDS.has(options.model)) {
3860
+ fatalCliError(
3861
+ `"${DR34ML4Y_LORA_ID}" requires a supported LTX-2.3 I2V model: ` +
3862
+ 'ltx23-22b-fp8_i2v, ltx23-22b-fp8_i2v_dev, or 10eros. ' +
3863
+ 'The separately trained WAN DR34ML4Y artifact is not installed on Sogni.',
3864
+ { code: 'INVALID_ARGUMENT' }
3865
+ );
3866
+ }
3867
+ if (!options.noFilter) {
3868
+ fatalCliError(
3869
+ `"${DR34ML4Y_LORA_ID}" is an opt-in mature-theme LoRA and requires --no-filter.`,
3870
+ { code: 'INVALID_ARGUMENT' }
3871
+ );
3872
+ }
3873
+ if (options.loraStrengths.length === 0) {
3874
+ options.loraStrengths = options.loras.map(() => DR34ML4Y_DEFAULT_STRENGTH);
3875
+ }
3619
3876
  }
3620
3877
 
3621
3878
  if (options.video && (options.sampler || options.scheduler)) {
@@ -4256,7 +4513,17 @@ if (options.video && !options.frames) {
4256
4513
  // with sharp `fit: inside` and then override the project width/height with the resized reference dims.
4257
4514
  // That means a "valid" requested size can still fail if the resized ref lands off the model divisor.
4258
4515
  if (options.video) {
4259
- const videoDimensionRules = videoDimensionRulesFromDefaults(getModelDefaults(options.model, openclawConfig), options.model);
4516
+ const baseVideoDimensionRules = videoDimensionRulesFromDefaults(getModelDefaults(options.model, openclawConfig), options.model);
4517
+ // A reference image routes through the wrapper's resize, which caps at 1536 for every model
4518
+ // and then adopts the resized reference's dimensions as the project's. Honour that ceiling up
4519
+ // front so the CLI picks a divisor-valid size instead of letting the wrapper clamp blindly.
4520
+ const hasVideoReference = Boolean(options.refImage || options.refImageEnd);
4521
+ const videoDimensionRules = hasVideoReference
4522
+ ? {
4523
+ ...baseVideoDimensionRules,
4524
+ maxDimension: Math.min(baseVideoDimensionRules.maxDimension, WRAPPER_MAX_REF_VIDEO_DIMENSION)
4525
+ }
4526
+ : baseVideoDimensionRules;
4260
4527
  if (!Number.isFinite(options.width) || options.width <= 0 || !Number.isFinite(options.height) || options.height <= 0) {
4261
4528
  fatalCliError('Video width/height must be positive numbers.', {
4262
4529
  code: 'INVALID_ARGUMENT',
@@ -4342,6 +4609,46 @@ if (options.video) {
4342
4609
 
4343
4610
  const beforeW = options.width;
4344
4611
  const beforeH = options.height;
4612
+
4613
+ // An exact-aspect bounding box can only land on sizes where BOTH sides are divisor-valid.
4614
+ // For aspect ratios with sparse valid sizes (e.g. 25:14 on a /16 model, which tops out at
4615
+ // 1200x672 under a 1536 cap) that forfeits a large share of the model's pixel budget.
4616
+ // Pre-resizing the reference reaches the cap instead, trading a tiny aspect adjustment for
4617
+ // the resolution — so prefer it when it wins materially on pixels and barely moves the aspect.
4618
+ const preResize = predictVideoRefPreResizeDims(dims.width, dims.height, videoDimensionRules);
4619
+ const candidateArea = candidate.output ? candidate.output.width * candidate.output.height : 0;
4620
+ const preResizeArea = preResize ? preResize.width * preResize.height : 0;
4621
+ const refAspect = dims.width / dims.height;
4622
+ const aspectDrift = preResize
4623
+ ? Math.abs((preResize.width / preResize.height) - refAspect) / refAspect
4624
+ : Infinity;
4625
+
4626
+ if (preResizeArea > candidateArea * VIDEO_REF_PRERESIZE_MIN_AREA_GAIN
4627
+ && aspectDrift <= VIDEO_REF_PRERESIZE_MAX_ASPECT_DRIFT) {
4628
+ options.width = preResize.width;
4629
+ options.height = preResize.height;
4630
+ options[ref.resizeFlag] = true;
4631
+ options._adjustedVideoDims = {
4632
+ reason: 'i2v-ref-pre-resize',
4633
+ referenceType: ref.key,
4634
+ requested: { width: beforeW, height: beforeH },
4635
+ adjusted: { width: options.width, height: options.height },
4636
+ resizedFrom: predicted,
4637
+ resizedTo: { width: preResize.width, height: preResize.height },
4638
+ insteadOf: candidate.output
4639
+ ? { width: candidate.output.width, height: candidate.output.height }
4640
+ : null
4641
+ };
4642
+ if (!options.quiet) {
4643
+ console.error(
4644
+ `Pre-resizing ${ref.label.toLowerCase()} to ${preResize.width}x${preResize.height} ` +
4645
+ `instead of shrinking the video to ${candidate.output.width}x${candidate.output.height} ` +
4646
+ `(keeps ${Math.round((preResizeArea / candidateArea - 1) * 100)}% more pixels).`
4647
+ );
4648
+ }
4649
+ continue;
4650
+ }
4651
+
4345
4652
  options.width = candidate.width;
4346
4653
  options.height = candidate.height;
4347
4654
 
@@ -4374,12 +4681,17 @@ if (options.video) {
4374
4681
 
4375
4682
  const effectiveDimsSource = localRefDims.get('refImage') || localRefDims.get('refImageEnd') || null;
4376
4683
  if (effectiveDimsSource) {
4377
- const predicted = predictSharpInsideResizeDims(
4378
- effectiveDimsSource.width,
4379
- effectiveDimsSource.height,
4380
- options.width,
4381
- options.height
4382
- );
4684
+ const effectiveResizeFlag = localRefDims.has('refImage') ? '_needsRefResize' : '_needsRefEndResize';
4685
+ // A pre-resized reference reaches the wrapper already divisor-valid, so the video lands on
4686
+ // the pre-resize dims rather than the fit:inside prediction of the original.
4687
+ const predicted = options[effectiveResizeFlag]
4688
+ ? predictVideoRefPreResizeDims(effectiveDimsSource.width, effectiveDimsSource.height, videoDimensionRules)
4689
+ : predictSharpInsideResizeDims(
4690
+ effectiveDimsSource.width,
4691
+ effectiveDimsSource.height,
4692
+ options.width,
4693
+ options.height
4694
+ );
4383
4695
  if (predicted) {
4384
4696
  options._effectiveVideoDims = {
4385
4697
  width: predicted.width,
@@ -5960,119 +6272,94 @@ function normalizeLiveModelTag(value) {
5960
6272
  .replace(/[\s_]+/g, '-');
5961
6273
  }
5962
6274
 
5963
- function decodeModelCatalogAttribute(value) {
5964
- return String(value || '')
5965
- .replace(/&#(\d+);/g, (_match, code) => String.fromCodePoint(Number(code)))
5966
- .replace(/&#x([0-9a-f]+);/gi, (_match, code) => String.fromCodePoint(Number.parseInt(code, 16)))
5967
- .replace(/&quot;/g, '"')
5968
- .replace(/&#39;|&apos;/g, "'")
5969
- .replace(/&lt;/g, '<')
5970
- .replace(/&gt;/g, '>')
5971
- .replace(/&amp;/g, '&');
5972
- }
5973
-
5974
- function modelCatalogEntriesFromHtml(html) {
5975
- const entries = [];
5976
- const anchorPattern = /<a\b[^>]*>/gi;
5977
- let anchorMatch;
5978
- while ((anchorMatch = anchorPattern.exec(String(html || ''))) !== null) {
5979
- const attributes = {};
5980
- const attributePattern = /([:\w-]+)\s*=\s*"([^"]*)"/g;
5981
- let attributeMatch;
5982
- while ((attributeMatch = attributePattern.exec(anchorMatch[0])) !== null) {
5983
- attributes[attributeMatch[1].toLowerCase()] = decodeModelCatalogAttribute(attributeMatch[2]);
5984
- }
5985
- const classes = (attributes.class || '').split(/\s+/);
5986
- if (!classes.includes('mcard')) continue;
5987
-
5988
- const textTokens = (attributes['data-text'] || '')
5989
- .toLocaleLowerCase()
5990
- .split(/\s+/)
5991
- .filter(Boolean);
5992
- const capabilities = (attributes['data-caps'] || '')
5993
- .toLocaleLowerCase()
5994
- .split(/\s+/)
5995
- .filter(Boolean);
5996
- const tags = new Set();
5997
- if (attributes['data-uncensored'] === '1' || capabilities.includes('uncensored')) {
5998
- tags.add('uncensored');
5999
- }
6000
- if (attributes['data-community'] === '1') tags.add('community');
6001
- const tier = normalizeLiveModelTag(attributes['data-tier']);
6002
- if (tier) tags.add(tier);
6003
- for (const tag of KNOWN_MODEL_CATALOG_TAGS) {
6004
- if (textTokens.includes(tag)) tags.add(tag);
6005
- }
6006
- entries.push({
6007
- modelIds: new Set(textTokens),
6008
- tags: [...tags].sort()
6009
- });
6010
- }
6011
- return entries;
6012
- }
6013
-
6014
- async function fetchModelCatalogEntries() {
6015
- if (getEnv('SOGNI_AGENT_TEST_STATE_PATH')) {
6016
- return modelCatalogEntriesFromHtml(getEnv('SOGNI_AGENT_TEST_MODEL_CATALOG_HTML') || '');
6275
+ async function fetchLiveModelCatalog(network, media) {
6276
+ const fixtureJson = getEnv('SOGNI_AGENT_TEST_MODEL_CATALOG_JSON');
6277
+ let cachedCatalog = null;
6278
+ try {
6279
+ if (existsSync(MODEL_CATALOG_LIST_CACHE_PATH)) {
6280
+ const cached = JSON.parse(readFileSync(MODEL_CATALOG_LIST_CACHE_PATH, 'utf8'));
6281
+ const cacheAge = Date.now() - cached?.fetchedAt;
6282
+ if (
6283
+ Number.isFinite(cached?.fetchedAt) &&
6284
+ cacheAge >= 0 &&
6285
+ cached?.network === network &&
6286
+ cached?.media === media &&
6287
+ Array.isArray(cached?.models)
6288
+ ) {
6289
+ cachedCatalog = cached;
6290
+ if (cacheAge < MODEL_CATALOG_CACHE_TTL_MS) return cached;
6291
+ }
6292
+ }
6293
+ } catch {
6294
+ // A corrupt cache is treated as a miss and replaced by the live response.
6017
6295
  }
6018
6296
 
6019
- const controller = new AbortController();
6020
- const timeoutId = setTimeout(() => controller.abort(), SOGNI_MODEL_CATALOG_TIMEOUT_MS);
6021
6297
  try {
6022
- const response = await fetchSafeUrl(
6023
- SOGNI_MODEL_CATALOG_URL,
6024
- {
6025
- headers: { Accept: 'text/html' },
6026
- signal: controller.signal
6027
- },
6028
- { allowedHosts: ['www.sogni.ai'] }
6029
- );
6030
- if (!response.ok) {
6031
- const err = new Error(`Sogni model catalog returned HTTP ${response.status}.`);
6032
- err.code = 'MODEL_CATALOG_UNAVAILABLE';
6033
- throw err;
6034
- }
6035
- const contentLength = Number(response.headers.get('content-length'));
6036
- if (Number.isFinite(contentLength) && contentLength > SOGNI_MODEL_CATALOG_MAX_BYTES) {
6037
- const err = new Error('Sogni model catalog response is unexpectedly large.');
6038
- err.code = 'MODEL_CATALOG_INVALID';
6039
- throw err;
6040
- }
6041
- const html = await response.text();
6042
- if (Buffer.byteLength(html, 'utf8') > SOGNI_MODEL_CATALOG_MAX_BYTES) {
6043
- const err = new Error('Sogni model catalog response is unexpectedly large.');
6044
- err.code = 'MODEL_CATALOG_INVALID';
6045
- throw err;
6298
+ let catalog;
6299
+ if (fixtureJson) {
6300
+ const payload = JSON.parse(fixtureJson);
6301
+ const data = payload?.data || payload;
6302
+ catalog = {
6303
+ fetchedAt: Date.now(),
6304
+ network,
6305
+ media,
6306
+ etag: null,
6307
+ catalogVersion: data?.catalogVersion || null,
6308
+ models: data?.models
6309
+ };
6310
+ } else {
6311
+ const url = new URL(MODEL_CATALOG_URL);
6312
+ url.searchParams.set('network', network);
6313
+ if (media !== 'all') url.searchParams.set('mediaType', media);
6314
+ const headers = { accept: 'application/json' };
6315
+ if (cachedCatalog?.etag) headers['if-none-match'] = cachedCatalog.etag;
6316
+ const response = await fetch(url, {
6317
+ headers,
6318
+ signal: AbortSignal.timeout(SOGNI_MODEL_CATALOG_TIMEOUT_MS)
6319
+ });
6320
+ if (response.status === 304 && cachedCatalog) {
6321
+ catalog = { ...cachedCatalog, fetchedAt: Date.now() };
6322
+ } else {
6323
+ if (!response.ok) throw new Error(`${url} returned HTTP ${response.status}`);
6324
+ const contentLength = Number(response.headers.get('content-length'));
6325
+ if (Number.isFinite(contentLength) && contentLength > SOGNI_MODEL_CATALOG_MAX_BYTES) {
6326
+ const error = new Error('Sogni model catalog response is unexpectedly large.');
6327
+ error.code = 'MODEL_CATALOG_INVALID';
6328
+ throw error;
6329
+ }
6330
+ const text = await response.text();
6331
+ if (Buffer.byteLength(text, 'utf8') > SOGNI_MODEL_CATALOG_MAX_BYTES) {
6332
+ const error = new Error('Sogni model catalog response is unexpectedly large.');
6333
+ error.code = 'MODEL_CATALOG_INVALID';
6334
+ throw error;
6335
+ }
6336
+ const payload = JSON.parse(text);
6337
+ catalog = {
6338
+ fetchedAt: Date.now(),
6339
+ network,
6340
+ media,
6341
+ etag: response.headers.get('etag'),
6342
+ catalogVersion: payload?.data?.catalogVersion || null,
6343
+ models: payload?.data?.models
6344
+ };
6345
+ }
6046
6346
  }
6047
- const entries = modelCatalogEntriesFromHtml(html);
6048
- if (entries.length === 0) {
6049
- const err = new Error('Sogni model catalog contained no model cards.');
6050
- err.code = 'MODEL_CATALOG_INVALID';
6051
- throw err;
6347
+ if (!Array.isArray(catalog?.models)) {
6348
+ const error = new Error('Sogni model catalog response contained no model list.');
6349
+ error.code = 'MODEL_CATALOG_INVALID';
6350
+ throw error;
6052
6351
  }
6053
- return entries;
6054
- } finally {
6055
- clearTimeout(timeoutId);
6352
+ persistModelCatalogCache(catalog, MODEL_CATALOG_LIST_CACHE_PATH);
6353
+ return catalog;
6354
+ } catch (cause) {
6355
+ const error = new Error(`Could not load the live Sogni model catalog (${cause?.message || cause}).`);
6356
+ error.code = cause?.code || 'MODEL_CATALOG_UNAVAILABLE';
6357
+ error.hint = `Check Sogni platform status and retry. Catalog: ${MODEL_CATALOG_URL}`;
6358
+ throw error;
6056
6359
  }
6057
6360
  }
6058
6361
 
6059
- function enrichLiveModelsWithCatalogTags(models, catalogEntries) {
6060
- return models.map((model) => {
6061
- const modelId = String(model.id || '').toLocaleLowerCase();
6062
- const entry = catalogEntries.find((candidate) => candidate.modelIds.has(modelId));
6063
- return {
6064
- ...model,
6065
- tags: entry?.tags || []
6066
- };
6067
- });
6068
- }
6069
-
6070
6362
  async function runLiveModels() {
6071
- const creds = loadCredentials();
6072
- const apiKey = requireApiKeyCredentials(
6073
- creds,
6074
- options.liveModelAction === 'search' ? '--search-models' : '--list-models'
6075
- );
6076
6363
  const network = options.liveModelNetwork || openclawConfig?.defaultNetwork || 'fast';
6077
6364
  const media = options.liveModelMedia || 'all';
6078
6365
  const query = options.liveModelQuery?.trim() || null;
@@ -6083,95 +6370,77 @@ async function runLiveModels() {
6083
6370
  err.code = 'INVALID_ARGUMENT';
6084
6371
  throw err;
6085
6372
  }
6086
- const modelClient = new SogniClientWrapper({
6087
- appSource: SOGNI_APP_SOURCE,
6088
- network,
6089
- autoConnect: false,
6090
- apiKey,
6091
- authType: 'apiKey'
6092
- });
6093
-
6094
- try {
6095
- await connectSogniClient(modelClient);
6096
- let models = await modelClient.getAvailableModels({ sortByWorkers: true });
6097
- const queryAsTag = normalizeLiveModelTag(query);
6098
- const catalogRequired = tagFilters.length > 0 || KNOWN_MODEL_CATALOG_TAGS.has(queryAsTag);
6099
- let catalogTagsAvailable = false;
6100
- try {
6101
- const catalogEntries = await fetchModelCatalogEntries();
6102
- if (catalogRequired && catalogEntries.length === 0) {
6103
- const err = new Error('Sogni model catalog contained no model cards.');
6104
- err.code = 'MODEL_CATALOG_INVALID';
6105
- throw err;
6106
- }
6107
- models = enrichLiveModelsWithCatalogTags(models, catalogEntries);
6108
- catalogTagsAvailable = catalogEntries.length > 0;
6109
- } catch (error) {
6110
- if (catalogRequired) {
6111
- if (!error.code) error.code = 'MODEL_CATALOG_UNAVAILABLE';
6112
- error.hint = 'Tag filtering requires the live Sogni model catalog at https://www.sogni.ai/models.';
6113
- throw error;
6114
- }
6115
- models = enrichLiveModelsWithCatalogTags(models, []);
6116
- if (!options.quiet && !options.json && !JSON_ERROR_MODE) {
6117
- console.error(`Warning: model catalog tags unavailable: ${cliErrorMessage(error)}`);
6118
- }
6119
- }
6120
- if (media !== 'all') {
6121
- models = models.filter((model) => model.media === media);
6122
- }
6123
- if (tagFilters.length > 0) {
6124
- models = models.filter((model) =>
6125
- tagFilters.every((tag) => model.tags.includes(tag))
6126
- );
6127
- }
6128
- if (normalizedQuery) {
6129
- models = models.filter((model) =>
6130
- normalizeLiveModelSearch(`${model.id} ${model.name} ${model.tags.join(' ')}`).includes(normalizedQuery)
6131
- );
6132
- }
6373
+ const catalog = await fetchLiveModelCatalog(network, media);
6374
+ let models = catalog.models.map((model) => ({
6375
+ id: model.id,
6376
+ name: model.name || model.id,
6377
+ workerCount: Number(model.workerCounts?.[network] || 0),
6378
+ media: model.mediaType,
6379
+ networks: Array.isArray(model.availableNetworks) ? model.availableNetworks : [],
6380
+ workerCounts: model.workerCounts || {},
6381
+ tierId: model.tierId || null,
6382
+ tags: Array.isArray(model.tags)
6383
+ ? [...new Set(model.tags.map(normalizeLiveModelTag).filter(Boolean))].sort()
6384
+ : []
6385
+ })).filter(model =>
6386
+ ['image', 'video', 'audio'].includes(model.media) &&
6387
+ model.networks.includes(network) &&
6388
+ (media === 'all' || model.media === media)
6389
+ );
6390
+ const catalogTagsAvailable = catalog.models.every(model => Array.isArray(model.tags));
6391
+ const queryAsTag = normalizeLiveModelTag(query);
6392
+ if ((tagFilters.length > 0 || KNOWN_MODEL_CATALOG_TAGS.has(queryAsTag)) && !catalogTagsAvailable) {
6393
+ const error = new Error('Sogni model catalog response does not include catalog tags.');
6394
+ error.code = 'MODEL_CATALOG_INVALID';
6395
+ error.hint = `Tag filtering requires catalog tags from ${MODEL_CATALOG_URL}`;
6396
+ throw error;
6397
+ }
6398
+ models.sort((left, right) =>
6399
+ right.workerCount - left.workerCount ||
6400
+ left.name.localeCompare(right.name) ||
6401
+ left.id.localeCompare(right.id)
6402
+ );
6403
+ if (tagFilters.length > 0) {
6404
+ models = models.filter((model) => tagFilters.every((tag) => model.tags.includes(tag)));
6405
+ }
6406
+ if (normalizedQuery) {
6407
+ models = models.filter((model) =>
6408
+ normalizeLiveModelSearch(`${model.id} ${model.name} ${model.tags.join(' ')}`).includes(normalizedQuery)
6409
+ );
6410
+ }
6133
6411
 
6134
- const result = {
6135
- success: true,
6136
- type: 'live-models',
6137
- network,
6138
- media,
6139
- query,
6140
- tagFilters,
6141
- catalogTagsAvailable,
6142
- count: models.length,
6143
- models,
6144
- timestamp: new Date().toISOString()
6145
- };
6146
- if (options.json || JSON_ERROR_MODE) {
6147
- console.log(JSON.stringify(result));
6148
- return;
6149
- }
6412
+ const result = {
6413
+ success: true,
6414
+ type: 'live-models',
6415
+ network,
6416
+ media,
6417
+ query,
6418
+ tagFilters,
6419
+ catalogTagsAvailable,
6420
+ catalogVersion: catalog.catalogVersion,
6421
+ count: models.length,
6422
+ models,
6423
+ timestamp: new Date().toISOString()
6424
+ };
6425
+ if (options.json || JSON_ERROR_MODE) {
6426
+ console.log(JSON.stringify(result));
6427
+ return;
6428
+ }
6150
6429
 
6151
- const scope = [
6152
- media === 'all' ? 'all media' : media,
6153
- `network=${network}`,
6154
- query ? `query=${JSON.stringify(query)}` : null,
6155
- tagFilters.length ? `tags=${tagFilters.join('+')}` : null
6156
- ].filter(Boolean).join(', ');
6157
- console.log(`Live Sogni models (${models.length}; ${scope})`);
6158
- if (models.length === 0) {
6159
- console.log('No matching models found.');
6160
- return;
6161
- }
6162
- console.log('MEDIA\tWORKERS\tMODEL ID\tTAGS\tNAME');
6163
- for (const model of models) {
6164
- console.log(`${model.media}\t${model.workerCount}\t${model.id}\t${model.tags.join(',') || '-'}\t${model.name}`);
6165
- }
6166
- } finally {
6167
- try {
6168
- if (modelClient.isConnected()) {
6169
- await Promise.race([
6170
- modelClient.disconnect(),
6171
- new Promise(resolve => setTimeout(resolve, 1000))
6172
- ]);
6173
- }
6174
- } catch {}
6430
+ const scope = [
6431
+ media === 'all' ? 'all media' : media,
6432
+ `network=${network}`,
6433
+ query ? `query=${JSON.stringify(query)}` : null,
6434
+ tagFilters.length ? `tags=${tagFilters.join('+')}` : null
6435
+ ].filter(Boolean).join(', ');
6436
+ console.log(`Live Sogni models (${models.length}; ${scope})`);
6437
+ if (models.length === 0) {
6438
+ console.log('No matching models found.');
6439
+ return;
6440
+ }
6441
+ console.log('MEDIA\tWORKERS\tMODEL ID\tTAGS\tNAME');
6442
+ for (const model of models) {
6443
+ console.log(`${model.media}\t${model.workerCount}\t${model.id}\t${model.tags.join(',') || '-'}\t${model.name}`);
6175
6444
  }
6176
6445
  }
6177
6446
 
@@ -9670,6 +9939,7 @@ async function main() {
9670
9939
  return;
9671
9940
  }
9672
9941
 
9942
+ await loadLiveModelDefaults(options.model);
9673
9943
  await ensureSufficientVideoBalance(client, log);
9674
9944
 
9675
9945
  if (options.estimateVideoCost) {
@@ -10154,6 +10424,10 @@ async function main() {
10154
10424
  if (options.lastFrameStrength != null) {
10155
10425
  projectConfig.lastFrameStrength = options.lastFrameStrength;
10156
10426
  }
10427
+ if (options.loras.length > 0) {
10428
+ projectConfig.loras = options.loras;
10429
+ projectConfig.loraStrengths = options.loraStrengths;
10430
+ }
10157
10431
 
10158
10432
  const videoResult = await client.createVideoProject(withBillingMode(projectConfig));
10159
10433