@sogni-ai/sogni-creative-agent-skill 3.71.1 → 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.
Files changed (32) hide show
  1. package/.agents/skills/sogni-creative-agent-skill/SKILL.md +1 -1
  2. package/.agents/skills/sogni-creative-agent-skill/references/h3-video-loras.md +3 -3
  3. package/.agents/skills/sogni-creative-agent-skill/references/hosted-api.md +2 -2
  4. package/.agents/skills/sogni-creative-agent-skill/references/image-prompting.md +1 -1
  5. package/.agents/skills/sogni-creative-agent-skill/references/long-jobs-and-queues.md +57 -0
  6. package/.agents/skills/sogni-creative-agent-skill/references/models.md +2 -2
  7. package/.agents/skills/sogni-creative-agent-skill/references/private-mature-video.md +1 -2
  8. package/.agents/skills/sogni-creative-agent-skill/references/video-prompting.md +10 -10
  9. package/.claude-plugin/plugin.json +1 -1
  10. package/.codex-plugin/plugin.json +1 -1
  11. package/CHANGELOG.md +13 -0
  12. package/README.md +8 -5
  13. package/SKILL.md +6 -6
  14. package/desktop-extension/manifest.json +1 -1
  15. package/generated/creative-agent-runtime.mjs +1 -1
  16. package/llm.txt +5 -0
  17. package/openclaw.plugin.json +1 -1
  18. package/package.json +5 -3
  19. package/plugin-skills/sogni-creative-agent/SKILL.md +2 -2
  20. package/progress-events.mjs +186 -0
  21. package/references/h3-video-loras.md +3 -3
  22. package/references/hosted-api.md +2 -2
  23. package/references/image-prompting.md +1 -1
  24. package/references/long-jobs-and-queues.md +57 -0
  25. package/references/models.md +2 -2
  26. package/references/private-mature-video.md +1 -2
  27. package/references/video-prompting.md +10 -10
  28. package/render-accounting.mjs +213 -0
  29. package/skill-package.json +1 -1
  30. package/sogni-agent.mjs +790 -54
  31. package/sogni-app-id.mjs +141 -45
  32. package/version.mjs +1 -1
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';
@@ -30,10 +30,14 @@ import {
30
30
  } from './attribution.mjs';
31
31
  import { assertSafeUrl, fetchSafeUrl } from './ssrf-guard.mjs';
32
32
  import {
33
- MESH_FLAGS, PIXAL3D_VIEW_FLAGS, SPEECH_VALUE_FLAGS, MUSIC3_MODEL_ID, MUSIC3_DEFAULTS, SPEECH_REFERENCE_SECONDS,
33
+ MESH_FLAGS, PIXAL3D_MODEL_ID, PIXAL3D_MULTIVIEW_MODEL_ID, PIXAL3D_VIEW_FLAGS, SPEECH_VALUE_FLAGS, MUSIC3_MODEL_ID, MUSIC3_DEFAULTS, SPEECH_REFERENCE_SECONDS,
34
34
  prepareMediaUtilityOptions, imageUtilityConfig, speechConfig, utilityResultMetadata, validateGlb
35
35
  } from './media-utilities.mjs';
36
36
  import { SAM3_VIDEO_MODEL_ID, videoSegmentationConfig } from './sam-video-segmentation.mjs';
37
+ import {
38
+ QUOTE_UNAVAILABLE, buildQuoteResult, chargeFromProjectRecords, quoteUnavailableError
39
+ } from './render-accounting.mjs';
40
+ import { attachProgressEvents, createProgressEventWriter } from './progress-events.mjs';
37
41
  import { SAM3_MODEL_ID, segmentPoint, segmentBox, validateSegmentationPrompts, segmentationConfig } from './sam-segmentation.mjs';
