@sogni-ai/sogni-creative-agent-skill 3.72.2 → 3.73.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
@@ -10,9 +10,8 @@
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';
14
13
  import { createRequire } from 'module';
15
- import { readFileSync, writeFileSync, existsSync, mkdirSync, mkdtempSync, statSync, readdirSync, realpathSync, lstatSync, unlinkSync, rmdirSync, rmSync, renameSync, openSync, writeSync, closeSync } from 'fs';
14
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, mkdtempSync, statSync, readdirSync, realpathSync, lstatSync, unlinkSync, rmdirSync, rmSync, renameSync, openSync, readSync, writeSync, closeSync } from 'fs';
16
15
  import { join, dirname, basename, extname, sep, resolve } from 'path';
17
16
  import { homedir, tmpdir } from 'os';
18
17
  import sharp from 'sharp';
@@ -28,7 +27,7 @@ import {
28
27
  resolveAgentAttribution,
29
28
  semanticWorkloadAttribution,
30
29
  } from './attribution.mjs';
31
- import { assertSafeUrl, fetchSafeUrl } from './ssrf-guard.mjs';
30
+ import { assertSafeUrl, fetchSafeUrl, readResponseBody } from './ssrf-guard.mjs';
32
31
  import {
33
32
  MESH_FLAGS, PIXAL3D_MODEL_ID, PIXAL3D_MULTIVIEW_MODEL_ID, PIXAL3D_VIEW_FLAGS, SPEECH_VALUE_FLAGS, MUSIC3_MODEL_ID, MUSIC3_DEFAULTS, SPEECH_REFERENCE_SECONDS,
34
33
  prepareMediaUtilityOptions, imageUtilityConfig, speechConfig, utilityResultMetadata, validateGlb
@@ -343,6 +342,145 @@ function sanitizePath(p, label) {
343
342
  return expandHomePath(p);
344
343
  }
345
344
 
345
+ // ---------------------------------------------------------------------------
346
+ // Local media tools (ffmpeg/ffprobe). Each one gets only the environment it
347
+ // needs, reads only local files and pipes, and reads only self-contained
348
+ // media: never a playlist or list that names other files or addresses.
349
+ // Defined here, above the top-level option checks that already probe media.
350
+ // ---------------------------------------------------------------------------
351
+
352
+ // Variables a media tool needs to start and to find its libraries and temp
353
+ // folder, plus LANG and LC_*. Nothing else in this process's environment,
354
+ // the Sogni API key included, reaches it.
355
+ const MEDIA_TOOL_ENV_NAMES = new Set([
356
+ 'PATH', 'HOME', 'TMPDIR', 'TMP', 'TEMP', 'LANG',
357
+ // Windows: process start, executable extension lookup, the user profile.
358
+ 'SYSTEMROOT', 'WINDIR', 'PATHEXT', 'USERPROFILE',
359
+ // An ffmpeg build installed outside the system library path loads its libraries through these.
360
+ 'LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'DYLD_FALLBACK_LIBRARY_PATH',
361
+ ]);
362
+
363
+ function mediaToolEnvironment() {
364
+ return Object.fromEntries(Object.entries(process.env).filter(([name, value]) => {
365
+ const upper = name.toUpperCase();
366
+ return value !== undefined && (MEDIA_TOOL_ENV_NAMES.has(upper) || upper.startsWith('LC_'));
367
+ }));
368
+ }
369
+
370
+ // Demuxers that read further files or network addresses named inside the
371
+ // input: playlists and manifests (hls, dash), edit lists (concat, which also
372
+ // reads ffconcat files, and imf), stream descriptions (sdp, rtp, rtsp, sap),
373
+ // filter graphs and scripts (lavfi, avisynth, vapoursynth). Given one disguised
374
+ // as media, ffmpeg converts what it names, such as another local file.
375
+ const INDIRECT_MEDIA_DEMUXERS = new Set([
376
+ 'applehttp', 'avisynth', 'concat', 'dash', 'hls', 'imf', 'lavfi',
377
+ 'rtp', 'rtsp', 'sap', 'sdp', 'vapoursynth', 'webm_dash_manifest',
378
+ ]);
379
+ // A frame-number pattern (%d, %03d) in a path the image2 demuxer opens makes it
380
+ // read a numbered sequence of other files.
381
+ const IMAGE_SEQUENCE_PATTERN = /%\d*d/;
382
+ // Input option for every ffmpeg and ffprobe input: local files and pipes only,
383
+ // so no input makes either tool fetch a URL around the SSRF guard.
384
+ const MEDIA_INPUT_PROTOCOL_ARGS = Object.freeze(['-protocol_whitelist', 'file,pipe']);
385
+
386
+ /** ffmpeg arguments that open `filePath` as an input under MEDIA_INPUT_PROTOCOL_ARGS. */
387
+ function mediaInputArgs(filePath) {
388
+ return [...MEDIA_INPUT_PROTOCOL_ARGS, '-i', filePath];
389
+ }
390
+
391
+ let execaPromise = null;
392
+ async function loadExeca() {
393
+ if (!execaPromise) {
394
+ execaPromise = import('execa');
395
+ }
396
+ return execaPromise;
397
+ }
398
+
399
+ /**
400
+ * Throws UNSAFE_MEDIA_INPUT when ffprobe's `formatName` for `filePath` (such as
401
+ * "mov,mp4,m4a,3gp,3g2,mj2") is a format that names other inputs. `label` is
402
+ * how the user knows the file.
403
+ */
404
+ function assertSelfContainedMediaFormat(formatName, filePath, label) {
405
+ const names = String(formatName || '').split(',').map((name) => name.trim()).filter(Boolean);
406
+ const indirect = names.find((name) => INDIRECT_MEDIA_DEMUXERS.has(name))
407
+ || (names.includes('image2') && IMAGE_SEQUENCE_PATTERN.test(filePath) ? 'image2 sequence' : null);
408
+ if (!indirect) return;
409
+ const err = new Error(
410
+ `${label} is not a self-contained media file: its format, ${indirect}, refers to other files or addresses. ` +
411
+ 'Use an image, audio, or video file.'
412
+ );
413
+ err.code = 'UNSAFE_MEDIA_INPUT';
414
+ err.details = { source: label, format: formatName };
415
+ throw err;
416
+ }
417
+
418
+ /**
419
+ * Run ffprobe on one file with JSON output: `args` before the entries, one
420
+ * -show_entries per `entries` item, plus format=format_name, which refuses the
421
+ * file (UNSAFE_MEDIA_INPUT) when it names other inputs. Resolves
422
+ * { ffprobePath, result, probe }: `probe` is the parsed JSON, or null when
423
+ * ffprobe failed or printed none; `result` is runCommand's.
424
+ */
425
+ async function probeMediaFile(filePath, { label = filePath, entries = [], args = [] } = {}) {
426
+ const ffprobePath = sanitizePath(getEnv('FFPROBE_PATH') || 'ffprobe', 'FFPROBE_PATH');
427
+ const result = await runCommand(ffprobePath, [
428
+ '-v', 'error',
429
+ ...args,
430
+ ...entries.flatMap((entry) => ['-show_entries', entry]),
431
+ '-show_entries', 'format=format_name',
432
+ '-of', 'json',
433
+ ...MEDIA_INPUT_PROTOCOL_ARGS,
434
+ filePath,
435
+ ], { captureOutput: true });
436
+ let probe = null;
437
+ try {
438
+ probe = JSON.parse(result.stdout || 'null');
439
+ } catch {
440
+ probe = null;
441
+ }
442
+ if (!probe || typeof probe !== 'object' || Array.isArray(probe)) probe = null;
443
+ assertSelfContainedMediaFormat(probe?.format?.format_name, filePath, label);
444
+ return { ffprobePath, result, probe };
445
+ }
446
+
447
+ // The format of an input that names other inputs, from the first bytes ffmpeg's
448
+ // own hls, concat, dash and imf probes look for, or null.
449
+ function sniffIndirectMediaFormat(filePath) {
450
+ let head;
451
+ try {
452
+ const fd = openSync(filePath, 'r');
453
+ try {
454
+ const bytes = Buffer.alloc(4096);
455
+ head = bytes.subarray(0, readSync(fd, bytes, 0, bytes.length, 0)).toString('latin1');
456
+ } finally {
457
+ closeSync(fd);
458
+ }
459
+ } catch {
460
+ // An unreadable file reaches ffmpeg, which reports it with the step's own error.
461
+ return null;
462
+ }
463
+ if (head.startsWith('#EXTM3U')) return 'hls';
464
+ if (head.startsWith('ffconcat version')) return 'concat';
465
+ if (/<MPD[\s>]/i.test(head)) return 'dash';
466
+ if (head.includes('<CompositionPlaylist')) return 'imf';
467
+ return null;
468
+ }
469
+
470
+ /**
471
+ * Check a file before ffmpeg reads it, refusing it (UNSAFE_MEDIA_INPUT) when
472
+ * ffprobe identifies a format that names other inputs. When ffprobe is missing
473
+ * or cannot identify the file, its first bytes decide: an HLS playlist, ffconcat
474
+ * list, DASH manifest or IMF composition is refused. Any other file goes to
475
+ * ffmpeg as before, and a corrupt one fails with the step's own error. `label`
476
+ * replaces `filePath` (often a temporary copy) in messages.
477
+ */
478
+ async function assertSelfContainedMediaInput(filePath, label = filePath) {
479
+ const { probe } = await probeMediaFile(filePath, { label });
480
+ if (probe?.format?.format_name) return;
481
+ assertSelfContainedMediaFormat(sniffIndirectMediaFormat(filePath), filePath, label);
482
+ }
483
+
346
484
  const DEFAULT_CREDENTIALS_PATH = join(homedir(), '.config', 'sogni', 'credentials');
347
485
  const DEFAULT_LAST_RENDER_PATH = join(homedir(), '.config', 'sogni', 'last-render.json');
348
486
  const DEFAULT_MODEL_CATALOG_CACHE_PATH = join(homedir(), '.config', 'sogni', 'model-catalog-cache.json');
@@ -363,6 +501,11 @@ const DEFAULT_PERSONAS_INDEX_PATH = join(homedir(), '.config', 'sogni', 'persona
363
501
  const DEFAULT_API_MEDIA_REFERENCE_MAX_BYTES = 100 * 1024 * 1024;
364
502
  // The API's ceiling on one uploaded reference (MAX_UPLOAD_SIZE_BYTES in sogni-api).
365
503
  const API_MEDIA_REFERENCE_UPLOAD_MAX_BYTES = 100 * 1024 * 1024;
504
+ // The most the CLI downloads from one user-supplied media URL. Uploads stop at the
505
+ // API's 100 MiB, but a source the CLI trims locally first (a Seedance
506
+ // video-to-video source with --video-start) may be longer. Override with
507
+ // SOGNI_MEDIA_DOWNLOAD_MAX_BYTES; local files have no limit.
508
+ const DEFAULT_MEDIA_DOWNLOAD_MAX_BYTES = 512 * 1024 * 1024;
366
509
  // Content types the API accepts per reference kind (ALLOWED_IMAGE_CONTENT_TYPES,
367
510
  // ALLOWED_AUDIO_CONTENT_TYPES and ALLOWED_VIDEO_CONTENT_TYPES in sogni-api).
368
511
  const VENDOR_REFERENCE_UPLOAD_CONTENT_TYPES = Object.freeze({
@@ -1780,15 +1923,11 @@ async function probeVideoUpscaleSource(buffer, sourceLabel) {
1780
1923
  let result;
1781
1924
  try {
1782
1925
  writeFileSync(inputPath, buffer);
1783
- result = await runCommand(ffprobePath, [
1784
- '-v', 'error',
1785
- '-select_streams', 'v:0',
1786
- '-count_frames',
1787
- '-show_entries',
1788
- 'stream=width,height,nb_read_frames,avg_frame_rate,r_frame_rate,sample_aspect_ratio,color_transfer:stream_side_data=rotation',
1789
- '-of', 'json',
1790
- inputPath,
1791
- ], { captureOutput: true });
1926
+ ({ result } = await probeMediaFile(inputPath, {
1927
+ label: sourceLabel,
1928
+ args: ['-select_streams', 'v:0', '-count_frames'],
1929
+ entries: ['stream=width,height,nb_read_frames,avg_frame_rate,r_frame_rate,sample_aspect_ratio,color_transfer:stream_side_data=rotation'],
1930
+ }));
1792
1931
  } finally {
1793
1932
  try { if (existsSync(inputPath)) unlinkSync(inputPath); } catch {}
1794
1933
  try { rmdirSync(tempDir); } catch {}
@@ -1865,16 +2004,11 @@ async function probeConformedVideoUpscaleSource(buffer, sourceLabel) {
1865
2004
  let result;
1866
2005
  try {
1867
2006
  writeFileSync(inputPath, buffer);
1868
- result = await runCommand(ffprobePath, [
1869
- '-v', 'error',
1870
- '-select_streams', 'v:0',
1871
- '-count_frames',
1872
- '-show_frames',
1873
- '-show_entries',
1874
- 'stream=width,height,nb_read_frames,avg_frame_rate,r_frame_rate,sample_aspect_ratio,color_transfer:stream_side_data=rotation:frame=best_effort_timestamp_time',
1875
- '-of', 'json',
1876
- inputPath,
1877
- ], { captureOutput: true });
2007
+ ({ result } = await probeMediaFile(inputPath, {
2008
+ label: sourceLabel,
2009
+ args: ['-select_streams', 'v:0', '-count_frames', '-show_frames'],
2010
+ entries: ['stream=width,height,nb_read_frames,avg_frame_rate,r_frame_rate,sample_aspect_ratio,color_transfer:stream_side_data=rotation:frame=best_effort_timestamp_time'],
2011
+ }));
1878
2012
  } finally {
1879
2013
  try { if (existsSync(inputPath)) unlinkSync(inputPath); } catch {}
1880
2014
  try { rmdirSync(tempDir); } catch {}
@@ -4100,6 +4234,7 @@ function runPromptGuideAction(argv) {
4100
4234
  // before any config, credential or network work.
4101
4235
  if (RAW_ARGS[0] === 'prompt-guide') {
4102
4236
  runPromptGuideAction(RAW_ARGS.slice(1));
4237
+ await flushStdout();
4103
4238
  process.exit(0);
4104
4239
  }
4105
4240
 
@@ -6172,6 +6307,7 @@ Examples:
6172
6307
  sogni-agent -Q pro "a beautiful mountain landscape at sunset"
6173
6308
  sogni-agent -n 3 "a {red|blue|green} sports car on a highway"
6174
6309
  `);
6310
+ await flushStdout();
6175
6311
  process.exit(0);
6176
6312
  } else if (arg === '--') {
6177
6313
  if (!options.prompt && args[i + 1] !== undefined) {
@@ -8133,7 +8269,12 @@ if (options.video) {
8133
8269
  const localVideoReferences = [options.refVideo, ...options.refVideos]
8134
8270
  .filter((reference) => reference && !isHttpUrl(reference) && existsSync(reference));
8135
8271
  for (const reference of localVideoReferences) {
8136
- const frameRate = probeLocalVideoFrameRate(reference);
8272
+ let frameRate;
8273
+ try {
8274
+ frameRate = await probeLocalVideoFrameRate(reference);
8275
+ } catch (error) {
8276
+ fatalCliError(error.message, { code: error.code, details: error.details });
8277
+ }
8137
8278
  if (!frameRate) {
8138
8279
  fatalCliError(
8139
8280
  `MiniMax H3 r2v could not verify the reference-video frame rate for "${reference}". ` +
@@ -9292,6 +9433,13 @@ const CHAT_HTTP_TIMEOUT_MS = (() => {
9292
9433
  // than the connect-phase default that suffices for GET/download/stream calls.
9293
9434
  const UPLOAD_HTTP_TIMEOUT_MS = Math.max(DEFAULT_HTTP_TIMEOUT_MS, 120000);
9294
9435
 
9436
+ function networkTimeoutError(timeoutMs) {
9437
+ const err = new Error(`Sogni network request timed out after ${Math.round(timeoutMs / 1000)}s.`);
9438
+ err.code = 'NETWORK_TIMEOUT';
9439
+ err.hint = 'Check your internet connection. If you are behind a corporate proxy/VPN or firewall, it may be blocking api.sogni.ai. You can raise the limit with SOGNI_HTTP_TIMEOUT_MS.';
9440
+ return err;
9441
+ }
9442
+
9295
9443
  // fetch() with an AbortController-based timeout that maps a timeout/abort into a
9296
9444
  // clean, coded error instead of a hang or an opaque "aborted" stack.
9297
9445
  async function fetchWithTimeout(resource, init = {}, timeoutMs = DEFAULT_HTTP_TIMEOUT_MS) {
@@ -9300,12 +9448,7 @@ async function fetchWithTimeout(resource, init = {}, timeoutMs = DEFAULT_HTTP_TI
9300
9448
  try {
9301
9449
  return await fetch(resource, { ...init, signal: controller.signal });
9302
9450
  } catch (error) {
9303
- if (error?.name === 'AbortError') {
9304
- const err = new Error(`Sogni network request timed out after ${Math.round(timeoutMs / 1000)}s.`);
9305
- err.code = 'NETWORK_TIMEOUT';
9306
- err.hint = 'Check your internet connection. If you are behind a corporate proxy/VPN or firewall, it may be blocking api.sogni.ai. You can raise the limit with SOGNI_HTTP_TIMEOUT_MS.';
9307
- throw err;
9308
- }
9451
+ if (error?.name === 'AbortError') throw networkTimeoutError(timeoutMs);
9309
9452
  throw error;
9310
9453
  } finally {
9311
9454
  clearTimeout(timer);
@@ -9405,6 +9548,13 @@ function formatApiMediaFlags(refs) {
9405
9548
  return [...new Set(refs.map(ref => ref.flag))].join(', ');
9406
9549
  }
9407
9550
 
9551
+ function mediaDownloadMaxBytes() {
9552
+ const configured = Number(getEnv('SOGNI_MEDIA_DOWNLOAD_MAX_BYTES') || '');
9553
+ return Number.isFinite(configured) && configured > 0
9554
+ ? configured
9555
+ : DEFAULT_MEDIA_DOWNLOAD_MAX_BYTES;
9556
+ }
9557
+
9408
9558
  function apiMediaReferenceMaxBytes() {
9409
9559
  const configured = Number(getEnv('SOGNI_API_MEDIA_REFERENCE_MAX_BYTES') || '');
9410
9560
  return Number.isFinite(configured) && configured > 0
@@ -11733,21 +11883,62 @@ function applyPersonaAndVoiceReferences() {
11733
11883
  }
11734
11884
  }
11735
11885
 
11886
+ // Download a user-supplied media URL. fetchSafeUrl connects only to addresses it
11887
+ // has checked, on every redirect hop, so neither a redirect nor a rebinding DNS
11888
+ // name can reach a private or metadata address; a hop Node's fetch() sends
11889
+ // through a proxy from the environment goes through that proxy. The server has
11890
+ // DEFAULT_HTTP_TIMEOUT_MS to answer; the body must then keep arriving (the
11891
+ // result-download stall limit) and stay within mediaDownloadMaxBytes().
11892
+ async function fetchRemoteMedia(url) {
11893
+ let host = 'the media server';
11894
+ try { host = new URL(url).host; } catch { /* keep the generic name */ }
11895
+ const controller = new AbortController();
11896
+ let timedOut = false;
11897
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, DEFAULT_HTTP_TIMEOUT_MS);
11898
+ let response;
11899
+ try {
11900
+ response = await fetchSafeUrl(url, { signal: controller.signal });
11901
+ } catch (error) {
11902
+ if (timedOut) throw networkTimeoutError(DEFAULT_HTTP_TIMEOUT_MS);
11903
+ throw error;
11904
+ } finally {
11905
+ clearTimeout(timer);
11906
+ }
11907
+ if (!response.ok) {
11908
+ await response.body?.cancel?.().catch(() => {});
11909
+ const err = new Error(`Failed to fetch media (${response.status} ${response.statusText})`);
11910
+ err.code = 'FETCH_FAILED';
11911
+ err.details = { url, status: response.status, statusText: response.statusText };
11912
+ throw err;
11913
+ }
11914
+ const maxBytes = mediaDownloadMaxBytes();
11915
+ const { stallMs } = mediaDownloadTiming();
11916
+ try {
11917
+ const buffer = await readResponseBody(response, { maxBytes, stallMs });
11918
+ return { buffer, contentType: response.headers.get('content-type') };
11919
+ } catch (error) {
11920
+ if (error?.code === 'BODY_TOO_LARGE') {
11921
+ const err = new Error(`The media at ${host} is larger than the ${maxBytes}-byte download limit.`);
11922
+ err.code = 'MEDIA_DOWNLOAD_TOO_LARGE';
11923
+ err.hint = 'Download the file and pass its local path, or raise the limit with SOGNI_MEDIA_DOWNLOAD_MAX_BYTES.';
11924
+ err.details = { url, maxBytes };
11925
+ throw err;
11926
+ }
11927
+ if (error?.code === 'BODY_STALLED') {
11928
+ const err = new Error(`The media download from ${host} stalled with no data for ${formatDownloadDuration(stallMs)}.`);
11929
+ err.code = 'NETWORK_TIMEOUT';
11930
+ err.hint = 'Check the URL and your connection, or download the file and pass its local path.';
11931
+ err.details = { url, stallMs };
11932
+ throw err;
11933
+ }
11934
+ throw error;
11935
+ }
11936
+ }
11937
+
11736
11938
  // Fetch image as buffer
11737
11939
  async function fetchMediaBuffer(pathOrUrl) {
11738
11940
  if (pathOrUrl.startsWith('http://') || pathOrUrl.startsWith('https://')) {
11739
- // fetchSafeUrl re-validates every redirect hop, so a vetted public URL
11740
- // cannot bounce the download to a private/metadata address.
11741
- const response = await fetchSafeUrl(pathOrUrl, {}, {
11742
- fetchImpl: (resource, init) => fetchWithTimeout(resource, init)
11743
- });
11744
- if (!response.ok) {
11745
- const err = new Error(`Failed to fetch media (${response.status} ${response.statusText})`);
11746
- err.code = 'FETCH_FAILED';
11747
- err.details = { url: pathOrUrl, status: response.status, statusText: response.statusText };
11748
- throw err;
11749
- }
11750
- return Buffer.from(await response.arrayBuffer());
11941
+ return (await fetchRemoteMedia(pathOrUrl)).buffer;
11751
11942
  }
11752
11943
  try {
11753
11944
  return readFileSync(pathOrUrl);
@@ -11762,20 +11953,9 @@ async function fetchMediaBuffer(pathOrUrl) {
11762
11953
 
11763
11954
  async function fetchMediaBlob(pathOrUrl, fallbackMimeType = 'application/octet-stream') {
11764
11955
  if (pathOrUrl.startsWith('http://') || pathOrUrl.startsWith('https://')) {
11765
- // fetchSafeUrl re-validates every redirect hop, so a vetted public URL
11766
- // cannot bounce the download to a private/metadata address.
11767
- const response = await fetchSafeUrl(pathOrUrl, {}, {
11768
- fetchImpl: (resource, init) => fetchWithTimeout(resource, init)
11769
- });
11770
- if (!response.ok) {
11771
- const err = new Error(`Failed to fetch media (${response.status} ${response.statusText})`);
11772
- err.code = 'FETCH_FAILED';
11773
- err.details = { url: pathOrUrl, status: response.status, statusText: response.statusText };
11774
- throw err;
11775
- }
11776
- const contentType = response.headers.get('content-type')?.split(';')[0]?.trim();
11777
- const mimeType = contentType || mimeTypeForPath(pathOrUrl, fallbackMimeType);
11778
- return new Blob([await response.arrayBuffer()], { type: mimeType });
11956
+ const { buffer, contentType } = await fetchRemoteMedia(pathOrUrl);
11957
+ const mimeType = contentType?.split(';')[0]?.trim() || mimeTypeForPath(pathOrUrl, fallbackMimeType);
11958
+ return new Blob([buffer], { type: mimeType });
11779
11959
  }
11780
11960
 
11781
11961
  const buffer = await fetchMediaBuffer(pathOrUrl);
@@ -11787,6 +11967,7 @@ async function prepareReferenceAudioIdentityMedia(pathOrUrl) {
11787
11967
  if (!pathOrUrl.startsWith('http://') && !pathOrUrl.startsWith('https://') && (cleanExt === '.wav' || cleanExt === '.wave')) {
11788
11968
  const sourcePath = sanitizePath(pathOrUrl, '--reference-audio-identity');
11789
11969
  const ffmpegPath = await ensureFfmpegAvailable();
11970
+ await assertSelfContainedMediaInput(sourcePath);
11790
11971
  const tempDir = createTrackedTempDir('sogni-audio-id-');
11791
11972
  const outputPath = join(tempDir, 'voice-identity.m4a');
11792
11973
  try {
@@ -11794,7 +11975,7 @@ async function prepareReferenceAudioIdentityMedia(pathOrUrl) {
11794
11975
  '-hide_banner',
11795
11976
  '-loglevel', 'error',
11796
11977
  '-y',
11797
- '-i', sourcePath,
11978
+ ...mediaInputArgs(sourcePath),
11798
11979
  '-vn',
11799
11980
  '-ac', '1',
11800
11981
  '-c:a', 'aac',
@@ -11834,11 +12015,12 @@ async function transcodeMp3ReferenceAudioBuffer(buffer, sourceLabel) {
11834
12015
  const outputPath = join(tempDir, 'reference-audio.m4a');
11835
12016
  try {
11836
12017
  writeFileSync(inputPath, buffer);
12018
+ await assertSelfContainedMediaInput(inputPath, sourceLabel);
11837
12019
  const result = await runCommand(ffmpegPath, [
11838
12020
  '-hide_banner',
11839
12021
  '-loglevel', 'error',
11840
12022
  '-y',
11841
- '-i', inputPath,
12023
+ ...mediaInputArgs(inputPath),
11842
12024
  '-vn',
11843
12025
  '-c:a', 'aac',
11844
12026
  '-b:a', '192k',
@@ -11889,11 +12071,12 @@ async function trimPreparedReferenceAudioWindowBuffer(buffer, {
11889
12071
  const outputPath = join(tempDir, 'reference-audio-window.m4a');
11890
12072
  try {
11891
12073
  writeFileSync(inputPath, buffer);
12074
+ await assertSelfContainedMediaInput(inputPath, 'The reference audio');
11892
12075
  const args = ['-hide_banner', '-loglevel', 'error', '-y'];
11893
12076
  if (Number.isFinite(startSeconds) && startSeconds > 0) {
11894
12077
  args.push('-ss', String(startSeconds));
11895
12078
  }
11896
- args.push('-i', inputPath);
12079
+ args.push(...mediaInputArgs(inputPath));
11897
12080
  if (Number.isFinite(durationSeconds) && durationSeconds > 0) {
11898
12081
  args.push('-t', String(durationSeconds));
11899
12082
  }
@@ -11938,35 +12121,26 @@ function withMediaExtension(filename, extension) {
11938
12121
  return `${base || 'reference'}${cleanExtension}`;
11939
12122
  }
11940
12123
 
11941
- async function probeLocalMediaDurationSeconds(pathOrUrl) {
11942
- if (isHttpUrl(pathOrUrl)) return undefined;
11943
- const ffprobePath = sanitizePath(getEnv('FFPROBE_PATH') || 'ffprobe', 'FFPROBE_PATH');
11944
- const result = await runCommand(ffprobePath, [
11945
- '-v', 'error',
11946
- '-show_entries', 'format=duration',
11947
- '-of', 'default=noprint_wrappers=1:nokey=1',
11948
- pathOrUrl,
11949
- ], { captureOutput: true });
12124
+ // The media duration ffprobe reports in seconds, or undefined when it reports none.
12125
+ async function probeMediaDurationSeconds(filePath, label) {
12126
+ const { result, probe } = await probeMediaFile(filePath, { label, entries: ['format=duration'] });
11950
12127
  if (result.error || result.status !== 0) return undefined;
11951
- const parsed = Number(String(result.stdout || '').trim());
12128
+ const raw = probe?.format?.duration;
12129
+ const parsed = raw === undefined || raw === null || raw === '' ? Number.NaN : Number(raw);
11952
12130
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
11953
12131
  }
11954
12132
 
12133
+ async function probeLocalMediaDurationSeconds(pathOrUrl) {
12134
+ if (isHttpUrl(pathOrUrl)) return undefined;
12135
+ return probeMediaDurationSeconds(pathOrUrl, pathOrUrl);
12136
+ }
12137
+
11955
12138
  async function probeMediaBufferDurationSeconds(buffer, filename) {
11956
- const ffprobePath = sanitizePath(getEnv('FFPROBE_PATH') || 'ffprobe', 'FFPROBE_PATH');
11957
12139
  const tempDir = createTrackedTempDir('sogni-wan3-probe-');
11958
12140
  const inputPath = mediaTempInputPath(tempDir, filename, '.media');
11959
12141
  try {
11960
12142
  writeFileSync(inputPath, Buffer.from(buffer));
11961
- const result = await runCommand(ffprobePath, [
11962
- '-v', 'error',
11963
- '-show_entries', 'format=duration',
11964
- '-of', 'default=noprint_wrappers=1:nokey=1',
11965
- inputPath,
11966
- ], { captureOutput: true });
11967
- if (result.error || result.status !== 0) return undefined;
11968
- const parsed = Number(String(result.stdout || '').trim());
11969
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
12143
+ return await probeMediaDurationSeconds(inputPath, filename);
11970
12144
  } finally {
11971
12145
  try { if (existsSync(inputPath)) unlinkSync(inputPath); } catch {}
11972
12146
  try { rmdirSync(tempDir); } catch {}
@@ -12067,11 +12241,12 @@ async function transcodeSeedanceReferenceAudioToMp3(request) {
12067
12241
  const outputPath = join(tempDir, 'reference-audio.mp3');
12068
12242
  try {
12069
12243
  writeFileSync(inputPath, Buffer.from(request.data));
12244
+ await assertSelfContainedMediaInput(inputPath, request.filename);
12070
12245
  const result = await runCommand(ffmpegPath, [
12071
12246
  '-hide_banner',
12072
12247
  '-loglevel', 'error',
12073
12248
  '-y',
12074
- '-i', inputPath,
12249
+ ...mediaInputArgs(inputPath),
12075
12250
  '-vn',
12076
12251
  '-ac', '2',
12077
12252
  '-ar', '44100',
@@ -12108,12 +12283,13 @@ async function trimSeedanceReferenceAudioToMp3(request) {
12108
12283
  );
12109
12284
  try {
12110
12285
  writeFileSync(inputPath, Buffer.from(request.data));
12286
+ await assertSelfContainedMediaInput(inputPath, request.filename);
12111
12287
  const result = await runCommand(ffmpegPath, [
12112
12288
  '-hide_banner',
12113
12289
  '-loglevel', 'error',
12114
12290
  '-y',
12115
12291
  '-ss', String(start),
12116
- '-i', inputPath,
12292
+ ...mediaInputArgs(inputPath),
12117
12293
  '-t', String(duration),
12118
12294
  '-vn',
12119
12295
  '-ac', '2',
@@ -12411,12 +12587,13 @@ async function trimSeedanceV2VSourceVideoBuffer(buffer, sourceLabel, startOffset
12411
12587
  );
12412
12588
  try {
12413
12589
  writeFileSync(inputPath, buffer);
12590
+ await assertSelfContainedMediaInput(inputPath, sourceLabel);
12414
12591
  const result = await runCommand(ffmpegPath, [
12415
12592
  '-hide_banner',
12416
12593
  '-loglevel', 'error',
12417
12594
  '-y',
12418
12595
  '-ss', String(start),
12419
- '-i', inputPath,
12596
+ ...mediaInputArgs(inputPath),
12420
12597
  '-t', String(duration),
12421
12598
  '-map', '0:v:0',
12422
12599
  '-an',
@@ -12853,14 +13030,6 @@ function removeClientListener(client, event, handler) {
12853
13030
  }
12854
13031
  }
12855
13032
 
12856
- let execaPromise = null;
12857
- async function loadExeca() {
12858
- if (!execaPromise) {
12859
- execaPromise = import('execa');
12860
- }
12861
- return execaPromise;
12862
- }
12863
-
12864
13033
  async function ensureFfmpegAvailable(operation = 'this audio/video operation') {
12865
13034
  const ffmpegPath = sanitizePath(getEnv('FFMPEG_PATH') || 'ffmpeg', 'FFMPEG_PATH');
12866
13035
  const result = await runCommand(ffmpegPath, ['-version'], { captureOutput: true });
@@ -12913,10 +13082,14 @@ function isNonEmptyFile(filePath) {
12913
13082
  }
12914
13083
  }
12915
13084
 
12916
- async function runCommand(command, args, { captureOutput = false, env = undefined } = {}) {
13085
+ // A child gets mediaToolEnvironment() plus `env`. Only `inheritEnv: true`, for
13086
+ // a child that is this CLI itself and needs its credentials, passes the whole
13087
+ // environment, with `env` on top.
13088
+ async function runCommand(command, args, { captureOutput = false, env = undefined, inheritEnv = false } = {}) {
12917
13089
  const options = {
12918
13090
  reject: false,
12919
- ...(env ? { env: { ...process.env, ...env } } : {}),
13091
+ extendEnv: inheritEnv,
13092
+ env: inheritEnv ? { ...env } : { ...mediaToolEnvironment(), ...env },
12920
13093
  };
12921
13094
  if (captureOutput) {
12922
13095
  options.stdout = 'pipe';
@@ -12953,6 +13126,8 @@ async function buildAngles360Video(outputPath, frames, fps) {
12953
13126
  sanitizePath(outputPath, '--angles-360-video output path');
12954
13127
  frames.forEach((f, i) => sanitizePath(f, `frame[${i}]`));
12955
13128
  const ffmpegPath = await ensureFfmpegAvailable();
13129
+ // The list is the CLI's own concat input; each frame it names is checked like any other input.
13130
+ for (const frame of frames) await assertSelfContainedMediaInput(frame);
12956
13131
  const tempListPath = outputPath.replace(/\.mp4$/i, '') + '.concat.txt';
12957
13132
  const frameDuration = 1 / fps;
12958
13133
  writeConcatList(tempListPath, frames, frameDuration);
@@ -12961,7 +13136,7 @@ async function buildAngles360Video(outputPath, frames, fps) {
12961
13136
  '-y',
12962
13137
  '-f', 'concat',
12963
13138
  '-safe', '0',
12964
- '-i', tempListPath,
13139
+ ...mediaInputArgs(tempListPath),
12965
13140
  '-r', String(fps),
12966
13141
  '-pix_fmt', 'yuv420p',
12967
13142
  outputPath
@@ -12983,6 +13158,7 @@ async function buildAngles360Video(outputPath, frames, fps) {
12983
13158
 
12984
13159
  async function runFrameExtraction(args, { videoPath, outputImagePath, which }) {
12985
13160
  const ffmpegPath = await ensureFfmpegAvailable();
13161
+ await assertSelfContainedMediaInput(videoPath);
12986
13162
  const result = await runCommand(ffmpegPath, args, { captureOutput: true });
12987
13163
 
12988
13164
  if (result.error || result.status !== 0 || !isNonEmptyFile(outputImagePath)) {
@@ -13016,7 +13192,7 @@ async function extractLastFrameFromVideo(videoPath, outputImagePath) {
13016
13192
  // output so the final write is the genuine last frame.
13017
13193
  const args = [
13018
13194
  '-sseof', '-1',
13019
- '-i', videoPath,
13195
+ ...mediaInputArgs(videoPath),
13020
13196
  '-update', '1', // Keep overwriting -> output is the last decoded frame
13021
13197
  '-q:v', '1', // Best quality
13022
13198
  '-y',
@@ -13032,7 +13208,7 @@ async function extractFirstFrameFromVideo(videoPath, outputImagePath) {
13032
13208
 
13033
13209
  // First decoded frame only.
13034
13210
  const args = [
13035
- '-i', videoPath,
13211
+ ...mediaInputArgs(videoPath),
13036
13212
  '-frames:v', '1',
13037
13213
  '-q:v', '1', // Best quality
13038
13214
  '-y',
@@ -13055,7 +13231,7 @@ async function extractFrameAtTimeFromVideo(videoPath, seconds, outputImagePath)
13055
13231
  // Seek after opening the input for frame-accurate visual QA. Loop Maker
13056
13232
  // clips are short, so accuracy is more useful here than keyframe-only speed.
13057
13233
  const args = [
13058
- '-i', videoPath,
13234
+ ...mediaInputArgs(videoPath),
13059
13235
  '-ss', String(timestamp),
13060
13236
  '-frames:v', '1',
13061
13237
  '-q:v', '1',
@@ -13083,31 +13259,20 @@ function parseFrameRate(raw) {
13083
13259
  return Number.isFinite(v) && v > 0 ? v : null;
13084
13260
  }
13085
13261
 
13086
- function probeLocalVideoFrameRate(filePath) {
13087
- const ffprobePath = sanitizePath(getEnv('FFPROBE_PATH') || 'ffprobe', 'FFPROBE_PATH');
13088
- try {
13089
- const stdout = execFileSync(
13090
- ffprobePath,
13091
- [
13092
- '-v', 'error',
13093
- '-select_streams', 'v:0',
13094
- '-show_entries', 'stream=avg_frame_rate,r_frame_rate',
13095
- '-of', 'default=noprint_wrappers=1:nokey=1',
13096
- filePath,
13097
- ],
13098
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
13099
- );
13100
- for (const candidate of String(stdout || '').trim().split(/\s+/)) {
13101
- const frameRate = parseFrameRate(candidate);
13102
- if (frameRate) return frameRate;
13103
- }
13104
- } catch {}
13105
- return null;
13262
+ async function probeLocalVideoFrameRate(filePath) {
13263
+ const { result, probe } = await probeMediaFile(filePath, {
13264
+ args: ['-select_streams', 'v:0'],
13265
+ entries: ['stream=avg_frame_rate,r_frame_rate'],
13266
+ });
13267
+ if (result.error || result.status !== 0) return null;
13268
+ const stream = Array.isArray(probe?.streams) ? probe.streams[0] : null;
13269
+ return parseFrameRate(stream?.avg_frame_rate) || parseFrameRate(stream?.r_frame_rate) || null;
13106
13270
  }
13107
13271
 
13108
13272
  // Probe a media file's primary video stream + whether it has any audio.
13109
13273
  // Fields are null when the probe fails (e.g. ffprobe missing); callers fall
13110
- // back to safe defaults unless they explicitly require verification.
13274
+ // back to safe defaults unless they explicitly require verification. A file
13275
+ // that names other inputs throws UNSAFE_MEDIA_INPUT.
13111
13276
  async function probeVideoStreamInfo(filePath) {
13112
13277
  const info = {
13113
13278
  width: null,
@@ -13118,17 +13283,10 @@ async function probeVideoStreamInfo(filePath) {
13118
13283
  videoCodec: null,
13119
13284
  audioCodec: null
13120
13285
  };
13121
- const ffprobePath = sanitizePath(getEnv('FFPROBE_PATH') || 'ffprobe', 'FFPROBE_PATH');
13122
- const result = await runCommand(ffprobePath, [
13123
- '-v', 'error',
13124
- '-show_entries', 'stream=codec_type,codec_name,width,height,avg_frame_rate,r_frame_rate',
13125
- '-show_entries', 'format=duration',
13126
- '-of', 'json',
13127
- filePath,
13128
- ], { captureOutput: true });
13129
- if (result.error || result.status !== 0) return info;
13130
- let parsed;
13131
- try { parsed = JSON.parse(result.stdout || '{}'); } catch { return info; }
13286
+ const { result, probe: parsed } = await probeMediaFile(filePath, {
13287
+ entries: ['stream=codec_type,codec_name,width,height,avg_frame_rate,r_frame_rate', 'format=duration'],
13288
+ });
13289
+ if (result.error || result.status !== 0 || !parsed) return info;
13132
13290
  const streams = Array.isArray(parsed.streams) ? parsed.streams : [];
13133
13291
  const video = streams.find((s) => s.codec_type === 'video');
13134
13292
  const audio = streams.find((s) => s.codec_type === 'audio');
@@ -13160,7 +13318,7 @@ async function verifyVideoFile(videoPath) {
13160
13318
  const result = await runCommand(ffmpegPath, [
13161
13319
  '-hide_banner',
13162
13320
  '-loglevel', 'error',
13163
- '-i', videoPath,
13321
+ ...mediaInputArgs(videoPath),
13164
13322
  '-map', '0:v:0',
13165
13323
  '-map', '0:a?',
13166
13324
  '-f', 'null',
@@ -13186,11 +13344,12 @@ async function trimVideoClip(inputPath, startSeconds, durationSeconds, outputPat
13186
13344
  sanitizePath(inputPath, 'trim input video');
13187
13345
  sanitizePath(outputPath, 'trim output video');
13188
13346
  const ffmpegPath = await ensureFfmpegAvailable();
13347
+ await assertSelfContainedMediaInput(inputPath);
13189
13348
  const result = await runCommand(ffmpegPath, [
13190
13349
  '-hide_banner',
13191
13350
  '-loglevel', 'error',
13192
13351
  '-y',
13193
- '-i', inputPath,
13352
+ ...mediaInputArgs(inputPath),
13194
13353
  '-ss', String(startSeconds),
13195
13354
  '-t', String(durationSeconds),
13196
13355
  '-map', '0:v:0',
@@ -13232,6 +13391,9 @@ async function buildConcatVideoFromClips(outputPath, clips, { audioPath = null,
13232
13391
  if (audioPath) sanitizePath(audioPath, '--concat-audio');
13233
13392
  const ffmpegPath = await ensureFfmpegAvailable();
13234
13393
 
13394
+ for (const input of audioPath ? [...clips, audioPath] : clips) {
13395
+ await assertSelfContainedMediaInput(input);
13396
+ }
13235
13397
  const infos = [];
13236
13398
  for (const clip of clips) {
13237
13399
  infos.push(await probeVideoStreamInfo(clip));
@@ -13278,7 +13440,7 @@ async function buildConcatVideoFromClips(outputPath, clips, { audioPath = null,
13278
13440
  );
13279
13441
 
13280
13442
  const args = ['-y'];
13281
- clips.forEach((clip) => { args.push('-i', clip); });
13443
+ clips.forEach((clip) => { args.push(...mediaInputArgs(clip)); });
13282
13444
 
13283
13445
  let mapAudio = '[ca]';
13284
13446
  if (audioPath) {
@@ -13287,7 +13449,7 @@ async function buildConcatVideoFromClips(outputPath, clips, { audioPath = null,
13287
13449
  if (Number.isFinite(audioStart) && audioStart > 0) {
13288
13450
  args.push('-ss', String(audioStart));
13289
13451
  }
13290
- args.push('-i', audioPath);
13452
+ args.push(...mediaInputArgs(audioPath));
13291
13453
  const extIdx = clips.length;
13292
13454
  let extChain = `[${extIdx}:a]aformat=sample_rates=44100:channel_layouts=stereo,apad`;
13293
13455
  if (totalDuration > 0) {
@@ -13338,11 +13500,14 @@ async function remixVideoAudio(inputVideo, outputVideo, opts = {}) {
13338
13500
  if (bedAudio) sanitizePath(bedAudio, '--bed-audio');
13339
13501
  if (mixAudio) sanitizePath(mixAudio, '--mix-audio');
13340
13502
  const ffmpegPath = await ensureFfmpegAvailable();
13503
+ for (const input of [inputVideo, bedAudio, mixAudio].filter(Boolean)) {
13504
+ await assertSelfContainedMediaInput(input);
13505
+ }
13341
13506
 
13342
13507
  const info = await probeVideoStreamInfo(inputVideo);
13343
13508
  const totalDuration = info.duration && info.duration > 0 ? info.duration : null;
13344
13509
 
13345
- const args = ['-y', '-i', inputVideo];
13510
+ const args = ['-y', ...mediaInputArgs(inputVideo)];
13346
13511
 
13347
13512
  // Resolve the bed source. With --audio-loop we re-open the source as a
13348
13513
  // -stream_loop input (the only robust, duration-based loop in ffmpeg).
@@ -13350,11 +13515,11 @@ async function remixVideoAudio(inputVideo, outputVideo, opts = {}) {
13350
13515
  let nextIndex = 1;
13351
13516
  const bedSourceFile = bedAudio || inputVideo;
13352
13517
  if (loop) {
13353
- args.push('-stream_loop', '-1', '-i', bedSourceFile);
13518
+ args.push('-stream_loop', '-1', ...mediaInputArgs(bedSourceFile));
13354
13519
  bedRef = `[${nextIndex}:a]`;
13355
13520
  nextIndex += 1;
13356
13521
  } else if (bedAudio) {
13357
- args.push('-i', bedAudio);
13522
+ args.push(...mediaInputArgs(bedAudio));
13358
13523
  bedRef = `[${nextIndex}:a]`;
13359
13524
  nextIndex += 1;
13360
13525
  } else {
@@ -13364,7 +13529,7 @@ async function remixVideoAudio(inputVideo, outputVideo, opts = {}) {
13364
13529
  let mixIndex = null;
13365
13530
  if (mixAudio) {
13366
13531
  mixIndex = nextIndex;
13367
- args.push('-i', mixAudio);
13532
+ args.push(...mediaInputArgs(mixAudio));
13368
13533
  nextIndex += 1;
13369
13534
  }
13370
13535
 
@@ -13800,6 +13965,7 @@ function sourceReelLineageEnvironment(workloadAttribution) {
13800
13965
  async function runSourceReelChild(label, args, logPath, outputPath, workloadAttribution) {
13801
13966
  const result = await runCommand(process.execPath, args, {
13802
13967
  captureOutput: true,
13968
+ inheritEnv: true,
13803
13969
  env: sourceReelLineageEnvironment(workloadAttribution),
13804
13970
  });
13805
13971
  const parsed = parseSourceReelChildJson(result.stdout);