@sogni-ai/sogni-creative-agent-skill 3.73.0 → 3.73.2

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({
@@ -710,12 +853,15 @@ function resolveConfiguredPath(rawPath, fallbackPath, label) {
710
853
  async function disableLiveModelAvailabilityEvents(wrapper) {
711
854
  const sdkClient = wrapper?.client;
712
855
 
856
+ const stopWatching = watchForConnectionTakeover(wrapper);
713
857
  try {
714
858
  if (typeof sdkClient?.setSocketEventSubscriptions === 'function') {
715
859
  await sdkClient.setSocketEventSubscriptions(SOCKET_EVENT_SUBSCRIPTIONS);
716
860
  }
717
861
  } catch (err) {
718
862
  // Subscription optimization is best-effort and must not block generation.
863
+ } finally {
864
+ stopWatching();
719
865
  }
720
866
  }
721
867
 
@@ -837,6 +983,10 @@ function classifyCliError(error, context = {}) {
837
983
  error = unwrapGenericProjectError(error);
838
984
  const rawMessage = cliErrorMessage(error);
839
985
 
986
+ if (error?.code === '4015') {
987
+ return { error_type: 'SWITCH_CONNECTION', category: 'connection_error', message: rawMessage, retryable: false };
988
+ }
989
+
840
990
  if (RELAXED_UNAVAILABLE_MESSAGE.test(rawMessage)) {
841
991
  return {
842
992
  error_type: 'MODEL_UNAVAILABLE',
@@ -1146,23 +1296,55 @@ function reportFatalError(error) {
1146
1296
  process.on('uncaughtException', reportFatalError);
1147
1297
  process.on('unhandledRejection', reportFatalError);
1148
1298
 
1149
- // Connect to Sogni, mapping a rejected connection into a clean auth error
1150
- // where we can. (Detached SDK failures that never reach this await are caught
1151
- // by the global handlers above.)
1299
+ const connectionTakeovers = new WeakMap();
1300
+
1152
1301
  /** The CLI's SDK client, signed in with the API key under one app ID. */
1153
1302
  function createSkillSogniClient(creds, appId) {
1154
- return new SogniClientWrapper({
1303
+ const takeover = new AbortController();
1304
+ const client = new SogniClientWrapper({
1155
1305
  appSource: SOGNI_APP_SOURCE,
1156
1306
  appId,
1157
1307
  attribution: clientAttribution(AGENT_ATTRIBUTION),
1158
1308
  network: renderNetwork,
1159
1309
  autoConnect: false,
1310
+ onConnectionTakeover: () => takeover.abort(),
1160
1311
  apiKey: creds.SOGNI_API_KEY,
1161
1312
  authType: 'apiKey'
1162
1313
  });
1314
+ connectionTakeovers.set(client, takeover.signal);
1315
+ client.on(ClientEvent.PROJECT_CREATED, project => runProjectIds.add(project.id));
1316
+ return client;
1317
+ }
1318
+
1319
+ // A 4015 ends this socket's event stream. Keep completed downloads and other
1320
+ // REST-only work independent of it, and stop only commands relying on the socket.
1321
+ function watchForConnectionTakeover(client, projectId = options.projectLookup?.projectId) {
1322
+ const signal = connectionTakeovers.get(client);
1323
+ const report = () => {
1324
+ const projects = sdkClientOf(client)?.projects?.trackedProjects || [];
1325
+ const ids = new Set(projectId ? [projectId] : []);
1326
+ for (const project of projects) {
1327
+ if (!project.finished && runProjectIds.has(project.id)) ids.add(project.id);
1328
+ }
1329
+ const projectIds = [...ids];
1330
+ const waitCommands = projectIds.map(waitCommandFor);
1331
+ const usesFixedId = getEnv('SOGNI_APP_ID') || getEnv('SOGNI_APP_ID_PATH');
1332
+ const appIdHint = 'For parallel runs, let the CLI allocate its app IDs or give each process its own SOGNI_APP_ID.';
1333
+ fatalCliError('Another connection took over this Sogni app ID (4015).', {
1334
+ code: '4015',
1335
+ details: { projectIds, waitCommands },
1336
+ hint: waitCommands.length
1337
+ ? `${usesFixedId ? 'Clear the shared SOGNI_APP_ID or SOGNI_APP_ID_PATH before recovery. ' : ''}Recover the existing render with: ${waitCommands.join('; ')}`
1338
+ : appIdHint
1339
+ });
1340
+ };
1341
+ if (signal.aborted) report();
1342
+ signal.addEventListener('abort', report, { once: true });
1343
+ return () => signal.removeEventListener('abort', report);
1163
1344
  }
1164
1345
 
1165
1346
  async function connectSogniClient(client) {
1347
+ const stopWatching = watchForConnectionTakeover(client);
1166
1348
  try {
1167
1349
  await client.connect();
1168
1350
  } catch (error) {
@@ -1172,6 +1354,8 @@ async function connectSogniClient(client) {
1172
1354
  if (!error.code) error.code = 'INVALID_API_KEY';
1173
1355
  }
1174
1356
  throw error;
1357
+ } finally {
1358
+ stopWatching();
1175
1359
  }
1176
1360
  }
1177
1361
 
@@ -1780,15 +1964,11 @@ async function probeVideoUpscaleSource(buffer, sourceLabel) {
1780
1964
  let result;
1781
1965
  try {
1782
1966
  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 });
1967
+ ({ result } = await probeMediaFile(inputPath, {
1968
+ label: sourceLabel,
1969
+ args: ['-select_streams', 'v:0', '-count_frames'],
1970
+ entries: ['stream=width,height,nb_read_frames,avg_frame_rate,r_frame_rate,sample_aspect_ratio,color_transfer:stream_side_data=rotation'],
1971
+ }));
1792
1972
  } finally {
1793
1973
  try { if (existsSync(inputPath)) unlinkSync(inputPath); } catch {}
1794
1974
  try { rmdirSync(tempDir); } catch {}
@@ -1865,16 +2045,11 @@ async function probeConformedVideoUpscaleSource(buffer, sourceLabel) {
1865
2045
  let result;
1866
2046
  try {
1867
2047
  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 });
2048
+ ({ result } = await probeMediaFile(inputPath, {
2049
+ label: sourceLabel,
2050
+ args: ['-select_streams', 'v:0', '-count_frames', '-show_frames'],
2051
+ 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'],
2052
+ }));
1878
2053
  } finally {
1879
2054
  try { if (existsSync(inputPath)) unlinkSync(inputPath); } catch {}
1880
2055
  try { rmdirSync(tempDir); } catch {}
@@ -4100,6 +4275,7 @@ function runPromptGuideAction(argv) {
4100
4275
  // before any config, credential or network work.
4101
4276
  if (RAW_ARGS[0] === 'prompt-guide') {
4102
4277
  runPromptGuideAction(RAW_ARGS.slice(1));
4278
+ await flushStdout();
4103
4279
  process.exit(0);
4104
4280
  }
4105
4281
 
@@ -6172,6 +6348,7 @@ Examples:
6172
6348
  sogni-agent -Q pro "a beautiful mountain landscape at sunset"
6173
6349
  sogni-agent -n 3 "a {red|blue|green} sports car on a highway"
6174
6350
  `);
6351
+ await flushStdout();
6175
6352
  process.exit(0);
6176
6353
  } else if (arg === '--') {
6177
6354
  if (!options.prompt && args[i + 1] !== undefined) {
@@ -8133,7 +8310,12 @@ if (options.video) {
8133
8310
  const localVideoReferences = [options.refVideo, ...options.refVideos]
8134
8311
  .filter((reference) => reference && !isHttpUrl(reference) && existsSync(reference));
8135
8312
  for (const reference of localVideoReferences) {
8136
- const frameRate = probeLocalVideoFrameRate(reference);
8313
+ let frameRate;
8314
+ try {
8315
+ frameRate = await probeLocalVideoFrameRate(reference);
8316
+ } catch (error) {
8317
+ fatalCliError(error.message, { code: error.code, details: error.details });
8318
+ }
8137
8319
  if (!frameRate) {
8138
8320
  fatalCliError(
8139
8321
  `MiniMax H3 r2v could not verify the reference-video frame rate for "${reference}". ` +
@@ -9292,6 +9474,13 @@ const CHAT_HTTP_TIMEOUT_MS = (() => {
9292
9474
  // than the connect-phase default that suffices for GET/download/stream calls.
9293
9475
  const UPLOAD_HTTP_TIMEOUT_MS = Math.max(DEFAULT_HTTP_TIMEOUT_MS, 120000);
9294
9476
 
9477
+ function networkTimeoutError(timeoutMs) {
9478
+ const err = new Error(`Sogni network request timed out after ${Math.round(timeoutMs / 1000)}s.`);
9479
+ err.code = 'NETWORK_TIMEOUT';
9480
+ 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.';
9481
+ return err;
9482
+ }
9483
+
9295
9484
  // fetch() with an AbortController-based timeout that maps a timeout/abort into a
9296
9485
  // clean, coded error instead of a hang or an opaque "aborted" stack.
9297
9486
  async function fetchWithTimeout(resource, init = {}, timeoutMs = DEFAULT_HTTP_TIMEOUT_MS) {
@@ -9300,12 +9489,7 @@ async function fetchWithTimeout(resource, init = {}, timeoutMs = DEFAULT_HTTP_TI
9300
9489
  try {
9301
9490
  return await fetch(resource, { ...init, signal: controller.signal });
9302
9491
  } 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
- }
9492
+ if (error?.name === 'AbortError') throw networkTimeoutError(timeoutMs);
9309
9493
  throw error;
9310
9494
  } finally {
9311
9495
  clearTimeout(timer);
@@ -9405,6 +9589,13 @@ function formatApiMediaFlags(refs) {
9405
9589
  return [...new Set(refs.map(ref => ref.flag))].join(', ');
9406
9590
  }
9407
9591
 
9592
+ function mediaDownloadMaxBytes() {
9593
+ const configured = Number(getEnv('SOGNI_MEDIA_DOWNLOAD_MAX_BYTES') || '');
9594
+ return Number.isFinite(configured) && configured > 0
9595
+ ? configured
9596
+ : DEFAULT_MEDIA_DOWNLOAD_MAX_BYTES;
9597
+ }
9598
+
9408
9599
  function apiMediaReferenceMaxBytes() {
9409
9600
  const configured = Number(getEnv('SOGNI_API_MEDIA_REFERENCE_MAX_BYTES') || '');
9410
9601
  return Number.isFinite(configured) && configured > 0
@@ -11733,21 +11924,62 @@ function applyPersonaAndVoiceReferences() {
11733
11924
  }
11734
11925
  }
11735
11926
 
11927
+ // Download a user-supplied media URL. fetchSafeUrl connects only to addresses it
11928
+ // has checked, on every redirect hop, so neither a redirect nor a rebinding DNS
11929
+ // name can reach a private or metadata address; a hop Node's fetch() sends
11930
+ // through a proxy from the environment goes through that proxy. The server has
11931
+ // DEFAULT_HTTP_TIMEOUT_MS to answer; the body must then keep arriving (the
11932
+ // result-download stall limit) and stay within mediaDownloadMaxBytes().
11933
+ async function fetchRemoteMedia(url) {
11934
+ let host = 'the media server';
11935
+ try { host = new URL(url).host; } catch { /* keep the generic name */ }
11936
+ const controller = new AbortController();
11937
+ let timedOut = false;
11938
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, DEFAULT_HTTP_TIMEOUT_MS);
11939
+ let response;
11940
+ try {
11941
+ response = await fetchSafeUrl(url, { signal: controller.signal });
11942
+ } catch (error) {
11943
+ if (timedOut) throw networkTimeoutError(DEFAULT_HTTP_TIMEOUT_MS);
11944
+ throw error;
11945
+ } finally {
11946
+ clearTimeout(timer);
11947
+ }
11948
+ if (!response.ok) {
11949
+ await response.body?.cancel?.().catch(() => {});
11950
+ const err = new Error(`Failed to fetch media (${response.status} ${response.statusText})`);
11951
+ err.code = 'FETCH_FAILED';
11952
+ err.details = { url, status: response.status, statusText: response.statusText };
11953
+ throw err;
11954
+ }
11955
+ const maxBytes = mediaDownloadMaxBytes();
11956
+ const { stallMs } = mediaDownloadTiming();
11957
+ try {
11958
+ const buffer = await readResponseBody(response, { maxBytes, stallMs });
11959
+ return { buffer, contentType: response.headers.get('content-type') };
11960
+ } catch (error) {
11961
+ if (error?.code === 'BODY_TOO_LARGE') {
11962
+ const err = new Error(`The media at ${host} is larger than the ${maxBytes}-byte download limit.`);
11963
+ err.code = 'MEDIA_DOWNLOAD_TOO_LARGE';
11964
+ err.hint = 'Download the file and pass its local path, or raise the limit with SOGNI_MEDIA_DOWNLOAD_MAX_BYTES.';
11965
+ err.details = { url, maxBytes };
11966
+ throw err;
11967
+ }
11968
+ if (error?.code === 'BODY_STALLED') {
11969
+ const err = new Error(`The media download from ${host} stalled with no data for ${formatDownloadDuration(stallMs)}.`);
11970
+ err.code = 'NETWORK_TIMEOUT';
11971
+ err.hint = 'Check the URL and your connection, or download the file and pass its local path.';
11972
+ err.details = { url, stallMs };
11973
+ throw err;
11974
+ }
11975
+ throw error;
11976
+ }
11977
+ }
11978
+
11736
11979
  // Fetch image as buffer
11737
11980
  async function fetchMediaBuffer(pathOrUrl) {
11738
11981
  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());
11982
+ return (await fetchRemoteMedia(pathOrUrl)).buffer;
11751
11983
  }
11752
11984
  try {
11753
11985
  return readFileSync(pathOrUrl);
@@ -11762,20 +11994,9 @@ async function fetchMediaBuffer(pathOrUrl) {
11762
11994
 
11763
11995
  async function fetchMediaBlob(pathOrUrl, fallbackMimeType = 'application/octet-stream') {
11764
11996
  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 });
11997
+ const { buffer, contentType } = await fetchRemoteMedia(pathOrUrl);
11998
+ const mimeType = contentType?.split(';')[0]?.trim() || mimeTypeForPath(pathOrUrl, fallbackMimeType);
11999
+ return new Blob([buffer], { type: mimeType });
11779
12000
  }
11780
12001
 
11781
12002
  const buffer = await fetchMediaBuffer(pathOrUrl);
@@ -11787,6 +12008,7 @@ async function prepareReferenceAudioIdentityMedia(pathOrUrl) {
11787
12008
  if (!pathOrUrl.startsWith('http://') && !pathOrUrl.startsWith('https://') && (cleanExt === '.wav' || cleanExt === '.wave')) {
11788
12009
  const sourcePath = sanitizePath(pathOrUrl, '--reference-audio-identity');
11789
12010
  const ffmpegPath = await ensureFfmpegAvailable();
12011
+ await assertSelfContainedMediaInput(sourcePath);
11790
12012
  const tempDir = createTrackedTempDir('sogni-audio-id-');
11791
12013
  const outputPath = join(tempDir, 'voice-identity.m4a');
11792
12014
  try {
@@ -11794,7 +12016,7 @@ async function prepareReferenceAudioIdentityMedia(pathOrUrl) {
11794
12016
  '-hide_banner',
11795
12017
  '-loglevel', 'error',
11796
12018
  '-y',
11797
- '-i', sourcePath,
12019
+ ...mediaInputArgs(sourcePath),
11798
12020
  '-vn',
11799
12021
  '-ac', '1',
11800
12022
  '-c:a', 'aac',
@@ -11834,11 +12056,12 @@ async function transcodeMp3ReferenceAudioBuffer(buffer, sourceLabel) {
11834
12056
  const outputPath = join(tempDir, 'reference-audio.m4a');
11835
12057
  try {
11836
12058
  writeFileSync(inputPath, buffer);
12059
+ await assertSelfContainedMediaInput(inputPath, sourceLabel);
11837
12060
  const result = await runCommand(ffmpegPath, [
11838
12061
  '-hide_banner',
11839
12062
  '-loglevel', 'error',
11840
12063
  '-y',
11841
- '-i', inputPath,
12064
+ ...mediaInputArgs(inputPath),
11842
12065
  '-vn',
11843
12066
  '-c:a', 'aac',
11844
12067
  '-b:a', '192k',
@@ -11889,11 +12112,12 @@ async function trimPreparedReferenceAudioWindowBuffer(buffer, {
11889
12112
  const outputPath = join(tempDir, 'reference-audio-window.m4a');
11890
12113
  try {
11891
12114
  writeFileSync(inputPath, buffer);
12115
+ await assertSelfContainedMediaInput(inputPath, 'The reference audio');
11892
12116
  const args = ['-hide_banner', '-loglevel', 'error', '-y'];
11893
12117
  if (Number.isFinite(startSeconds) && startSeconds > 0) {
11894
12118
  args.push('-ss', String(startSeconds));
11895
12119
  }
11896
- args.push('-i', inputPath);
12120
+ args.push(...mediaInputArgs(inputPath));
11897
12121
  if (Number.isFinite(durationSeconds) && durationSeconds > 0) {
11898
12122
  args.push('-t', String(durationSeconds));
11899
12123
  }
@@ -11938,35 +12162,26 @@ function withMediaExtension(filename, extension) {
11938
12162
  return `${base || 'reference'}${cleanExtension}`;
11939
12163
  }
11940
12164
 
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 });
12165
+ // The media duration ffprobe reports in seconds, or undefined when it reports none.
12166
+ async function probeMediaDurationSeconds(filePath, label) {
12167
+ const { result, probe } = await probeMediaFile(filePath, { label, entries: ['format=duration'] });
11950
12168
  if (result.error || result.status !== 0) return undefined;
11951
- const parsed = Number(String(result.stdout || '').trim());
12169
+ const raw = probe?.format?.duration;
12170
+ const parsed = raw === undefined || raw === null || raw === '' ? Number.NaN : Number(raw);
11952
12171
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
11953
12172
  }
11954
12173
 
12174
+ async function probeLocalMediaDurationSeconds(pathOrUrl) {
12175
+ if (isHttpUrl(pathOrUrl)) return undefined;
12176
+ return probeMediaDurationSeconds(pathOrUrl, pathOrUrl);
12177
+ }
12178
+
11955
12179
  async function probeMediaBufferDurationSeconds(buffer, filename) {
11956
- const ffprobePath = sanitizePath(getEnv('FFPROBE_PATH') || 'ffprobe', 'FFPROBE_PATH');
11957
12180
  const tempDir = createTrackedTempDir('sogni-wan3-probe-');
11958
12181
  const inputPath = mediaTempInputPath(tempDir, filename, '.media');
11959
12182
  try {
11960
12183
  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;
12184
+ return await probeMediaDurationSeconds(inputPath, filename);
11970
12185
  } finally {
11971
12186
  try { if (existsSync(inputPath)) unlinkSync(inputPath); } catch {}
11972
12187
  try { rmdirSync(tempDir); } catch {}
@@ -12067,11 +12282,12 @@ async function transcodeSeedanceReferenceAudioToMp3(request) {
12067
12282
  const outputPath = join(tempDir, 'reference-audio.mp3');
12068
12283
  try {
12069
12284
  writeFileSync(inputPath, Buffer.from(request.data));
12285
+ await assertSelfContainedMediaInput(inputPath, request.filename);
12070
12286
  const result = await runCommand(ffmpegPath, [
12071
12287
  '-hide_banner',
12072
12288
  '-loglevel', 'error',
12073
12289
  '-y',
12074
- '-i', inputPath,
12290
+ ...mediaInputArgs(inputPath),
12075
12291
  '-vn',
12076
12292
  '-ac', '2',
12077
12293
  '-ar', '44100',
@@ -12108,12 +12324,13 @@ async function trimSeedanceReferenceAudioToMp3(request) {
12108
12324
  );
12109
12325
  try {
12110
12326
  writeFileSync(inputPath, Buffer.from(request.data));
12327
+ await assertSelfContainedMediaInput(inputPath, request.filename);
12111
12328
  const result = await runCommand(ffmpegPath, [
12112
12329
  '-hide_banner',
12113
12330
  '-loglevel', 'error',
12114
12331
  '-y',
12115
12332
  '-ss', String(start),
12116
- '-i', inputPath,
12333
+ ...mediaInputArgs(inputPath),
12117
12334
  '-t', String(duration),
12118
12335
  '-vn',
12119
12336
  '-ac', '2',
@@ -12411,12 +12628,13 @@ async function trimSeedanceV2VSourceVideoBuffer(buffer, sourceLabel, startOffset
12411
12628
  );
12412
12629
  try {
12413
12630
  writeFileSync(inputPath, buffer);
12631
+ await assertSelfContainedMediaInput(inputPath, sourceLabel);
12414
12632
  const result = await runCommand(ffmpegPath, [
12415
12633
  '-hide_banner',
12416
12634
  '-loglevel', 'error',
12417
12635
  '-y',
12418
12636
  '-ss', String(start),
12419
- '-i', inputPath,
12637
+ ...mediaInputArgs(inputPath),
12420
12638
  '-t', String(duration),
12421
12639
  '-map', '0:v:0',
12422
12640
  '-an',
@@ -12853,14 +13071,6 @@ function removeClientListener(client, event, handler) {
12853
13071
  }
12854
13072
  }
12855
13073
 
12856
- let execaPromise = null;
12857
- async function loadExeca() {
12858
- if (!execaPromise) {
12859
- execaPromise = import('execa');
12860
- }
12861
- return execaPromise;
12862
- }
12863
-
12864
13074
  async function ensureFfmpegAvailable(operation = 'this audio/video operation') {
12865
13075
  const ffmpegPath = sanitizePath(getEnv('FFMPEG_PATH') || 'ffmpeg', 'FFMPEG_PATH');
12866
13076
  const result = await runCommand(ffmpegPath, ['-version'], { captureOutput: true });
@@ -12913,10 +13123,14 @@ function isNonEmptyFile(filePath) {
12913
13123
  }
12914
13124
  }
12915
13125
 
12916
- async function runCommand(command, args, { captureOutput = false, env = undefined } = {}) {
13126
+ // A child gets mediaToolEnvironment() plus `env`. Only `inheritEnv: true`, for
13127
+ // a child that is this CLI itself and needs its credentials, passes the whole
13128
+ // environment, with `env` on top.
13129
+ async function runCommand(command, args, { captureOutput = false, env = undefined, inheritEnv = false } = {}) {
12917
13130
  const options = {
12918
13131
  reject: false,
12919
- ...(env ? { env: { ...process.env, ...env } } : {}),
13132
+ extendEnv: inheritEnv,
13133
+ env: inheritEnv ? { ...env } : { ...mediaToolEnvironment(), ...env },
12920
13134
  };
12921
13135
  if (captureOutput) {
12922
13136
  options.stdout = 'pipe';
@@ -12953,6 +13167,8 @@ async function buildAngles360Video(outputPath, frames, fps) {
12953
13167
  sanitizePath(outputPath, '--angles-360-video output path');
12954
13168
  frames.forEach((f, i) => sanitizePath(f, `frame[${i}]`));
12955
13169
  const ffmpegPath = await ensureFfmpegAvailable();
13170
+ // The list is the CLI's own concat input; each frame it names is checked like any other input.
13171
+ for (const frame of frames) await assertSelfContainedMediaInput(frame);
12956
13172
  const tempListPath = outputPath.replace(/\.mp4$/i, '') + '.concat.txt';
12957
13173
  const frameDuration = 1 / fps;
12958
13174
  writeConcatList(tempListPath, frames, frameDuration);
@@ -12961,7 +13177,7 @@ async function buildAngles360Video(outputPath, frames, fps) {
12961
13177
  '-y',
12962
13178
  '-f', 'concat',
12963
13179
  '-safe', '0',
12964
- '-i', tempListPath,
13180
+ ...mediaInputArgs(tempListPath),
12965
13181
  '-r', String(fps),
12966
13182
  '-pix_fmt', 'yuv420p',
12967
13183
  outputPath
@@ -12983,6 +13199,7 @@ async function buildAngles360Video(outputPath, frames, fps) {
12983
13199
 
12984
13200
  async function runFrameExtraction(args, { videoPath, outputImagePath, which }) {
12985
13201
  const ffmpegPath = await ensureFfmpegAvailable();
13202
+ await assertSelfContainedMediaInput(videoPath);
12986
13203
  const result = await runCommand(ffmpegPath, args, { captureOutput: true });
12987
13204
 
12988
13205
  if (result.error || result.status !== 0 || !isNonEmptyFile(outputImagePath)) {
@@ -13016,7 +13233,7 @@ async function extractLastFrameFromVideo(videoPath, outputImagePath) {
13016
13233
  // output so the final write is the genuine last frame.
13017
13234
  const args = [
13018
13235
  '-sseof', '-1',
13019
- '-i', videoPath,
13236
+ ...mediaInputArgs(videoPath),
13020
13237
  '-update', '1', // Keep overwriting -> output is the last decoded frame
13021
13238
  '-q:v', '1', // Best quality
13022
13239
  '-y',
@@ -13032,7 +13249,7 @@ async function extractFirstFrameFromVideo(videoPath, outputImagePath) {
13032
13249
 
13033
13250
  // First decoded frame only.
13034
13251
  const args = [
13035
- '-i', videoPath,
13252
+ ...mediaInputArgs(videoPath),
13036
13253
  '-frames:v', '1',
13037
13254
  '-q:v', '1', // Best quality
13038
13255
  '-y',
@@ -13055,7 +13272,7 @@ async function extractFrameAtTimeFromVideo(videoPath, seconds, outputImagePath)
13055
13272
  // Seek after opening the input for frame-accurate visual QA. Loop Maker
13056
13273
  // clips are short, so accuracy is more useful here than keyframe-only speed.
13057
13274
  const args = [
13058
- '-i', videoPath,
13275
+ ...mediaInputArgs(videoPath),
13059
13276
  '-ss', String(timestamp),
13060
13277
  '-frames:v', '1',
13061
13278
  '-q:v', '1',
@@ -13083,31 +13300,20 @@ function parseFrameRate(raw) {
13083
13300
  return Number.isFinite(v) && v > 0 ? v : null;
13084
13301
  }
13085
13302
 
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;
13303
+ async function probeLocalVideoFrameRate(filePath) {
13304
+ const { result, probe } = await probeMediaFile(filePath, {
13305
+ args: ['-select_streams', 'v:0'],
13306
+ entries: ['stream=avg_frame_rate,r_frame_rate'],
13307
+ });
13308
+ if (result.error || result.status !== 0) return null;
13309
+ const stream = Array.isArray(probe?.streams) ? probe.streams[0] : null;
13310
+ return parseFrameRate(stream?.avg_frame_rate) || parseFrameRate(stream?.r_frame_rate) || null;
13106
13311
  }
13107
13312
 
13108
13313
  // Probe a media file's primary video stream + whether it has any audio.
13109
13314
  // Fields are null when the probe fails (e.g. ffprobe missing); callers fall
13110
- // back to safe defaults unless they explicitly require verification.
13315
+ // back to safe defaults unless they explicitly require verification. A file
13316
+ // that names other inputs throws UNSAFE_MEDIA_INPUT.
13111
13317
  async function probeVideoStreamInfo(filePath) {
13112
13318
  const info = {
13113
13319
  width: null,
@@ -13118,17 +13324,10 @@ async function probeVideoStreamInfo(filePath) {
13118
13324
  videoCodec: null,
13119
13325
  audioCodec: null
13120
13326
  };
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; }
13327
+ const { result, probe: parsed } = await probeMediaFile(filePath, {
13328
+ entries: ['stream=codec_type,codec_name,width,height,avg_frame_rate,r_frame_rate', 'format=duration'],
13329
+ });
13330
+ if (result.error || result.status !== 0 || !parsed) return info;
13132
13331
  const streams = Array.isArray(parsed.streams) ? parsed.streams : [];
13133
13332
  const video = streams.find((s) => s.codec_type === 'video');
13134
13333
  const audio = streams.find((s) => s.codec_type === 'audio');
@@ -13160,7 +13359,7 @@ async function verifyVideoFile(videoPath) {
13160
13359
  const result = await runCommand(ffmpegPath, [
13161
13360
  '-hide_banner',
13162
13361
  '-loglevel', 'error',
13163
- '-i', videoPath,
13362
+ ...mediaInputArgs(videoPath),
13164
13363
  '-map', '0:v:0',
13165
13364
  '-map', '0:a?',
13166
13365
  '-f', 'null',
@@ -13186,11 +13385,12 @@ async function trimVideoClip(inputPath, startSeconds, durationSeconds, outputPat
13186
13385
  sanitizePath(inputPath, 'trim input video');
13187
13386
  sanitizePath(outputPath, 'trim output video');
13188
13387
  const ffmpegPath = await ensureFfmpegAvailable();
13388
+ await assertSelfContainedMediaInput(inputPath);
13189
13389
  const result = await runCommand(ffmpegPath, [
13190
13390
  '-hide_banner',
13191
13391
  '-loglevel', 'error',
13192
13392
  '-y',
13193
- '-i', inputPath,
13393
+ ...mediaInputArgs(inputPath),
13194
13394
  '-ss', String(startSeconds),
13195
13395
  '-t', String(durationSeconds),
13196
13396
  '-map', '0:v:0',
@@ -13232,6 +13432,9 @@ async function buildConcatVideoFromClips(outputPath, clips, { audioPath = null,
13232
13432
  if (audioPath) sanitizePath(audioPath, '--concat-audio');
13233
13433
  const ffmpegPath = await ensureFfmpegAvailable();
13234
13434
 
13435
+ for (const input of audioPath ? [...clips, audioPath] : clips) {
13436
+ await assertSelfContainedMediaInput(input);
13437
+ }
13235
13438
  const infos = [];
13236
13439
  for (const clip of clips) {
13237
13440
  infos.push(await probeVideoStreamInfo(clip));
@@ -13278,7 +13481,7 @@ async function buildConcatVideoFromClips(outputPath, clips, { audioPath = null,
13278
13481
  );
13279
13482
 
13280
13483
  const args = ['-y'];
13281
- clips.forEach((clip) => { args.push('-i', clip); });
13484
+ clips.forEach((clip) => { args.push(...mediaInputArgs(clip)); });
13282
13485
 
13283
13486
  let mapAudio = '[ca]';
13284
13487
  if (audioPath) {
@@ -13287,7 +13490,7 @@ async function buildConcatVideoFromClips(outputPath, clips, { audioPath = null,
13287
13490
  if (Number.isFinite(audioStart) && audioStart > 0) {
13288
13491
  args.push('-ss', String(audioStart));
13289
13492
  }
13290
- args.push('-i', audioPath);
13493
+ args.push(...mediaInputArgs(audioPath));
13291
13494
  const extIdx = clips.length;
13292
13495
  let extChain = `[${extIdx}:a]aformat=sample_rates=44100:channel_layouts=stereo,apad`;
13293
13496
  if (totalDuration > 0) {
@@ -13338,11 +13541,14 @@ async function remixVideoAudio(inputVideo, outputVideo, opts = {}) {
13338
13541
  if (bedAudio) sanitizePath(bedAudio, '--bed-audio');
13339
13542
  if (mixAudio) sanitizePath(mixAudio, '--mix-audio');
13340
13543
  const ffmpegPath = await ensureFfmpegAvailable();
13544
+ for (const input of [inputVideo, bedAudio, mixAudio].filter(Boolean)) {
13545
+ await assertSelfContainedMediaInput(input);
13546
+ }
13341
13547
 
13342
13548
  const info = await probeVideoStreamInfo(inputVideo);
13343
13549
  const totalDuration = info.duration && info.duration > 0 ? info.duration : null;
13344
13550
 
13345
- const args = ['-y', '-i', inputVideo];
13551
+ const args = ['-y', ...mediaInputArgs(inputVideo)];
13346
13552
 
13347
13553
  // Resolve the bed source. With --audio-loop we re-open the source as a
13348
13554
  // -stream_loop input (the only robust, duration-based loop in ffmpeg).
@@ -13350,11 +13556,11 @@ async function remixVideoAudio(inputVideo, outputVideo, opts = {}) {
13350
13556
  let nextIndex = 1;
13351
13557
  const bedSourceFile = bedAudio || inputVideo;
13352
13558
  if (loop) {
13353
- args.push('-stream_loop', '-1', '-i', bedSourceFile);
13559
+ args.push('-stream_loop', '-1', ...mediaInputArgs(bedSourceFile));
13354
13560
  bedRef = `[${nextIndex}:a]`;
13355
13561
  nextIndex += 1;
13356
13562
  } else if (bedAudio) {
13357
- args.push('-i', bedAudio);
13563
+ args.push(...mediaInputArgs(bedAudio));
13358
13564
  bedRef = `[${nextIndex}:a]`;
13359
13565
  nextIndex += 1;
13360
13566
  } else {
@@ -13364,7 +13570,7 @@ async function remixVideoAudio(inputVideo, outputVideo, opts = {}) {
13364
13570
  let mixIndex = null;
13365
13571
  if (mixAudio) {
13366
13572
  mixIndex = nextIndex;
13367
- args.push('-i', mixAudio);
13573
+ args.push(...mediaInputArgs(mixAudio));
13368
13574
  nextIndex += 1;
13369
13575
  }
13370
13576
 
@@ -13800,6 +14006,7 @@ function sourceReelLineageEnvironment(workloadAttribution) {
13800
14006
  async function runSourceReelChild(label, args, logPath, outputPath, workloadAttribution) {
13801
14007
  const result = await runCommand(process.execPath, args, {
13802
14008
  captureOutput: true,
14009
+ inheritEnv: true,
13803
14010
  env: sourceReelLineageEnvironment(workloadAttribution),
13804
14011
  });
13805
14012
  const parsed = parseSourceReelChildJson(result.stdout);
@@ -14020,6 +14227,7 @@ function waitCommandFor(projectId) {
14020
14227
  * still ends a run whose submission never completes.
14021
14228
  */
14022
14229
  function createProjectWaitTracker(client, log, timeoutMs = options.timeout) {
14230
+ const stopWatching = watchForConnectionTakeover(client);
14023
14231
  const projects = new Map();
14024
14232
  const reasons = new Map();
14025
14233
  const described = new Map();
@@ -14046,6 +14254,7 @@ function createProjectWaitTracker(client, log, timeoutMs = options.timeout) {
14046
14254
  return now - startedAt - heldMs - (heldSince === null ? 0 : now - heldSince);
14047
14255
  };
14048
14256
  const cleanup = () => {
14257
+ stopWatching();
14049
14258
  clearTimeout(timer);
14050
14259
  if (typeof sdkProjects?.off === 'function') sdkProjects.off('queueChanged', onQueueChanged);
14051
14260
  };
@@ -14370,12 +14579,14 @@ async function followProjectToEnd(client, projectId, { log, creds, timeoutMs })
14370
14579
  }
14371
14580
  }
14372
14581
  const deadline = Date.now() + timeoutMs;
14373
- let tracked = await trackedProjectAfterSync(projectsApi, projectId);
14582
+ const stopWatching = watchForConnectionTakeover(client, projectId);
14374
14583
  let trackingClient = client;
14375
14584
  let sideClient = null;
14376
14585
  let claim = null;
14377
14586
  let stopProgressEvents = () => {};
14587
+ let stopWatchingSideClient;
14378
14588
  try {
14589
+ let tracked = await trackedProjectAfterSync(projectsApi, projectId);
14379
14590
  if (!tracked) {
14380
14591
  const inFlight = await projectsApi.listProjectsElsewhere();
14381
14592
  const holder = (inFlight || []).find((project) => project?.id === projectId);
@@ -14385,8 +14596,14 @@ async function followProjectToEnd(client, projectId, { log, creds, timeoutMs })
14385
14596
  log(`Taking project ${projectId} back from the run that submitted it...`);
14386
14597
  sideClient = createSkillSogniClient(creds, claim.appId);
14387
14598
  await connectSogniClient(sideClient);
14599
+ stopWatchingSideClient = watchForConnectionTakeover(sideClient, projectId);
14388
14600
  tracked = await trackedProjectAfterSync(sdkClientOf(sideClient).projects, projectId);
14389
- trackingClient = sideClient;
14601
+ if (tracked) {
14602
+ stopWatching();
14603
+ trackingClient = sideClient;
14604
+ } else {
14605
+ stopWatchingSideClient();
14606
+ }
14390
14607
  }
14391
14608
  if (!tracked) {
14392
14609
  log(claim?.heldByPid
@@ -14404,6 +14621,8 @@ async function followProjectToEnd(client, projectId, { log, creds, timeoutMs })
14404
14621
  }
14405
14622
  await settleTrackedProject(tracked, { log, deadline, timeoutMs });
14406
14623
  } finally {
14624
+ stopWatching();
14625
+ stopWatchingSideClient?.();
14407
14626
  stopProgressEvents();
14408
14627
  if (sideClient) {
14409
14628
  try { await sideClient.disconnect(); } catch { /* already closed */ }
@@ -14538,6 +14757,7 @@ async function buildProjectTimeoutError(projects, timeoutMs, label = 'Project')
14538
14757
  }
14539
14758
 
14540
14759
  async function runImageEditProjectWithEvents(client, editConfig, expectedCount, log, timeoutMs, label) {
14760
+ const stopWatching = watchForConnectionTakeover(client);
14541
14761
  const results = [];
14542
14762
  let completed = 0;
14543
14763
  let projectId = null;
@@ -14578,6 +14798,7 @@ async function runImageEditProjectWithEvents(client, editConfig, expectedCount,
14578
14798
  };
14579
14799
 
14580
14800
  const cleanup = () => {
14801
+ stopWatching();
14581
14802
  clearTimeout(timeout);
14582
14803
  removeClientListener(client, ClientEvent.JOB_COMPLETED, onCompleted);
14583
14804
  removeClientListener(client, ClientEvent.JOB_FAILED, onFailed);
@@ -14902,7 +15123,8 @@ async function runMultiAngleFlow(client, log) {
14902
15123
  if (options.autoResizeVideoAssets !== null) {
14903
15124
  clipConfig.autoResizeVideoAssets = options.autoResizeVideoAssets;
14904
15125
  }
14905
- const clipResult = await client.createVideoProject(withBillingMode(clipConfig));
15126
+ const stopWatching = watchForConnectionTakeover(client);
15127
+ const clipResult = await client.createVideoProject(withBillingMode(clipConfig)).finally(stopWatching);
14906
15128
 
14907
15129
  // Check for errors in the response (e.g., insufficient tokens)
14908
15130
  if (clipResult?.error || clipResult?.message) {
@@ -15701,15 +15923,7 @@ async function runDoctor() {
15701
15923
  if (creds?.SOGNI_API_KEY) {
15702
15924
  let doctorClient = null;
15703
15925
  try {
15704
- doctorClient = new SogniClientWrapper({
15705
- appSource: SOGNI_APP_SOURCE,
15706
- appId: getOrCreateSogniAppId(),
15707
- attribution: clientAttribution(AGENT_ATTRIBUTION),
15708
- network: renderNetwork,
15709
- autoConnect: false,
15710
- apiKey: creds.SOGNI_API_KEY,
15711
- authType: 'apiKey'
15712
- });
15926
+ doctorClient = createSkillSogniClient(creds, getOrCreateSogniAppId());
15713
15927
  const authFlow = (async () => {
15714
15928
  await connectSogniClient(doctorClient);
15715
15929
  const balance = await doctorClient.getBalance();
@@ -17659,7 +17873,8 @@ async function main() {
17659
17873
  // projects.create() resolves once the request is handed to the socket, before the server
17660
17874
  // has it, so exiting at once dropped every detached project (2026-10-01: none reached
17661
17875
  // the server, yet each was reported as submitted). Report only what the server answered.
17662
- const unconfirmed = await awaitServerAnswer([...activeProjects]);
17876
+ const stopWatching = watchForConnectionTakeover(client);
17877
+ const unconfirmed = await awaitServerAnswer([...activeProjects]).finally(stopWatching);
17663
17878
  const refused = [...activeProjects].find((project) => project?.status === 'failed');
17664
17879
  if (refused) throw buildProjectResultError({ error: refused.terminalError?.() ?? refused.error }, 'Sogni refused the project');
17665
17880
  if (unconfirmed.length) {
@@ -17852,20 +18067,13 @@ async function main() {
17852
18067
 
17853
18068
  // Create a new client for second clip to avoid event conflicts
17854
18069
  const creds = loadCredentials();
17855
- const client2 = new SogniClientWrapper({
17856
- appSource: SOGNI_APP_SOURCE,
17857
- appId: getOrCreateSogniAppId(),
17858
- attribution: clientAttribution(AGENT_ATTRIBUTION),
17859
- network: renderNetwork,
17860
- autoConnect: false,
17861
- apiKey: creds.SOGNI_API_KEY,
17862
- authType: 'apiKey'
17863
- });
18070
+ const client2 = createSkillSogniClient(creds, getOrCreateSogniAppId());
17864
18071
  await connectSogniClient(client2);
17865
18072
  await disableLiveModelAvailabilityEvents(client2);
17866
18073
 
17867
18074
  // Create second clip and wait for completion via events
17868
18075
  let activeClip2Project = null;
18076
+ const stopWatchingClip2 = watchForConnectionTakeover(client2);
17869
18077
  const clip2Promise = new Promise((resolve, reject) => {
17870
18078
  const timeout = setTimeout(() => {
17871
18079
  void buildProjectTimeoutError([activeClip2Project], options.timeout, 'second clip project')
@@ -17873,6 +18081,7 @@ async function main() {
17873
18081
  }, options.timeout);
17874
18082
 
17875
18083
  client2.on(ClientEvent.JOB_COMPLETED, async (data) => {
18084
+ stopWatchingClip2();
17876
18085
  try {
17877
18086
  clearTimeout(timeout);
17878
18087
  if (data.job?.isWithheld === true) {