@sogni-ai/sogni-creative-agent-skill 3.72.0 → 3.72.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.
@@ -124,7 +124,7 @@ LTX-2.5 text-to-video, one shot, so one sentence: "A medium shot frames a woman
124
124
  ```
125
125
 
126
126
  <!-- BEGIN GENERATED PROMPT GUIDE: ltx-2.5 -->
127
- <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.1; edit the rules there, not here. -->
127
+ <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.2; edit the rules there, not here. -->
128
128
 
129
129
  ### Sogni's prompt rules: ltx-2.5
130
130
 
@@ -179,7 +179,7 @@ Preserve requested visual style and production value without adding new objects,
179
179
  <!-- END GENERATED PROMPT GUIDE: ltx-2.5 -->
180
180
 
181
181
  <!-- BEGIN GENERATED PROMPT GUIDE: ltx-2.3 -->
182
- <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.1; edit the rules there, not here. -->
182
+ <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.2; edit the rules there, not here. -->
183
183
 
184
184
  ### Sogni's prompt rules: ltx-2.3
185
185
 
@@ -227,7 +227,7 @@ Preserve requested visual style and production value without adding new objects,
227
227
 
228
228
  ## MiniMax H3 Prompting
229
229
 
230
- For MiniMax reference-to-video, default to **Balanced R2V** (`minimax-h3-r2v-balanced`), the tier that passes the quality bar for mature content and holds Mystic X at full strength (as of 2026-10). Use `minimax-h3-r2v-balanced-2stage` for two-stage, 1080p or 2K output. Keep Standard, LightX2V Turbo, or FastH3 Omni R2V only when explicitly requested.
230
+ When MiniMax H3 is selected for loose visual references and the creator has opted to use the Sensitive Content Filter off, prefer **Prism** (`minimax-h3-r2v-prism`) or `minimax-h3-r2v-prism-2stage` for two-stage, 1080p or 2K. Both require `--no-filter`. Otherwise use `minimax-h3-r2v-balanced` or `minimax-h3-r2v-balanced-2stage`. Keep the requested model and check compatibility with any requested LoRA.
231
231
 
232
232
  Write every H3 prompt using MiniMax's official structured rewrite contract. Do
233
233
  not substitute an unstructured prompt for the required fields. The field names,
@@ -977,7 +977,7 @@ the exact waveform-conditioned lip-sync input. Remote audio URLs and additional
977
977
  audio references keep their existing handling.
978
978
 
979
979
  <!-- BEGIN GENERATED PROMPT GUIDE: minimax-h3 -->
980
- <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.1; edit the rules there, not here. -->
980
+ <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.2; edit the rules there, not here. -->
981
981
 
982
982
  ### Sogni's prompt rules: minimax-h3
983
983
 
@@ -1059,7 +1059,7 @@ FINAL ASSESSMENT: silently verify the exact field order, required alignment line
1059
1059
  - Use stable (S1) speaker IDs and wrap exact spoken words in <d>[Language] ...</d>; keep visible text in exact double quotes.
1060
1060
  - overall_soundscape owns diegetic ambience and effects; non_diegetic_music owns audience-only score and is N/A when there is none.
1061
1061
  - Standard runs 20 steps with res_multistep/simple. Balanced uses fixed 8-step Euler/simple acceleration: LightX2V for FL2VA and Larry v4 for Ref2VA. FL2VA Turbo runs 4 steps with simple scheduling; er_sde is the default sampler, with euler and sa_solver available as explicit A/B variants. Ref2VA Turbo uses the exact upstream 4-step euler/simple recipe. All run at fixed 24 fps and guidance 1.
1062
- - Default MiniMax reference-to-video to Balanced R2V (minimax-h3-r2v-balanced), or minimax-h3-r2v-balanced-2stage for two-stage, 1080p or 2K output. Preserve an explicitly requested Standard, LightX2V Turbo, or FastH3 Omni R2V tier.
1062
+ - For MiniMax video from loose references, honor a specified model first, then the eligible tier recommended by the session. Otherwise use minimax-h3-r2v-balanced, or minimax-h3-r2v-balanced-2stage for two-stage, 1080p or 2K.
1063
1063
  - Standard, Balanced, and Turbo Ref2VA use exactly six ordered fields: subject_definitions, summary, retention_analysis, detailed_description, overall_soundscape, non_diegetic_music. The two-stage Ref2VA selectors (minimax-h3-r2v-2stage at 20 steps, minimax-h3-r2v-balanced-2stage at 8 steps) write the same six-field contract with the same references; only the delivered size changes. FastH3 Reference (minimax-h3-fasth3-r2v-turbo and its -2stage form, the FastH3 tier's reference-to-video) writes the same six-field contract.
1064
1064
  - Ref2VA uses <Subject N> for reusable visible content, <Picture N> only for concrete keyframe/composition anchors, <Video N> for whole-video relationships, and <Audio N> for copied or referenced signals. It requires at least one image or video; audio alone is invalid.
1065
1065
  - The FastH3 audio guide on sound_to_video (minimax-h3-fasth3-ia2v-turbo, minimax-h3-fasth3-flfa2v-turbo, minimax-h3-fasth3-a2v-turbo and their -2stage forms) writes the Base contract of its mode: image + audio as I2V, first/last frame + audio as FLF2V, audio only as T2V. The uploaded audio drives the picture from frame 0 and is the soundtrack, so describe what it contains and never add other dialogue or music. Use these selectors only when the user asks for MiniMax H3 or FastH3.
@@ -1195,7 +1195,7 @@ A low tracking shot races alongside a teal 1960s convertible down a sunlit coast
1195
1195
  ```