38
42
  import {
39
43
  INTERNAL_FLAG as UPDATE_CHECK_INTERNAL_FLAG,
@@ -424,6 +428,9 @@ process.on('exit', () => {
424
428
  // normal exit, fatal error, or signal. Ctrl-C during a long video job is the
425
429
  // common case that used to orphan directories under os.tmpdir().
426
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();
427
434
 
428
435
  function createTrackedTempDir(prefix) {
429
436
  const dir = mkdtempSync(join(tmpdir(), prefix));
@@ -432,6 +439,10 @@ function createTrackedTempDir(prefix) {
432
439
  }
433
440
 
434
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
+ }
435
446
  for (const dir of TRACKED_TEMP_DIRS) {
436
447
  try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }
437
448
  TRACKED_TEMP_DIRS.delete(dir);
@@ -857,6 +868,11 @@ function classifyCliError(error, context = {}) {
857
868
  return { error_type: 'PROVIDER_TIMEOUT', category: 'timeout', message: rawMessage, retryable: true };
858
869
  }
859
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
+
860
876
  // Socket 4103: Seedance 2.5 Uncensored, Seedance 2.0 Mini Uncensored, Seedream
861
877
  // 5.0 Pro Uncensored and Seedream 5.5 Uncensored refuse every job until the account accepts their
862
878
  // shared one-time likeness and consent agreement in the Sogni app. The message
@@ -4198,6 +4214,9 @@ const options = {
4198
4214
  targetResolution: null, // Short-side target for video, preserving aspect ratio
4199
4215
  autoResizeVideoAssets: null,
4200
4216
  estimateVideoCost: false,
4217
+ quote: false,
4218
+ receipt: false,
4219
+ progressEvents: false,
4201
4220
  showBalance: false,
4202
4221
  showVersion: false,
4203
4222
  doctor: false,
@@ -5582,6 +5601,12 @@ for (let i = 0; i < args.length; i++) {
5582
5601
  options.quiet = true;
5583
5602
  } else if (arg === '--estimate-video-cost') {
5584
5603
  options.estimateVideoCost = true;
5604
+ } else if (arg === '--quote') {
5605
+ options.quote = true;
5606
+ } else if (arg === '--receipt') {
5607
+ options.receipt = true;
5608
+ } else if (arg === '--progress-events') {
5609
+ options.progressEvents = true;
5585
5610
  } else if (arg === '--balance' || arg === '--balances') {
5586
5611
  options.showBalance = true;
5587
5612
  } else if (arg === '--version' || arg === '-V') {
@@ -5742,7 +5767,7 @@ Video Options:
5742
5767
  --ref-video <path|url> Video reference. Repeatable on Seedance and H3 r2v (up to 3 total);
5743
5768
  first entry is the primary, extras must be HTTPS URLs in CLI
5744
5769
  direct-gen for Seedance. On LTX/WAN: single primary for animate/v2v.
5745
- --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
5746
5771
 
5747
5772
  Seedance Reference Modes (mutually exclusive on seedance2 / seedance2-mini / seedance2-mini-uncensored /
5748
5773
  seedance2-fast / seedance2-5 / seedance2-5-uncensored):
@@ -5842,6 +5867,16 @@ General:
5842
5867
  instead of re-running --status in a loop
5843
5868
  --recent [hours] List this account's completed projects from the last N hours
5844
5869
  (default 24, max 168); fetch one with --result
5870
+ --quote Price this exact request and exit without rendering: Sogni's quote for the
5871
+ settings the render would send, plan coverage, Sogni's time estimate when it
5872
+ has one, and the balance (JSON with --json). Plan coverage is the CLI's
5873
+ reading of the account; Sogni decides again when the render is submitted
5874
+ --receipt Add what Sogni recorded as the charge ("charge") to a finished render's
5875
+ result and to --result; "charge": null with "chargeUnavailable" when the
5876
+ record does not say. One extra read per project after it finishes
5877
+ --progress-events Also write one "SOGNI_EVENT <json>" line to stderr per queue, model-loading,
5878
+ start, progress, time-left and retry event while a render waits or runs,
5879
+ including --result --wait and -q runs
5845
5880
  --steps <num> Override steps (model-dependent)
5846
5881
  --guidance <num> Override guidance (model-dependent)
5847
5882
  --moss-rope-scale-x <num> MOSS horizontal composition scale (0–100; neutral 1)
@@ -6029,9 +6064,11 @@ state negatives in the structured prompt.):
6029
6064
  minimax-h3-t2v-balanced Balanced text-to-video
6030
6065
  minimax-h3-i2v-balanced Balanced I2VA (--ref) or L2VA (--ref-end)
6031
6066
  minimax-h3-flf2v-balanced Balanced first-frame -> last-frame (--ref plus --ref-end)
6032
- minimax-h3-r2v-balanced Balanced Ref2VA with loose image/video/audio references
6033
- minimax-h3-r2v-prism Optional Ref2VA model for mature themes on Balanced's graph: 768p class,
6034
- 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
6035
6072
  minimax-h3-r2v-prism-2stage Prism Two-Stage: the minimax-h3-r2v-prism request, delivered at twice the
6036
6073
  canvas like minimax-h3-r2v-balanced-2stage; requires --no-filter
6037
6074
  minimax-h3-r2v-2stage Ref2VA Two-Stage: the minimax-h3-r2v request (20 steps), delivered at twice the
@@ -7484,6 +7521,53 @@ if (options.detach) {
7484
7521
  }
7485
7522
  }
7486
7523
 
7524
+ // --quote prices the one project a render submits up front, then exits.
7525
+ if (options.quote) {
7526
+ if (options.estimateVideoCost) {
7527
+ fatalCliError('--quote and --estimate-video-cost both price the request; use --quote.', {
7528
+ code: 'INVALID_ARGUMENT',
7529
+ details: { flag: '--quote', conflictsWith: '--estimate-video-cost' }
7530
+ });
7531
+ }
7532
+ const startsNoRender = [
7533
+ ['--status, --result and --recent', options.projectLookup],
7534
+ ['--balance', options.showBalance],
7535
+ ['--version', options.showVersion],
7536
+ ['--doctor', options.doctor],
7537
+ ['model and LoRA listings', apiModelUtilityAction || liveModelUtilityAction || loraCatalogUtilityAction],
7538
+ ['workflow and replay commands', apiWorkflowUtilityAction || apiReplayUtilityAction],
7539
+ ['contract and storyboard-plan commands', contractUtilityAction || storyboardPlanUtilityAction],
7540
+ ['local video tools', options.extractLastFrame || options.extractFirstFrame || options.extractFrameAt
7541
+ || options.trimVideo || options.verifyVideo || options.concatVideos || options.remixAudio],
7542
+ ['--list-media', options.listMedia],
7543
+ ['memory, personality and persona commands', options.memoryAction || options.personalityAction || personaUtilityAction]
7544
+ ].find(([, applies]) => applies);
7545
+ if (startsNoRender) {
7546
+ fatalCliError(`--quote prices a render; ${startsNoRender[0]} start none.`, {
7547
+ code: 'INVALID_ARGUMENT',
7548
+ details: { flag: '--quote', conflictsWith: startsNoRender[0] }
7549
+ });
7550
+ }
7551
+ const unquotable = [
7552
+ ['--looping renders its return clip only after the first clip finishes', options.looping
7553
+ && options.video && options.videoWorkflow === 'i2v' && options.refImage && options.output,
7554
+ 'Quote the clip without --looping; the return clip is a second render with the same settings.'],
7555
+ ['--multi-angle submits one project per angle', options.multiAngle],
7556
+ ['--source-reel submits one render per transition', options.sourceReelDir],
7557
+ ['--api-chat lets the hosted agent choose the renders', options.apiChat],
7558
+ ['a hosted workflow chooses its renders on the server', options.apiWorkflowAction],
7559
+ ['--smart-duration lets Wan 3 choose the length after the quote', options.wan3SmartDuration,
7560
+ 'Pass --duration (and --no-smart-duration) to quote a fixed length.']
7561
+ ].find(([, applies]) => applies);
7562
+ if (unquotable) {
7563
+ fatalCliError(`Sogni has no quote for this request: ${unquotable[0]}.`, {
7564
+ code: QUOTE_UNAVAILABLE,
7565
+ ...(unquotable[2] ? { hint: unquotable[2] } : {}),
7566
+ details: { flag: '--quote' }
7567
+ });
7568
+ }
7569
+ }
7570
+
7487
7571
  if (contractUtilityAction && options.contractAction === 'dispatch' && !options.contractToolName) {
7488
7572
  fatalCliError('--dispatch-tool requires a tool name.', { code: 'INVALID_ARGUMENT' });
7489
7573
  }
@@ -9545,6 +9629,8 @@ async function uploadVendorReferenceMedia(ref, index, apiKey, file) {
9545
9629
  throw err;
9546
9630
  }
9547
9631
  assertVendorReferenceUploadAllowed(ref, file);
9632
+ // --quote prepares and checks the reference like a render, but uploads nothing.
9633
+ if (options.quote) return { url: QUOTE_SKIPPED_UPLOAD_URL };
9548
9634
  return uploadPreparedApiMediaReference(ref, index, apiKey, file);
9549
9635
  }
9550
9636
 
@@ -12509,23 +12595,27 @@ function writeOutputFileSafe(filePath, buffer, label = 'output') {
12509
12595
  if (dir && dir !== '.' && !existsSync(dir)) mkdirSync(dir, { recursive: true });
12510
12596
  writeFileSync(filePath, buffer);
12511
12597
  } catch (e) {
12512
- const code = e?.code;
12513
- const err = new Error(`Could not write ${label} to ${filePath}.`);
12514
- err.code = 'OUTPUT_WRITE_FAILED';
12515
- if (code === 'EACCES' || code === 'EPERM' || code === 'EROFS') {
12516
- err.hint = 'The output path is not writable. Choose a different --output location or fix the directory permissions.';
12517
- } else if (code === 'ENOSPC') {
12518
- err.hint = 'No space left on the device. Free up disk space or choose another --output location.';
12519
- } else if (code === 'ENOENT') {
12520
- err.hint = 'The output directory does not exist and could not be created. Check the --output path.';
12521
- } else if (code === 'EISDIR') {
12522
- err.hint = '--output points to a directory; pass a file path instead.';
12523
- } else {
12524
- err.hint = 'Check the --output path and permissions.';
12525
- }
12526
- err.details = { filePath, cause: code || String(e) };
12527
- 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.';
12528
12616
  }
12617
+ err.details = { filePath, cause: code || String(e) };
12618
+ return err;
12529
12619
  }
12530
12620
 
12531
12621
  // With the Sensitive Content Filter on, the server withholds a flagged result:
@@ -12540,13 +12630,219 @@ function sensitiveContentWithheldError(totalCount = 1) {
12540
12630
  return err;
12541
12631
  }
12542
12632
 
12543
- async function downloadUrlToFile(url, filePath) {
12544
- const response = await fetchWithTimeout(url);
12545
- if (!response.ok) {
12546
- 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);
12547
12845
  }
12548
- const buffer = Buffer.from(await response.arrayBuffer());
12549
- writeOutputFileSafe(filePath, buffer);
12550
12846
  }