1196
1196
 
1197
1197
  <!-- BEGIN GENERATED PROMPT GUIDE: seedance-2.5 -->
1198
- <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.1; edit the rules there, not here. -->
1198
+ <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.2; edit the rules there, not here. -->
1199
1199
 
1200
1200
  ### Sogni's prompt rules: seedance-2.5
1201
1201
 
@@ -1269,7 +1269,7 @@ TARGET CAPABILITIES: Seedance 2.5 uses the same director-style prompt grammar an
1269
1269
  <!-- END GENERATED PROMPT GUIDE: seedance-2.5 -->
1270
1270
 
1271
1271
  <!-- BEGIN GENERATED PROMPT GUIDE: seedance-2.0 -->
1272
- <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.1; edit the rules there, not here. -->
1272
+ <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.2; edit the rules there, not here. -->
1273
1273
 
1274
1274
  ### Sogni's prompt rules: seedance-2.0
1275
1275
 
@@ -1378,7 +1378,7 @@ writer uses close this section.
1378
1378
  motion timing, camera path, framing, and background.
1379
1379
 
1380
1380
  <!-- BEGIN GENERATED PROMPT GUIDE: wan-2.2 -->
1381
- <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.1; edit the rules there, not here. -->
1381
+ <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.2; edit the rules there, not here. -->
1382
1382
 
1383
1383
  ### Sogni's prompt rules: wan-2.2
1384
1384
 
@@ -1468,7 +1468,7 @@ The rules Sogni's own prompt writer uses close this section.
1468
1468
  - Prompts may run to 20,000 characters.
1469
1469
 
1470
1470
  <!-- BEGIN GENERATED PROMPT GUIDE: wan-3 -->
1471
- <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.1; edit the rules there, not here. -->
1471
+ <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.2; edit the rules there, not here. -->
1472
1472
 
1473
1473
  ### Sogni's prompt rules: wan-3
1474
1474
 
@@ -1523,7 +1523,7 @@ audio that is always on. What it renders well and the reference limits are in
1523
1523
  [models.md § HappyHorse 1.1](./models.md#happyhorse-11-prompting-tips).
1524
1524
 
1525
1525
  <!-- BEGIN GENERATED PROMPT GUIDE: happyhorse-1.1 -->
1526
- <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.1; edit the rules there, not here. -->
1526
+ <!-- Generated by npm run sync:prompt-guides from @sogni-ai/sogni-intelligence-client 4.32.2; edit the rules there, not here. -->
1527
1527
 
1528
1528
  ### Sogni's prompt rules: happyhorse-1.1
1529
1529
 
@@ -3,7 +3,7 @@
3
3
  "private": true,
4
4
  "type": "module",
5
5
  "dependencies": {
6
- "@sogni-ai/sogni-intelligence-client": "4.32.1",
6
+ "@sogni-ai/sogni-intelligence-client": "4.32.2",
7
7
  "execa": "^10.0.1",
8
8
  "json5": "^2.2.3",
9
9
  "sharp": "0.35.5"
package/sogni-agent.mjs CHANGED
@@ -12,7 +12,7 @@ import JSON5 from 'json5';
12
12
  import { createHash, randomBytes } from 'crypto';
13
13
  import { execFileSync } from 'child_process';
14
14
  import { createRequire } from 'module';
15
- import { readFileSync, writeFileSync, existsSync, mkdirSync, mkdtempSync, statSync, readdirSync, realpathSync, lstatSync, unlinkSync, rmdirSync, rmSync, renameSync } from 'fs';
15
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, mkdtempSync, statSync, readdirSync, realpathSync, lstatSync, unlinkSync, rmdirSync, rmSync, renameSync, openSync, writeSync, closeSync } from 'fs';
16
16
  import { join, dirname, basename, extname, sep, resolve } from 'path';
17
17
  import { homedir, tmpdir } from 'os';
18
18
  import sharp from 'sharp';
@@ -428,6 +428,9 @@ process.on('exit', () => {
428
428
  // normal exit, fatal error, or signal. Ctrl-C during a long video job is the
429
429
  // common case that used to orphan directories under os.tmpdir().
430
430
  const TRACKED_TEMP_DIRS = new Set();
431
+ // In-flight result downloads (.part files beside the -o target). A signal exits
432
+ // through process.exit(), which skips the downloader's finally, so 'exit' removes them.
433
+ const TRACKED_TEMP_FILES = new Set();
431
434
 
432
435
  function createTrackedTempDir(prefix) {
433
436
  const dir = mkdtempSync(join(tmpdir(), prefix));
@@ -436,6 +439,10 @@ function createTrackedTempDir(prefix) {
436
439
  }
437
440
 
438
441
  function cleanupTrackedTempDirs() {
442
+ for (const file of TRACKED_TEMP_FILES) {
443
+ try { rmSync(file, { force: true }); } catch { /* best effort */ }
444
+ TRACKED_TEMP_FILES.delete(file);
445
+ }
439
446
  for (const dir of TRACKED_TEMP_DIRS) {
440
447
  try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }
441
448
  TRACKED_TEMP_DIRS.delete(dir);
@@ -861,6 +868,11 @@ function classifyCliError(error, context = {}) {
861
868
  return { error_type: 'PROVIDER_TIMEOUT', category: 'timeout', message: rawMessage, retryable: true };
862
869
  }
863
870
 
871
+ // The render finished; only its download failed, and `--result` (details.resultCommands) fetches it later.
872
+ if (error?.code === 'RESULT_DOWNLOAD_FAILED') {
873
+ return { error_type: 'PROVIDER_TIMEOUT', category: 'timeout', message: rawMessage, retryable: true };
874
+ }
875
+
864
876
  // Socket 4103: Seedance 2.5 Uncensored, Seedance 2.0 Mini Uncensored, Seedream
865
877
  // 5.0 Pro Uncensored and Seedream 5.5 Uncensored refuse every job until the account accepts their
866
878
  // shared one-time likeness and consent agreement in the Sogni app. The message
@@ -5755,7 +5767,7 @@ Video Options:
5755
5767
  --ref-video <path|url> Video reference. Repeatable on Seedance and H3 r2v (up to 3 total);
5756
5768
  first entry is the primary, extras must be HTTPS URLs in CLI
5757
5769
  direct-gen for Seedance. On LTX/WAN: single primary for animate/v2v.
5758
- --generate-audio, --no-generate-audio Keep/strip H3 audio; enable/disable Wan 3 native audio
5770
+ --generate-audio, --no-generate-audio Keep/strip H3 audio; enable/disable Wan 3 and Seedance native audio
5759
5771
 
5760
5772
  Seedance Reference Modes (mutually exclusive on seedance2 / seedance2-mini / seedance2-mini-uncensored /
5761
5773
  seedance2-fast / seedance2-5 / seedance2-5-uncensored):
@@ -6052,9 +6064,11 @@ state negatives in the structured prompt.):
6052
6064
  minimax-h3-t2v-balanced Balanced text-to-video
6053
6065
  minimax-h3-i2v-balanced Balanced I2VA (--ref) or L2VA (--ref-end)
6054
6066
  minimax-h3-flf2v-balanced Balanced first-frame -> last-frame (--ref plus --ref-end)
6055
- minimax-h3-r2v-balanced Balanced Ref2VA with loose image/video/audio references
6056
- minimax-h3-r2v-prism Optional Ref2VA model for mature themes on Balanced's graph: 768p class,
6057
- Balanced's references, keyframes and LoRAs; requires --no-filter
6067
+ minimax-h3-r2v-balanced Balanced Ref2VA with loose image/video/audio references; with the filter
6068
+ off, use minimax-h3-r2v-prism instead
6069
+ minimax-h3-r2v-prism Prism Ref2VA, the reference-to-video model whenever the filter is off (any
6070
+ theme), on Balanced's graph: 768p class, Balanced's references, keyframes
6071
+ and LoRAs; requires --no-filter
6058
6072
  minimax-h3-r2v-prism-2stage Prism Two-Stage: the minimax-h3-r2v-prism request, delivered at twice the
6059
6073
  canvas like minimax-h3-r2v-balanced-2stage; requires --no-filter
6060
6074
  minimax-h3-r2v-2stage Ref2VA Two-Stage: the minimax-h3-r2v request (20 steps), delivered at twice the
@@ -12581,23 +12595,27 @@ function writeOutputFileSafe(filePath, buffer, label = 'output') {
12581
12595
  if (dir && dir !== '.' && !existsSync(dir)) mkdirSync(dir, { recursive: true });
12582
12596
  writeFileSync(filePath, buffer);
12583
12597
  } catch (e) {
12584
- const code = e?.code;
12585
- const err = new Error(`Could not write ${label} to ${filePath}.`);
12586
- err.code = 'OUTPUT_WRITE_FAILED';
12587
- if (code === 'EACCES' || code === 'EPERM' || code === 'EROFS') {
12588
- err.hint = 'The output path is not writable. Choose a different --output location or fix the directory permissions.';
12589
- } else if (code === 'ENOSPC') {
12590
- err.hint = 'No space left on the device. Free up disk space or choose another --output location.';
12591
- } else if (code === 'ENOENT') {
12592
- err.hint = 'The output directory does not exist and could not be created. Check the --output path.';
12593
- } else if (code === 'EISDIR') {
12594
- err.hint = '--output points to a directory; pass a file path instead.';
12595
- } else {
12596
- err.hint = 'Check the --output path and permissions.';
12597
- }
12598
- err.details = { filePath, cause: code || String(e) };
12599
- throw err;
12598
+ throw outputWriteError(e, filePath, label);
12599
+ }
12600
+ }
12601
+
12602
+ function outputWriteError(e, filePath, label) {
12603
+ const code = e?.code;
12604
+ const err = new Error(`Could not write ${label} to ${filePath}.`);
12605
+ err.code = 'OUTPUT_WRITE_FAILED';
12606
+ if (code === 'EACCES' || code === 'EPERM' || code === 'EROFS') {
12607
+ err.hint = 'The output path is not writable. Choose a different --output location or fix the directory permissions.';
12608
+ } else if (code === 'ENOSPC') {
12609
+ err.hint = 'No space left on the device. Free up disk space or choose another --output location.';
12610
+ } else if (code === 'ENOENT') {
12611
+ err.hint = 'The output directory does not exist and could not be created. Check the --output path.';
12612
+ } else if (code === 'EISDIR') {
12613
+ err.hint = '--output points to a directory; pass a file path instead.';
12614
+ } else {
12615
+ err.hint = 'Check the --output path and permissions.';
12600
12616
  }
12617
+ err.details = { filePath, cause: code || String(e) };
12618
+ return err;
12601
12619
  }
12602
12620
 
12603
12621
  // With the Sensitive Content Filter on, the server withholds a flagged result:
@@ -12612,13 +12630,219 @@ function sensitiveContentWithheldError(totalCount = 1) {
12612
12630
  return err;
12613
12631
  }
12614
12632
 
12615
- async function downloadUrlToFile(url, filePath) {
12616
- const response = await fetchWithTimeout(url);
12617
- if (!response.ok) {
12618
- throw new Error(`Failed to download image: ${response.statusText}`);
12633
+ // Result downloads (media.sogni.ai). fetchWithTimeout bounds only the wait for the
12634
+ // headers, so an edge that trickled or stopped a body held a finished run open with no
12635
+ // end: on 2026-11-20 "Video 1/1 completed" waited 5+ minutes (curl got 1.9 MB in 418 s,
12636
+ // then an HTTP/2 INTERNAL_ERROR) and `--result` fetches of it ended "terminated".
12637
+ // An attempt now ends once no byte has arrived for MEDIA_DOWNLOAD_STALL_TIMEOUT_MS; a
12638
+ // failed attempt is retried after each MEDIA_DOWNLOAD_RETRY_BACKOFF_MS wait, resuming
12639
+ // with a Range request from the bytes already saved unless the server rules ranges out.
12640
+ // Bytes go to a hidden temp file beside the target, renamed into place only when complete.
12641
+ const MEDIA_DOWNLOAD_STALL_TIMEOUT_MS = 30_000;
12642
+ const MEDIA_DOWNLOAD_RETRY_BACKOFF_MS = [2_000, 5_000, 10_000];
12643
+
12644
+ /** The stall limit and retry waits; only the test harness may shorten them. */
12645
+ function mediaDownloadTiming() {
12646
+ const testMs = (name) => {
12647
+ const raw = getEnv('SOGNI_AGENT_TEST_STATE_PATH') ? getEnv(name) : undefined;
12648
+ const value = raw ? Number(raw) : NaN;
12649
+ return Number.isFinite(value) && value >= 0 ? value : null;
12650
+ };
12651
+ const stallMs = testMs('SOGNI_AGENT_TEST_DOWNLOAD_STALL_MS');
12652
+ const backoffMs = testMs('SOGNI_AGENT_TEST_DOWNLOAD_BACKOFF_MS');
12653
+ return {
12654
+ stallMs: stallMs || MEDIA_DOWNLOAD_STALL_TIMEOUT_MS,
12655
+ backoffMs: backoffMs === null ? MEDIA_DOWNLOAD_RETRY_BACKOFF_MS : MEDIA_DOWNLOAD_RETRY_BACKOFF_MS.map(() => backoffMs),
12656
+ };
12657
+ }
12658
+
12659
+ function formatDownloadDuration(ms) {
12660
+ return ms < 1000 ? `${ms} ms` : `${Math.round(ms / 1000)} s`;
12661
+ }
12662
+
12663
+ function formatDownloadProgress({ received, total }) {
12664
+ const bytes = (n) => n.toLocaleString('en-US');
12665
+ return total === null ? `${bytes(received)} bytes` : `${bytes(received)} of ${bytes(total)} bytes`;
12666
+ }
12667
+
12668
+ function shellWord(value) {
12669
+ return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${String(value).replace(/'/g, `'\\''`)}'`;
12670
+ }
12671
+
12672
+ /** A failed attempt that another one may fix; `reason` finishes "the download from <host> ...". */
12673
+ function retryableDownloadError(reason, cause = undefined) {
12674
+ const err = new Error(`Result download ${reason}`);
12675
+ err.downloadRetryable = true;
12676
+ err.reason = reason;
12677
+ if (cause) err.cause = cause;
12678
+ return err;
12679
+ }
12680
+
12681
+ function downloadConnectionReason(error) {
12682
+ const cause = error?.cause?.message || error?.cause?.code || error?.message || error?.code || String(error);
12683
+ return `lost the connection: ${cause}`;
12684
+ }
12685
+
12686
+ /**
12687
+ * Download a finished result to filePath. `projectId` and `retryOutput` (the -o path that
12688
+ * `--result` would save to) build the command printed when every attempt fails;
12689
+ * `validate(tempPath)` may refuse the bytes before they replace filePath.
12690
+ */
12691
+ async function downloadUrlToFile(url, filePath, { projectId = null, retryOutput = null, label = 'output', validate = null } = {}) {
12692
+ const { stallMs, backoffMs } = mediaDownloadTiming();
12693
+ let host = 'the media server';
12694
+ try { host = new URL(url).host; } catch { /* keep the generic name */ }
12695
+ const say = options.quiet ? () => {} : console.error.bind(console);
12696
+ const dir = dirname(filePath);
12697
+ const tempPath = join(dir, `.${basename(filePath)}.${process.pid}-${randomBytes(4).toString('hex')}.part`);
12698
+ TRACKED_TEMP_FILES.add(tempPath);
12699
+ // received: bytes in tempPath; total: the full size when the server says it;
12700
+ // validator: the ETag / Last-Modified sent as If-Range; resumable: false once ranges are ruled out.
12701
+ const state = { received: 0, total: null, validator: null, resumable: true };
12702
+ const attempts = backoffMs.length + 1;
12703
+ let lastFailure = null;
12704
+ let saved = false;
12705
+ try {
12706
+ try {
12707
+ if (dir && dir !== '.' && !existsSync(dir)) mkdirSync(dir, { recursive: true });
12708
+ } catch (e) {
12709
+ throw outputWriteError(e, filePath, label);
12710
+ }
12711
+ for (let attempt = 1; attempt <= attempts; attempt++) {
12712
+ if (lastFailure) {
12713
+ const waitMs = backoffMs[attempt - 2];
12714
+ const resume = state.received > 0 && state.resumable && state.validator ? ', resuming where it stopped' : '';
12715
+ say(`Result download from ${host} ${lastFailure.reason} at ${formatDownloadProgress(state)}; retrying in ${formatDownloadDuration(waitMs)} (attempt ${attempt} of ${attempts}${resume}).`);
12716
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
12717
+ }
12718
+ try {
12719
+ await downloadResultAttempt(url, tempPath, state, { stallMs, filePath, label });
12720
+ } catch (error) {
12721
+ if (!error?.downloadRetryable) throw error;
12722
+ lastFailure = error;
12723
+ continue;
12724
+ }
12725
+ if (validate) validate(tempPath);
12726
+ try {
12727
+ renameSync(tempPath, filePath);
12728
+ } catch (e) {
12729
+ throw outputWriteError(e, filePath, label);
12730
+ }
12731
+ saved = true;
12732
+ return;
12733
+ }
12734
+ } finally {
12735
+ if (!saved) {
12736
+ try { rmSync(tempPath, { force: true }); } catch { /* best effort */ }
12737
+ }
12738
+ TRACKED_TEMP_FILES.delete(tempPath);
12739
+ }
12740
+ const resultCommand = projectId ? `${resultCommandFor(projectId)}${retryOutput ? ` -o ${shellWord(retryOutput)}` : ''}` : null;
12741
+ const err = new Error(
12742
+ `Could not download the result from ${host}: ${attempts} attempts failed, the last one ${lastFailure.reason}, ` +
12743
+ `with ${formatDownloadProgress(state)} received. ` +
12744
+ (resultCommand
12745
+ ? `The render finished and stays on Sogni; fetch it later with: ${resultCommand}`
12746
+ : 'The render finished and stays on Sogni; find it later with: sogni-agent --recent')
12747
+ );
12748
+ err.code = 'RESULT_DOWNLOAD_FAILED';
12749
+ err.hint = 'Do not render it again. Fetching the result later with --result costs nothing.';
12750
+ err.details = {
12751
+ host,
12752
+ attempts,
12753
+ bytesReceived: state.received,
12754
+ totalBytes: state.total,
12755
+ projectIds: projectId ? [projectId] : [],
12756
+ resultCommands: resultCommand ? [resultCommand] : [],
12757
+ };
12758
+ throw err;
12759
+ }
12760
+
12761
+ /** One GET into tempPath: fresh, or appended from state.received with a Range request. */
12762
+ async function downloadResultAttempt(url, tempPath, state, { stallMs, filePath, label }) {
12763
+ const controller = new AbortController();
12764
+ let silentFor = null;
12765
+ const expireAfter = (ms) => setTimeout(() => { silentFor = ms; controller.abort(); }, ms);
12766
+ // Resume only when If-Range can prove the bytes on disk belong to the same object
12767
+ // (a strong ETag or Last-Modified); without one, start over rather than splice.
12768
+ const resuming = state.received > 0 && state.resumable && Boolean(state.validator);
12769
+ const headers = {};
12770
+ if (resuming) {
12771
+ headers.range = `bytes=${state.received}-`;
12772
+ headers['if-range'] = state.validator;
12773
+ }
12774
+ let timer = expireAfter(DEFAULT_HTTP_TIMEOUT_MS);
12775
+ let fd = null;
12776
+ try {
12777
+ let response;
12778
+ try {
12779
+ response = await fetch(url, { headers, signal: controller.signal });
12780
+ } catch (error) {
12781
+ throw retryableDownloadError(silentFor ? `got no reply for ${formatDownloadDuration(silentFor)}` : downloadConnectionReason(error), error);
12782
+ }
12783
+ clearTimeout(timer);
12784
+ timer = expireAfter(stallMs);
12785
+
12786
+ if (resuming && response.status === 206) {
12787
+ const range = /^bytes (\d+)-\d+\/(\d+|\*)$/i.exec(response.headers.get('content-range') || '');
12788
+ if (!range || Number(range[1]) !== state.received) {
12789
+ state.resumable = false;
12790
+ throw retryableDownloadError('answered the resume with a different byte range');
12791
+ }
12792
+ if (range[2] !== '*') state.total = Number(range[2]);
12793
+ fd = openSync(tempPath, 'a');
12794
+ } else if (resuming && response.status === 416 && state.total !== null && state.received >= state.total) {
12795
+ return;
12796
+ } else if (response.ok && response.status !== 206) {
12797
+ // A full body, also what a server that ignores Range sends: start the file over.
12798
+ const encoded = !['', 'identity'].includes((response.headers.get('content-encoding') || '').toLowerCase());
12799
+ const length = response.headers.get('content-length');
12800
+ state.received = 0;
12801
+ state.total = !encoded && length !== null && Number.isFinite(Number(length)) ? Number(length) : null;
12802
+ state.resumable = !encoded && (response.headers.get('accept-ranges') || '').toLowerCase() !== 'none';
12803
+ const etag = response.headers.get('etag');
12804
+ state.validator = etag && !etag.startsWith('W/') ? etag : response.headers.get('last-modified');
12805
+ fd = openSync(tempPath, 'w');
12806
+ } else if (response.status === 408 || response.status === 416 || response.status >= 500) {
12807
+ if (response.status === 416) state.resumable = false;
12808
+ throw retryableDownloadError(`answered HTTP ${response.status}`);
12809
+ } else {
12810
+ const err = new Error(`Result download failed: HTTP ${response.status}`);
12811
+ let host = null;
12812
+ try { host = new URL(url).host; } catch { /* no host to report */ }
12813
+ // Never the URL itself: result links are presigned and errorDetails is printed.
12814
+ err.details = { host, status: response.status };
12815
+ throw err;
12816
+ }
12817
+
12818
+ if (response.body) {
12819
+ const reader = response.body.getReader();
12820
+ for (;;) {
12821
+ let chunk;
12822
+ try {
12823
+ chunk = await reader.read();
12824
+ } catch (error) {
12825
+ throw retryableDownloadError(silentFor ? `stalled with no data for ${formatDownloadDuration(silentFor)}` : downloadConnectionReason(error), error);
12826
+ }
12827
+ if (chunk.done) break;
12828
+ for (let offset = 0; offset < chunk.value.length;) {
12829
+ offset += writeSync(fd, chunk.value, offset, chunk.value.length - offset);
12830
+ }
12831
+ state.received += chunk.value.length;
12832
+ timer.refresh();
12833
+ }
12834
+ }
12835
+ if (state.total !== null && state.received < state.total) {
12836
+ throw retryableDownloadError('ended early');
12837
+ }
12838
+ } catch (error) {
12839
+ if (error?.downloadRetryable || !error?.syscall) throw error;
12840
+ throw outputWriteError(error, filePath, label);
12841
+ } finally {
12842
+ clearTimeout(timer);
12843
+ controller.abort();
12844
+ if (fd !== null) closeSync(fd);
12619
12845
  }
12620
- const buffer = Buffer.from(await response.arrayBuffer());
12621
- writeOutputFileSafe(filePath, buffer);
12622
12846
  }
12623
12847
 
12624
12848
  function removeClientListener(client, event, handler) {
@@ -14016,7 +14240,7 @@ async function saveProjectResult(result, receipt = null) {
14016
14240
  const path = index === 0
14017
14241
  ? options.output
14018
14242
  : options.output.slice(0, options.output.length - extension.length) + `-${index + 1}` + extension;
14019
- await downloadUrlToFile(url, path);
14243
+ await downloadUrlToFile(url, path, { projectId: summary.projectId, retryOutput: options.output });
14020
14244
  localPaths.push(path);
14021
14245
  }
14022
14246
  }
@@ -14503,7 +14727,7 @@ async function runMultiAngleFlow(client, log) {
14503
14727
  const prefix = outputConfig.prefix ? `${outputConfig.prefix}-` : '';
14504
14728
  const filename = `${prefix}${safeAzimuth}${suffix}.${outputConfig.ext}`;
14505
14729
  const filePath = join(outputConfig.dir, filename);
14506
- await downloadUrlToFile(urls[i], filePath);
14730
+ await downloadUrlToFile(urls[i], filePath, { projectId: results.find((r) => r.resultUrl === urls[i])?.projectId });
14507
14731
  if (options.angles360Video && i === 0) {
14508
14732
  videoFrames.push(filePath);
14509
14733
  }
@@ -14693,7 +14917,7 @@ async function runMultiAngleFlow(client, log) {
14693
14917
  throw new Error('No video URL returned for 360 segment.');
14694
14918
  }
14695
14919
  const clipPath = join(clipDir, `segment-${i + 1}.mp4`);
14696
- await downloadUrlToFile(clipUrl, clipPath);
14920
+ await downloadUrlToFile(clipUrl, clipPath, { projectId: clipResult?.project?.id });
14697
14921
  clipPaths.push(clipPath);
14698
14922
  }
14699
14923
 
@@ -16901,7 +17125,7 @@ async function main() {
16901
17125
  if (options.seed !== null && options.seed !== undefined) {
16902
17126
  projectConfig.seed = options.seed;
16903
17127
  }
16904
- if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3Video)) {
17128
+ if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3Video || isSeedanceVideo)) {
16905
17129
  projectConfig.generateAudio = options.apiGenerateAudio;
16906
17130
  }
16907
17131
  if (isMiniMaxH3TwoStageModel(options.model) && !options.quiet) {
@@ -17554,7 +17778,7 @@ async function main() {
17554
17778
  if (options.videoStart !== null) renderInfo.videoStart = options.videoStart;
17555
17779
  }
17556
17780
  if (options.refVideos.length > 0) renderInfo.refVideos = options.refVideos;
17557
- if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3ModelLocal(options.model))) {
17781
+ if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3ModelLocal(options.model) || isSeedanceModel(options.model))) {
17558
17782
  renderInfo.generateAudio = options.apiGenerateAudio;
17559
17783
  }
17560
17784
  if (options.videoControlNetName && !isSeedanceModel(options.model)) {
@@ -17580,11 +17804,6 @@ async function main() {
17580
17804
 
17581
17805
  // Save to file if requested
17582
17806
  if (options.output && urls[0]) {
17583
- const response = await fetchWithTimeout(urls[0]);
17584
- if (!response.ok) throw new Error(`Result download failed: HTTP ${response.status}`);
17585
- const buffer = Buffer.from(await response.arrayBuffer());
17586
- if (options.imageTo3d) validateGlb(buffer);
17587
-
17588
17807
  const dir = dirname(options.output);
17589
17808
  if (dir && dir !== '.' && !existsSync(dir)) mkdirSync(dir, { recursive: true });
17590
17809
 
@@ -17598,7 +17817,7 @@ async function main() {
17598
17817
  const lastFramePath = join(tempDir, 'last-frame.png');
17599
17818
  const clip2Path = join(tempDir, 'clip2.mp4');
17600
17819
 
17601
- writeFileSync(clip1Path, buffer);
17820
+ await downloadUrlToFile(urls[0], clip1Path, { projectId: firstResult.projectId, label: 'video' });
17602
17821
  log('Extracting last frame...');
17603
17822
  await extractLastFrameFromVideo(clip1Path, lastFramePath);
17604
17823
 
@@ -17667,10 +17886,7 @@ async function main() {
17667
17886
  }
17668
17887
 
17669
17888
  // Download second clip
17670
- const response2 = await fetchWithTimeout(clip2Url);
17671
- if (!response2.ok) throw new Error(`Second clip download failed: HTTP ${response2.status}`);
17672
- const buffer2 = Buffer.from(await response2.arrayBuffer());
17673
- writeFileSync(clip2Path, buffer2);
17889
+ await downloadUrlToFile(clip2Url, clip2Path, { projectId: data.projectId || activeClip2Project?.id, label: 'video' });
17674
17890
 
17675
17891
  await client2.disconnect();
17676
17892
  resolve();
@@ -17713,7 +17929,13 @@ async function main() {
17713
17929
  await buildConcatVideoFromClips(options.output, [clip1Path, clip2Path]);
17714
17930
  log(`Saved looping video to ${options.output}`);
17715
17931
  } else {
17716
- writeOutputFileSafe(options.output, buffer, (options.video || options.upscaleVideo || options.segmentVideo) ? 'video' : (options.music || options.speech) ? 'audio' : options.imageTo3d ? 'model' : 'image');
17932
+ await downloadUrlToFile(urls[0], options.output, {
17933
+ projectId: firstResult.projectId,
17934
+ retryOutput: options.output,
17935
+ label: (options.video || options.upscaleVideo || options.segmentVideo) ? 'video' : (options.music || options.speech) ? 'audio' : options.imageTo3d ? 'model' : 'image',
17936
+ // A refused GLB never replaces the file already at -o.
17937
+ validate: options.imageTo3d ? (path) => validateGlb(readFileSync(path)) : null
17938
+ });
17717
17939
  log(`Saved to ${options.output}`);
17718
17940
  }
17719
17941
  }
@@ -17723,7 +17945,7 @@ async function main() {
17723
17945
  for (let index = 1; index < urls.length; index++) {
17724
17946
  const extension = extname(options.output);
17725
17947
  const path = options.output.slice(0, options.output.length - extension.length) + `-${index + 1}` + extension;
17726
- await downloadUrlToFile(urls[index], path);
17948
+ await downloadUrlToFile(urls[index], path, { projectId: firstResult.projectId, retryOutput: options.output, label: 'audio' });
17727
17949
  localPaths.push(path);
17728
17950
  }
17729
17951
  }
@@ -17735,7 +17957,7 @@ async function main() {
17735
17957
  if (!result.lastFrameUrl) continue;
17736
17958
  const extension = new URL(result.lastFrameUrl).pathname.match(/\.(png|jpe?g|webp)$/i)?.[1] || 'jpg';
17737
17959
  const framePath = options.output.replace(/\.[^/.]+$/, '') + `-last-frame${results.length > 1 ? `-${index + 1}` : ''}.${extension}`;
17738
- await downloadUrlToFile(result.lastFrameUrl, framePath);
17960
+ await downloadUrlToFile(result.lastFrameUrl, framePath, { projectId: result.projectId || firstResult.projectId, label: 'last frame' });
17739
17961
  lastFramePaths.push(framePath);
17740
17962
  log(`Saved last frame to ${framePath}`);
17741
17963
  }
@@ -17842,7 +18064,7 @@ async function main() {
17842
18064
  if (options.videoStart !== null) output.videoStart = options.videoStart;
17843
18065
  }
17844
18066
  if (options.refVideos.length > 0) output.refVideos = options.refVideos;
17845
- if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3ModelLocal(options.model))) {
18067
+ if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3ModelLocal(options.model) || isSeedanceModel(options.model))) {
17846
18068
  output.generateAudio = options.apiGenerateAudio;
17847
18069
  }
17848
18070
  if (options.videoControlNetName && !isSeedanceModel(options.model)) {