12551
12847
 
12552
12848
  function removeClientListener(client, event, handler) {
@@ -13923,12 +14219,12 @@ function printProjectStatus(result) {
13923
14219
  if (summary.finished && done > 0) console.log(`Fetch the media with: ${resultCommandFor(summary.projectId)}`);
13924
14220
  }
13925
14221
 
13926
- /** --result: the project's media, saved to -o like a normal run when given. */
13927
- async function saveProjectResult(result) {
14222
+ /** --result: the project's media, saved to -o like a normal run when given; `receipt` is --receipt's charge. */
14223
+ async function saveProjectResult(result, receipt = null) {
13928
14224
  const summary = projectLookupSummary(result);
13929
14225
  if (!summary.finished) {
13930
14226
  if (options.json) {
13931
- console.log(JSON.stringify({ success: true, ...summary, note: 'Not finished yet; it is still running on Sogni. Check again later; do not resubmit it.' }));
14227
+ console.log(JSON.stringify({ success: true, ...summary, note: 'Not finished yet; it is still running on Sogni. Check again later; do not resubmit it.', ...receipt }));
13932
14228
  } else {
13933
14229
  console.log(`Project ${summary.projectId} is not finished yet (${summary.status}); it is still running on Sogni.`);
13934
14230
  if (summary.message) console.log(summary.message);
@@ -13944,15 +14240,16 @@ async function saveProjectResult(result) {
13944
14240
  const path = index === 0
13945
14241
  ? options.output
13946
14242
  : options.output.slice(0, options.output.length - extension.length) + `-${index + 1}` + extension;
13947
- await downloadUrlToFile(url, path);
14243
+ await downloadUrlToFile(url, path, { projectId: summary.projectId, retryOutput: options.output });
13948
14244
  localPaths.push(path);
13949
14245
  }
13950
14246
  }
13951
14247
  if (options.json) {
13952
- console.log(JSON.stringify({ success: true, ...summary, urls, ...(localPaths.length ? { localPaths } : {}) }));
14248
+ console.log(JSON.stringify({ success: true, ...summary, urls, ...(localPaths.length ? { localPaths } : {}), ...receipt }));
13953
14249
  return;
13954
14250
  }
13955
14251
  console.log(`Project ${summary.projectId}: ${summary.status}`);
14252
+ if (receipt) console.log(describeCharge(receipt));
13956
14253
  if (summary.failure?.message) console.log(`Why it failed: ${summary.failure.message}`);
13957
14254
  if (localPaths.length) {
13958
14255
  for (const path of localPaths) console.log(`Saved to ${path}`);
@@ -13991,6 +14288,7 @@ function printRecentProjects(projects, hours) {
13991
14288
  * it never blocks the run.
13992
14289
  */
13993
14290
  async function warnAboutInFlightProjects(client, log) {
14291
+ if (options.quote) return;
13994
14292
  const projectsApi = sdkClientOf(client)?.projects;
13995
14293
  if (typeof projectsApi?.listProjectsElsewhere !== 'function') return;
13996
14294
  let inFlight;
@@ -14026,8 +14324,16 @@ async function runProjectLookup(client, lookup, { log = () => {}, creds } = {})
14026
14324
  await followProjectToEnd(client, lookup.projectId, { log, creds, timeoutMs });
14027
14325
  }
14028
14326
  const result = await projectsApi.getResult(lookup.projectId);
14029
- if (lookup.action === 'status') printProjectStatus(result);
14030
- else await saveProjectResult(result);
14327
+ if (lookup.action === 'status') {
14328
+ printProjectStatus(result);
14329
+ return;
14330
+ }
14331
+ const receipt = !options.receipt
14332
+ ? null
14333
+ : result.finished
14334
+ ? await readRunCharge(client, [lookup.projectId])
14335
+ : { charge: null, chargeUnavailable: 'The project has not finished.' };
14336
+ await saveProjectResult(result, receipt);
14031
14337
  }
14032
14338
 
14033
14339
  const PROJECT_WAIT_DEFAULT_TIMEOUT_MS = 1800 * 1000;
@@ -14065,8 +14371,10 @@ async function followProjectToEnd(client, projectId, { log, creds, timeoutMs })
14065
14371
  }
14066
14372
  const deadline = Date.now() + timeoutMs;
14067
14373
  let tracked = await trackedProjectAfterSync(projectsApi, projectId);
14374
+ let trackingClient = client;
14068
14375
  let sideClient = null;
14069
14376
  let claim = null;
14377
+ let stopProgressEvents = () => {};
14070
14378
  try {
14071
14379
  if (!tracked) {
14072
14380
  const inFlight = await projectsApi.listProjectsElsewhere();
@@ -14078,6 +14386,7 @@ async function followProjectToEnd(client, projectId, { log, creds, timeoutMs })
14078
14386
  sideClient = createSkillSogniClient(creds, claim.appId);
14079
14387
  await connectSogniClient(sideClient);
14080
14388
  tracked = await trackedProjectAfterSync(sdkClientOf(sideClient).projects, projectId);
14389
+ trackingClient = sideClient;
14081
14390
  }
14082
14391
  if (!tracked) {
14083
14392
  log(claim?.heldByPid
@@ -14087,8 +14396,15 @@ async function followProjectToEnd(client, projectId, { log, creds, timeoutMs })
14087
14396
  return;
14088
14397
  }
14089
14398
  }
14399
+ if (options.progressEvents) {
14400
+ stopProgressEvents = attachProgressEvents(sdkClientOf(trackingClient), {
14401
+ allow: (id) => id === projectId,
14402
+ writer: createSogniEventWriter()
14403
+ });
14404
+ }
14090
14405
  await settleTrackedProject(tracked, { log, deadline, timeoutMs });
14091
14406
  } finally {
14407
+ stopProgressEvents();
14092
14408
  if (sideClient) {
14093
14409
  try { await sideClient.disconnect(); } catch { /* already closed */ }
14094
14410
  }
@@ -14280,6 +14596,7 @@ async function runImageEditProjectWithEvents(client, editConfig, expectedCount,
14280
14596
  const projectResult = await client.createImageEditProject(withBillingMode(editConfig));
14281
14597
  activeProject = projectResult?.project || null;
14282
14598
  projectId = projectResult?.project?.id || projectId;
14599
+ if (projectId) runProjectIds.add(projectId);
14283
14600
 
14284
14601
  // Check for errors in the response (e.g., insufficient tokens)
14285
14602
  if (projectResult?.error || projectResult?.message) {
@@ -14410,7 +14727,7 @@ async function runMultiAngleFlow(client, log) {
14410
14727
  const prefix = outputConfig.prefix ? `${outputConfig.prefix}-` : '';
14411
14728
  const filename = `${prefix}${safeAzimuth}${suffix}.${outputConfig.ext}`;
14412
14729
  const filePath = join(outputConfig.dir, filename);
14413
- await downloadUrlToFile(urls[i], filePath);
14730
+ await downloadUrlToFile(urls[i], filePath, { projectId: results.find((r) => r.resultUrl === urls[i])?.projectId });
14414
14731
  if (options.angles360Video && i === 0) {
14415
14732
  videoFrames.push(filePath);
14416
14733
  }
@@ -14600,7 +14917,7 @@ async function runMultiAngleFlow(client, log) {
14600
14917
  throw new Error('No video URL returned for 360 segment.');
14601
14918
  }
14602
14919
  const clipPath = join(clipDir, `segment-${i + 1}.mp4`);
14603
- await downloadUrlToFile(clipUrl, clipPath);
14920
+ await downloadUrlToFile(clipUrl, clipPath, { projectId: clipResult?.project?.id });
14604
14921
  clipPaths.push(clipPath);
14605
14922
  }
14606
14923
 
@@ -14840,7 +15157,7 @@ function buildMiniMaxH3EstimateUnavailableError(cause) {
14840
15157
  }
14841
15158
 
14842
15159
  async function ensureSufficientVideoBalance(client, log) {
14843
- if (!options.video || options.estimateVideoCost) return;
15160
+ if (!options.video || options.estimateVideoCost || options.quote) return;
14844
15161
  // Wan 3.0 Enhanced launch credits live in the server-side model ledger and
14845
15162
  // cannot be inferred from wallet balance. Let the socket apply credit first,
14846
15163
  // then enforce PAYG balance for any remainder.
@@ -14906,6 +15223,404 @@ async function ensureSufficientVideoBalance(client, log) {
14906
15223
  }
14907
15224
  }
14908
15225
 
15226
+ // ---------------------------------------------------------------------------
15227
+ // --quote: price the config a render was about to submit, then exit.
15228
+ // ---------------------------------------------------------------------------
15229
+
15230
+ // Stands in for a reference upload --quote skips: no price depends on the URL.
15231
+ const QUOTE_SKIPPED_UPLOAD_URL = 'https://quote.invalid/reference-not-uploaded';
15232
+
15233
+ // GPT Image options that change an image quote, as the SDK's estimate names them.
15234
+ const IMAGE_ESTIMATE_PASSTHROUGH = [
15235
+ 'gptImageQuality', 'gptImageFrameCount', 'gptImageFrameDurationMs', 'gptImageComplexity'
15236
+ ];
15237
+ const IMAGE_ESTIMATE_OUTPUT_FORMATS = new Set(['png', 'jpg', 'webp', 'gif']);
15238
+
15239
+ // A refusal of the request itself (400 or 404 from the estimate endpoint, or
15240
+ // the wrapper rejecting the estimate's parameters with a 400 validation error)
15241
+ // means Sogni has no quote for it. Other failures, such as a lost connection
15242
+ // or a rate limit, keep their error.
15243
+ function asQuoteError(err) {
15244
+ if (err?.code === QUOTE_UNAVAILABLE) return err;
15245
+ if (isMiniMaxH3ExtendedDurationEstimateError(err)) {
15246
+ return quoteUnavailableError(buildMiniMaxH3EstimateUnavailableError(err).message, {
15247
+ hint: 'Quote a clip of 10 seconds or less, or render without --quote; Sogni checks the price when the render starts.',
15248
+ cause: err
15249
+ });
15250
+ }
15251
+ const status = err?.status ?? err?.statusCode;
15252
+ if (status === 400 || status === 404) {
15253
+ return quoteUnavailableError(`Sogni has no quote for this request: ${cliErrorMessage(err)}`, { cause: err });
15254
+ }
15255
+ return err;
15256
+ }
15257
+
15258
+ async function modelOptionsFor(client, modelId) {
15259
+ const projectsApi = sdkClientOf(client)?.projects;
15260
+ if (typeof projectsApi?.getModelOptions !== 'function') return null;
15261
+ try {
15262
+ return await projectsApi.getModelOptions(modelId);
15263
+ } catch {
15264
+ // Without the tier, its default steps are unknown and the caller refuses the quote.
15265
+ return null;
15266
+ }
15267
+ }
15268
+
15269
+ // The steps Sogni prices a project at: the request's own, else the tier default.
15270
+ async function pricedSteps(client, modelId, requested) {
15271
+ if (Number.isFinite(requested) && requested > 0) return requested;
15272
+ const fallback = (await modelOptionsFor(client, modelId))?.steps?.default;
15273
+ return Number.isFinite(fallback) && fallback > 0 ? fallback : null;
15274
+ }
15275
+
15276
+ // Runs `run` while recording the parameters the wrapper hands to the SDK's
15277
+ // `method`, so a quote reports the values it was priced on.
15278
+ async function withRecordedSdkCall(target, method, run) {
15279
+ const original = target?.[method];
15280
+ if (typeof original !== 'function') return { result: await run(), recorded: null };
15281
+ let recorded = null;
15282
+ target[method] = function recordQuoteParams(params, ...rest) {
15283
+ recorded = params;
15284
+ return original.call(this, params, ...rest);
15285
+ };
15286
+ try {
15287
+ return { result: await run(), recorded };
15288
+ } finally {
15289
+ target[method] = original;
15290
+ }
15291
+ }
15292
+
15293
+ async function quoteVideoConfig(client, config) {
15294
+ const tokenType = config.tokenType || 'spark';
15295
+ const projectsApi = sdkClientOf(client)?.projects;
15296
+ if (options.upscaleVideo || options.segmentVideo) {
15297
+ const source = options._videoUpscale?.source;
15298
+ const params = {
15299
+ model: config.modelId,
15300
+ tokenType,
15301
+ width: options.width,
15302
+ height: options.height,
15303
+ frames: options.frames,
15304
+ fps: options.fps,
15305
+ numberOfMedia: 1,
15306
+ network: config.network,
15307
+ ...(config.billingMode ? { billingMode: config.billingMode } : {}),
15308
+ ...(source ? { sourceWidth: source.width, sourceHeight: source.height } : {}),
15309
+ ...(config.sam3VideoPrompt ? { sam3VideoPrompt: config.sam3VideoPrompt } : {})
15310
+ };
15311
+ if (typeof projectsApi?.estimateVideoCost !== 'function') {
15312
+ throw quoteUnavailableError('This Sogni SDK cannot quote video upscaling or video selection.');
15313
+ }
15314
+ return {
15315
+ estimate: await projectsApi.estimateVideoCost(params),
15316
+ settings: {
15317
+ width: params.width,
15318
+ height: params.height,
15319
+ fps: params.fps,
15320
+ frames: params.frames,
15321
+ duration: params.frames / params.fps,
15322
+ count: 1,
15323
+ ...(source ? { sourceWidth: source.width, sourceHeight: source.height } : {}),
15324
+ ...(options._videoUpscale?.resolution ? { resolution: options._videoUpscale.resolution } : {})
15325
+ }
15326
+ };
15327
+ }
15328
+
15329
+ const modelDefaults = getModelDefaults(options.model, openclawConfig);
15330
+ const steps = resolveVideoSteps(options.model, modelDefaults, options.steps);
15331
+ const isStepFreeVendorVideo = isSeedanceModel(options.model)
15332
+ || isHappyHorseModel(options.model)
15333
+ || isWan3ModelLocal(options.model);
15334
+ if (!isStepFreeVendorVideo && (!Number.isFinite(steps) || steps <= 0)) {
15335
+ const err = new Error('--quote needs --steps for this video model (it has no default).');
15336
+ err.code = 'MISSING_STEPS';
15337
+ err.hint = 'Pass --steps explicitly (e.g. --steps 4 for lightx2v models).';
15338
+ throw err;
15339
+ }
15340
+ const params = await buildVideoEstimateParams({ tokenType, steps });
15341
+ // The wrapper fits the canvas to its model grid and reference shape before
15342
+ // the SDK sends the project, so the quote uses the size it would send.
15343
+ if (typeof client.prepareProjectConfig === 'function') {
15344
+ const prepared = await client.prepareProjectConfig({ ...config, type: 'video' });
15345
+ if (prepared?.width && prepared?.height) {
15346
+ params.width = prepared.width;
15347
+ params.height = prepared.height;
15348
+ }
15349
+ }
15350
+ if (config.billingMode) params.billingMode = config.billingMode;
15351
+ const { result: estimate, recorded } = await withRecordedSdkCall(
15352
+ projectsApi,
15353
+ 'estimateVideoCost',
15354
+ () => client.estimateVideoCost(params)
15355
+ );
15356
+ const fps = recorded?.fps ?? params.fps;
15357
+ const frames = recorded?.frames ?? params.frames ?? null;
15358
+ const delivered = isMiniMaxH3TwoStageModel(options.model)
15359
+ ? minimaxH3TwoStageDeliveredSize(params.width, params.height)
15360
+ : null;
15361
+ const settings = options.seedanceFinalize !== null
15362
+ ? {
15363
+ // A finalize is priced from its draft's ratio and length.
15364
+ seedanceDraftJobId: options.seedanceFinalize,
15365
+ ...seedanceFinalResolutionOptions(),
15366
+ count: params.numberOfMedia
15367
+ }
15368
+ : {
15369
+ width: params.width,
15370
+ height: params.height,
15371
+ ...(delivered ? { deliveredWidth: delivered.width, deliveredHeight: delivered.height } : {}),
15372
+ fps,
15373
+ frames,
15374
+ // The clip's length, as a render's result reports it.
15375
+ duration: options.frames ? options.frames / options.fps : options.duration,
15376
+ ...(Number.isFinite(params.steps) ? { steps: params.steps } : {}),
15377
+ count: params.numberOfMedia,
15378
+ ...(params.keyframeCount ? { keyframeCount: params.keyframeCount } : {}),
15379
+ ...(params.referenceImageCount !== undefined ? { referenceImageCount: params.referenceImageCount } : {}),
15380
+ ...(params.referenceVideoCount ? { referenceVideoCount: params.referenceVideoCount } : {}),
15381
+ ...(params.seedanceDraft ? { seedanceDraft: true } : {})
15382
+ };
15383
+ return { estimate, settings };
15384
+ }
15385
+
15386
+ async function quoteAudioConfig(client, config) {
15387
+ const tokenType = config.tokenType || 'spark';
15388
+ if (config.network === 'relaxed') {
15389
+ // Sogni quotes music and speech at Fast prices only.
15390
+ throw quoteUnavailableError('Sogni quotes music and speech on the Fast network only.', {
15391
+ hint: 'Quote with --network fast, or render on Relaxed without --quote.'
15392
+ });
15393
+ }
15394
+ const steps = await pricedSteps(client, config.modelId, config.steps);
15395
+ if (!steps) {
15396
+ throw quoteUnavailableError(`Sogni has no quote for ${config.modelId}: its default step count is unknown.`);
15397
+ }
15398
+ const count = config.numberOfMedia || 1;
15399
+ if (options.speech) {
15400
+ // Speech is priced per character of script. The SDK's audio estimate has
15401
+ // no field for the script length, so the socket's estimate route is read
15402
+ // directly with the same parameters the SDK sends.
15403
+ const socket = sdkClientOf(client)?.apiClient?.socket;
15404
+ if (typeof socket?.get !== 'function') throw quoteUnavailableError('This Sogni SDK cannot quote speech.');
15405
+ const characters = String(config.positivePrompt || '').length;
15406
+ const path = '/api/v1/job-audio/estimate/'
15407
+ + [tokenType, config.modelId, 30, steps, count].map((part) => encodeURIComponent(part)).join('/');
15408
+ const response = await socket.get(path, {
15409
+ characters,
15410
+ ...(config.network ? { network: config.network } : {}),
15411
+ ...(config.billingMode ? { billingMode: config.billingMode } : {})
15412
+ });
15413
+ const project = response?.quote?.project;
15414
+ if (!project) throw quoteUnavailableError('Sogni returned no price for this speech request.');
15415
+ return {
15416
+ estimate: {
15417
+ spark: project.costInSpark,
15418
+ sogni: project.costInSogni,
15419
+ usd: project.costInUSD,
15420
+ estimatedRenderSeconds: response.benchmark?.estimatedRenderTimeSec,
15421
+ estimatedTotalSeconds: response.benchmark?.estimatedTotalTimeSec,
15422
+ dailyFairUsePct: response.dailyFairUse?.pct
15423
+ },
15424
+ settings: { characters, count }
15425
+ };
15426
+ }
15427
+ const estimate = await client.estimateAudioCost({
15428
+ modelId: config.modelId,
15429
+ duration: config.duration,
15430
+ steps,
15431
+ numberOfMedia: count,
15432
+ tokenType,
15433
+ ...(config.network ? { network: config.network } : {}),
15434
+ ...(config.billingMode ? { billingMode: config.billingMode } : {}),
15435
+ ...(config.priorityMode !== undefined ? { priorityMode: config.priorityMode } : {})
15436
+ });
15437
+ return { estimate, settings: { duration: config.duration, steps, count } };
15438
+ }
15439
+
15440
+ async function quoteImageConfig(client, config) {
15441
+ const tokenType = config.tokenType || 'spark';
15442
+ const projectsApi = sdkClientOf(client)?.projects;
15443
+ if (typeof projectsApi?.estimateCost !== 'function') throw quoteUnavailableError('This Sogni SDK cannot quote images.');
15444
+ const modelId = config.modelId;
15445
+ const pixal3d = modelId === PIXAL3D_MODEL_ID || modelId === PIXAL3D_MULTIVIEW_MODEL_ID;
15446
+ if (pixal3d && config.shapeResolution !== undefined && config.shapeResolution !== 1024) {
15447
+ throw quoteUnavailableError('Sogni\'s image quote in this SDK prices Pixal3D at its default shape resolution only.', {
15448
+ hint: 'Quote without --shape-resolution, or render without --quote.'
15449
+ });
15450
+ }
15451
+ const segmentation = modelId === SAM3_MODEL_ID;
15452
+ const steps = await pricedSteps(client, modelId, config.steps);
15453
+ if (!steps) throw quoteUnavailableError(`Sogni has no quote for ${modelId}: its default step count is unknown.`);
15454
+ let { width, height } = config;
15455
+ // Sogni renders an InstantID face transfer requested at 1024x1024 at 1016x1016.
15456
+ if (config.controlNet?.name === 'instantid' && width === 1024 && height === 1024) {
15457
+ width = 1016;
15458
+ height = 1016;
15459
+ }
15460
+ const contextImages = Array.isArray(config.contextImages) ? config.contextImages.length : 0;
15461
+ const outputFormat = IMAGE_ESTIMATE_OUTPUT_FORMATS.has(config.outputFormat) ? config.outputFormat : undefined;
15462
+ const params = {
15463
+ network: config.network,
15464
+ tokenType,
15465
+ model: modelId,
15466
+ // Segmentation always renders one mask; utilities render no previews.
15467
+ imageCount: segmentation ? 1 : (config.numberOfMedia || 1),
15468
+ stepCount: steps,
15469
+ previewCount: segmentation || pixal3d ? 0 : (config.numberOfPreviews || 0),
15470
+ cnEnabled: Boolean(config.controlNet),
15471
+ ...(config.startingImage ? { startingImageStrength: config.startingImageStrength ?? 0.5 } : {}),
15472
+ ...(config.sizePreset && config.sizePreset !== 'custom'
15473
+ ? { sizePreset: config.sizePreset }
15474
+ : (width && height ? { width, height } : {})),
15475
+ ...(config.sampler ? { sampler: config.sampler } : {}),
15476
+ ...(config.guidance !== undefined ? { guidance: config.guidance } : {}),
15477
+ contextImages,
15478
+ ...(outputFormat ? { outputFormat } : {}),
15479
+ ...(config.billingMode ? { billingMode: config.billingMode } : {}),
15480
+ ...(config.priorityMode !== undefined ? { priorityMode: config.priorityMode } : {})
15481
+ };
15482
+ for (const key of IMAGE_ESTIMATE_PASSTHROUGH) {
15483
+ if (config[key] !== undefined) params[key] = config[key];
15484
+ }
15485
+ // A cutout is the source's size, which the config does not carry.
15486
+ const outputSize = width && height
15487
+ ? { width, height }
15488
+ : (options.removeBackground ? { width: options.width, height: options.height } : {});
15489
+ return {
15490
+ estimate: await projectsApi.estimateCost(params),
15491
+ settings: {
15492
+ ...outputSize,
15493
+ count: params.imageCount,
15494
+ steps,
15495
+ ...(contextImages ? { referenceImages: contextImages } : {}),
15496
+ ...(outputFormat ? { outputFormat } : {}),
15497
+ ...(params.gptImageQuality ? { quality: params.gptImageQuality } : {}),
15498
+ ...(params.gptImageFrameCount !== undefined ? { frameCount: params.gptImageFrameCount } : {})
15499
+ }
15500
+ };
15501
+ }
15502
+
15503
+ function quoteMedia(projectType) {
15504
+ if (projectType === 'video' || projectType === 'audio') return projectType;
15505
+ return options.imageTo3d ? 'model' : 'image';
15506
+ }
15507
+
15508
+ async function quoteProjectConfig(client, projectType, config) {
15509
+ let quoted;
15510
+ try {
15511
+ quoted = projectType === 'video'
15512
+ ? await quoteVideoConfig(client, config)
15513
+ : projectType === 'audio'
15514
+ ? await quoteAudioConfig(client, config)
15515
+ : await quoteImageConfig(client, config);
15516
+ } catch (err) {
15517
+ throw asQuoteError(err);
15518
+ }
15519
+ const subscription = await fetchSubscriptionSnapshot(client, null);
15520
+ let balance = null;
15521
+ try {
15522
+ balance = await client.getBalance();
15523
+ } catch { /* the balance is best effort; the quote stands without it */ }
15524
+ return buildQuoteResult({
15525
+ media: quoteMedia(projectType),
15526
+ model: config.modelId,
15527
+ network: config.network,
15528
+ tokenType: config.tokenType || 'spark',
15529
+ settings: quoted.settings,
15530
+ estimate: quoted.estimate,
15531
+ partnerModel: requiresSparkOnlyToken(config.modelId),
15532
+ subscription,
15533
+ balance,
15534
+ billingMode: config.billingMode
15535
+ });
15536
+ }
15537
+
15538
+ function formatQuoteAmount(price) {
15539
+ const parts = [];
15540
+ if (price.spark !== undefined) parts.push(`${formatTokenValue(price.spark)} Spark`);
15541
+ if (price.sogni !== undefined) parts.push(`${formatTokenValue(price.sogni)} SOGNI`);
15542
+ if (price.usd !== undefined) parts.push(`$${price.usd}`);
15543
+ return parts.join(' / ') || 'unknown';
15544
+ }
15545
+
15546
+ function printQuote(quote) {
15547
+ if (options.json) {
15548
+ console.log(JSON.stringify(quote));
15549
+ return;
15550
+ }
15551
+ console.log(`Price: ${formatQuoteAmount(quote.price)} (${quote.model}, ${quote.network})`);
15552
+ if (quote.memberPrice) {
15553
+ console.log(`Member price: ${formatQuoteAmount(quote.memberPrice)} (${quote.memberPrice.discountBps / 100}% off)`);
15554
+ }
15555
+ console.log(`Plan: ${quote.planCovered ? 'covers this render' : 'does not cover this render'}`);
15556
+ if (quote.time?.totalSeconds !== undefined || quote.time?.renderSeconds !== undefined) {
15557
+ console.log(`Time: ${quote.time.totalSeconds ?? quote.time.renderSeconds}s`
15558
+ + (quote.time.renderSeconds !== undefined ? ` (render ${quote.time.renderSeconds}s)` : ''));
15559
+ }
15560
+ if (quote.balance) {
15561
+ console.log(`Balance: ${formatTokenValue(quote.balance.spark)} Spark, ${formatTokenValue(quote.balance.sogni)} SOGNI`);
15562
+ }
15563
+ }
15564
+
15565
+ /**
15566
+ * --quote: each create call prices the config it receives, prints the quote
15567
+ * and ends the run, so the quote covers exactly what the render would submit.
15568
+ * Nothing is submitted and no render state is written.
15569
+ */
15570
+ function installQuoteInterceptor(client) {
15571
+ for (const [method, projectType] of [
15572
+ ['createImageProject', 'image'],
15573
+ ['createImageEditProject', 'image'],
15574
+ ['createVideoProject', 'video'],
15575
+ ['createAudioProject', 'audio']
15576
+ ]) {
15577
+ client[method] = async (config) => {
15578
+ printQuote(await quoteProjectConfig(client, projectType, config));
15579
+ try {
15580
+ await Promise.race([client.disconnect(), new Promise((resolve) => setTimeout(resolve, 1000))]);
15581
+ } catch { /* exiting either way */ }
15582
+ await flushStdout();
15583
+ process.exit(0);
15584
+ };
15585
+ }
15586
+ }
15587
+
15588
+ // ---------------------------------------------------------------------------
15589
+ // --receipt: the charge Sogni recorded for this run's projects.
15590
+ // ---------------------------------------------------------------------------
15591
+
15592
+ async function readRunCharge(client, projectIds) {
15593
+ const projectsApi = sdkClientOf(client)?.projects;
15594
+ if (typeof projectsApi?.getStatus !== 'function') {
15595
+ return { charge: null, chargeUnavailable: 'This Sogni SDK cannot read project records.' };
15596
+ }
15597
+ const records = [];
15598
+ try {
15599
+ for (const projectId of projectIds) records.push(await projectsApi.getStatus(projectId));
15600
+ } catch (err) {
15601
+ const reason = String(cliErrorMessage(err) || 'error').slice(0, 200);
15602
+ return { charge: null, chargeUnavailable: `Sogni's project record could not be read (${reason}).` };
15603
+ }
15604
+ return chargeFromProjectRecords(records);
15605
+ }
15606
+
15607
+ function describeCharge(receipt) {
15608
+ if (!receipt.charge) return `Charge unavailable: ${receipt.chargeUnavailable}`;
15609
+ const { paidBy, amount, value } = receipt.charge;
15610
+ const worth = value ? `; value ${formatQuoteAmount(value)}` : '';
15611
+ if (paidBy === 'plan') return `Charge: covered by your plan${worth}`;
15612
+ if (paidBy === 'credit') return `Charge: covered by promotional credit${worth}`;
15613
+ const paid = paidBy === 'sogni' ? `${formatTokenValue(amount.sogni)} SOGNI` : `${formatTokenValue(amount.spark)} Spark`;
15614
+ return `Charge: ${paid} ($${amount.usd})`;
15615
+ }
15616
+
15617
+ // --progress-events: projects this run submitted, whose events it reports.
15618
+ const runProjectIds = new Set();
15619
+
15620
+ function createSogniEventWriter() {
15621
+ return createProgressEventWriter({ write: (line) => process.stderr.write(line) });
15622
+ }
15623
+
14909
15624
  // ---------------------------------------------------------------------------
14910
15625
  // Token auto-fallback: resolve 'auto' to 'spark', retry with 'sogni' on
14911
15626
  // insufficient balance errors for native Sogni models. External API-backed
@@ -15724,6 +16439,14 @@ async function main() {
15724
16439
  return;
15725
16440
  }
15726
16441
 
16442
+ if (options.quote) installQuoteInterceptor(client);
16443
+ if (options.progressEvents && !options.quote) {
16444
+ attachProgressEvents(sdkClientOf(client), {
16445
+ allow: (projectId) => runProjectIds.has(projectId),
16446
+ writer: createSogniEventWriter()
16447
+ });
16448
+ }
16449
+
15727
16450
  if (options.multiAngle) {
15728
16451
  if (options.contextImages.length > 1 && !options.quiet) {
15729
16452
  console.error('Warning: --multi-angle uses the first context image only.');
@@ -15736,9 +16459,12 @@ async function main() {
15736
16459
  let completedJobs = 0;
15737
16460
  let loopingStartImageBuffer;
15738
16461
  const activeProjects = new Set();
16462
+ // Projects submitted after the first finished (the looping return clip).
16463
+ const laterProjectIds = [];
15739
16464
  const projectWait = createProjectWaitTracker(client, log);
15740
16465
  const trackProjectResult = (projectResult) => {
15741
16466
  if (projectResult?.project) {
16467
+ if (projectResult.project.id) runProjectIds.add(projectResult.project.id);
15742
16468
  activeProjects.add(projectResult.project);
15743
16469
  projectWait.track(projectResult.project);
15744
16470
  }
@@ -16399,7 +17125,7 @@ async function main() {
16399
17125
  if (options.seed !== null && options.seed !== undefined) {
16400
17126
  projectConfig.seed = options.seed;
16401
17127
  }
16402
- if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3Video)) {
17128
+ if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3Video || isSeedanceVideo)) {
16403
17129
  projectConfig.generateAudio = options.apiGenerateAudio;
16404
17130
  }
16405
17131
  if (isMiniMaxH3TwoStageModel(options.model) && !options.quiet) {
@@ -16860,6 +17586,11 @@ async function main() {
16860
17586
  : null;
16861
17587
 
16862
17588
  const useVariations = options.count > 1 && hasPromptVariations(options.prompt);
17589
+ if (useVariations && options.quote) {
17590
+ throw quoteUnavailableError('Sogni has no quote for this request: a prompt with variations submits one project per variation.', {
17591
+ hint: 'Quote one variation with --count 1.'
17592
+ });
17593
+ }
16863
17594
  const variationCount = useVariations ? options.count : 1;
16864
17595
  const imagesPerCall = useVariations ? 1 : options.count;
16865
17596
 
@@ -17047,7 +17778,7 @@ async function main() {
17047
17778
  if (options.videoStart !== null) renderInfo.videoStart = options.videoStart;
17048
17779
  }
17049
17780
  if (options.refVideos.length > 0) renderInfo.refVideos = options.refVideos;
17050
- if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3ModelLocal(options.model))) {
17781
+ if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3ModelLocal(options.model) || isSeedanceModel(options.model))) {
17051
17782
  renderInfo.generateAudio = options.apiGenerateAudio;
17052
17783
  }
17053
17784
  if (options.videoControlNetName && !isSeedanceModel(options.model)) {
@@ -17073,11 +17804,6 @@ async function main() {
17073
17804
 
17074
17805
  // Save to file if requested
17075
17806
  if (options.output && urls[0]) {
17076
- const response = await fetchWithTimeout(urls[0]);
17077
- if (!response.ok) throw new Error(`Result download failed: HTTP ${response.status}`);
17078
- const buffer = Buffer.from(await response.arrayBuffer());
17079
- if (options.imageTo3d) validateGlb(buffer);
17080
-
17081
17807
  const dir = dirname(options.output);
17082
17808
  if (dir && dir !== '.' && !existsSync(dir)) mkdirSync(dir, { recursive: true });
17083
17809
 
@@ -17091,7 +17817,7 @@ async function main() {
17091
17817
  const lastFramePath = join(tempDir, 'last-frame.png');
17092
17818
  const clip2Path = join(tempDir, 'clip2.mp4');
17093
17819
 
17094
- writeFileSync(clip1Path, buffer);
17820
+ await downloadUrlToFile(urls[0], clip1Path, { projectId: firstResult.projectId, label: 'video' });
17095
17821
  log('Extracting last frame...');
17096
17822
  await extractLastFrameFromVideo(clip1Path, lastFramePath);
17097
17823
 
@@ -17160,10 +17886,7 @@ async function main() {
17160
17886
  }
17161
17887
 
17162
17888
  // Download second clip
17163
- const response2 = await fetchWithTimeout(clip2Url);
17164
- if (!response2.ok) throw new Error(`Second clip download failed: HTTP ${response2.status}`);
17165
- const buffer2 = Buffer.from(await response2.arrayBuffer());
17166
- writeFileSync(clip2Path, buffer2);
17889
+ await downloadUrlToFile(clip2Url, clip2Path, { projectId: data.projectId || activeClip2Project?.id, label: 'video' });
17167
17890
 
17168
17891
  await client2.disconnect();
17169
17892
  resolve();
@@ -17193,6 +17916,7 @@ async function main() {
17193
17916
 
17194
17917
  const clip2Result = await client2.createVideoProject(withBillingMode(projectConfig2));
17195
17918
  activeClip2Project = clip2Result?.project || null;
17919
+ if (activeClip2Project?.id) laterProjectIds.push(activeClip2Project.id);
17196
17920
 
17197
17921
  // Check for errors in the response (e.g., insufficient tokens)
17198
17922
  if (clip2Result?.error || clip2Result?.message) {
@@ -17205,7 +17929,13 @@ async function main() {
17205
17929
  await buildConcatVideoFromClips(options.output, [clip1Path, clip2Path]);
17206
17930
  log(`Saved looping video to ${options.output}`);
17207
17931
  } else {
17208
- 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
+ });
17209
17939
  log(`Saved to ${options.output}`);
17210
17940
  }
17211
17941
  }
@@ -17215,7 +17945,7 @@ async function main() {
17215
17945
  for (let index = 1; index < urls.length; index++) {
17216
17946
  const extension = extname(options.output);
17217
17947
  const path = options.output.slice(0, options.output.length - extension.length) + `-${index + 1}` + extension;
17218
- await downloadUrlToFile(urls[index], path);
17948
+ await downloadUrlToFile(urls[index], path, { projectId: firstResult.projectId, retryOutput: options.output, label: 'audio' });
17219
17949
  localPaths.push(path);
17220
17950
  }
17221
17951
  }
@@ -17227,12 +17957,16 @@ async function main() {
17227
17957
  if (!result.lastFrameUrl) continue;
17228
17958
  const extension = new URL(result.lastFrameUrl).pathname.match(/\.(png|jpe?g|webp)$/i)?.[1] || 'jpg';
17229
17959
  const framePath = options.output.replace(/\.[^/.]+$/, '') + `-last-frame${results.length > 1 ? `-${index + 1}` : ''}.${extension}`;
17230
- await downloadUrlToFile(result.lastFrameUrl, framePath);
17960
+ await downloadUrlToFile(result.lastFrameUrl, framePath, { projectId: result.projectId || firstResult.projectId, label: 'last frame' });
17231
17961
  lastFramePaths.push(framePath);
17232
17962
  log(`Saved last frame to ${framePath}`);
17233
17963
  }
17234
17964
  }
17235
17965
 
17966
+ const receipt = options.receipt
17967
+ ? await readRunCharge(client, [...new Set([...activeProjects].map((project) => project?.id).concat(laterProjectIds).filter(Boolean))])
17968
+ : null;
17969
+
17236
17970
  // Output result
17237
17971
  if (options.json) {
17238
17972
  const output = {
@@ -17330,7 +18064,7 @@ async function main() {
17330
18064
  if (options.videoStart !== null) output.videoStart = options.videoStart;
17331
18065
  }
17332
18066
  if (options.refVideos.length > 0) output.refVideos = options.refVideos;
17333
- if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3ModelLocal(options.model))) {
18067
+ if (options.apiGenerateAudio !== null && (isMiniMaxH3Model(options.model) || isWan3ModelLocal(options.model) || isSeedanceModel(options.model))) {
17334
18068
  output.generateAudio = options.apiGenerateAudio;
17335
18069
  }
17336
18070
  if (options.videoControlNetName && !isSeedanceModel(options.model)) {
@@ -17375,9 +18109,11 @@ async function main() {
17375
18109
  output.duration = null;
17376
18110
  Object.assign(output, seedanceFinalResolutionOptions());
17377
18111
  }
18112
+ if (receipt) Object.assign(output, receipt);
17378
18113
  console.log(JSON.stringify(output));
17379
18114
  } else {
17380
18115
  urls.forEach(url => console.log(url));
18116
+ if (receipt) console.log(describeCharge(receipt));
17381
18117
  if (withheldCount > 0) console.log(`${withheldCount} of ${results.length} results withheld by the Sensitive Content Filter`);
17382
18118
  if (options.returnLastFrame) {
17383
18119
  results.forEach(result => { if (result.lastFrameUrl) console.log(`Last frame: ${result.lastFrameUrl}`); });