nanoodle 0.11.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/estimate.mjs CHANGED
@@ -43,7 +43,7 @@ function pricedModelId(node) {
43
43
  // that cannot happen. It contributes $0 and is not counted as `unpriced`,
44
44
  // because "we could not price it" is the wrong report — it is not billable.
45
45
  const PRICE_KIND = {
46
- llm: "chat", vision: "chat", decide: "chat",
46
+ llm: "chat", vision: "chat", decide: "decision", "decide-branch": "decision",
47
47
  image: "image", edit: "image", inpaint: "image",
48
48
  tvideo: "video", ivideo: "video", vedit: "video", lipsync: "video",
49
49
  music: "audio", remix: "audio", tts: "audio", transcribe: "audio", cleanvoice: "audio",
@@ -72,7 +72,7 @@ function pickObjByRes(map, reqRes, defRes) {
72
72
  function pickDur(p, raw, fields) {
73
73
  const f = parseFloat(fields && fields.duration);
74
74
  if (isFinite(f) && f > 0) return f;
75
- const d = _num(p.default_duration) ?? _num(raw.defaultDuration);
75
+ const d = _num(p.default_duration ?? p.default_duration_seconds) ?? _num(raw.defaultDuration);
76
76
  if (d != null && d > 0) return d;
77
77
  if (p.per_duration) { const k = Object.keys(p.per_duration)[0]; if (k && isFinite(+k)) return +k; }
78
78
  if (Array.isArray(p.supported_durations) && p.supported_durations.length) return +p.supported_durations[0];
@@ -80,6 +80,38 @@ function pickDur(p, raw, fields) {
80
80
  return 5;
81
81
  }
82
82
 
83
+ // Catalog billing is model-specific: a per-second rate alone does not imply
84
+ // started-second billing. Recognize quantity contracts, never vendor families or
85
+ // reference-input notes. Unknown contracts retain a fractional, inexact forecast.
86
+ const WHOLE_SECOND_BILLING = new Set([
87
+ "duration rounded up to whole seconds, then clamped to the minimum and maximum billable duration",
88
+ "verified source-video duration, rounded up to whole seconds",
89
+ "verified source-video duration, rounded up to whole seconds and clamped to the minimum and maximum billable duration",
90
+ "verified source-video duration, rounded up to whole seconds; longer videos are trimmed to 10 minutes",
91
+ "per generated second (source length rounded up to whole seconds), multiplied by num_samples",
92
+ ]);
93
+ const FRAME_LIMIT_BILLING = "rate × ceil(min(measured source seconds, (frame limit − 2) / fps)); 60 fps doubles the rate; turbo has no surcharge";
94
+ const billingRule = (p) => String(p.billing || "").trim().toLowerCase();
95
+ const clampSeconds = (seconds, lo, hi) => Math.min(_num(hi) ?? seconds, Math.max(_num(lo) ?? seconds, seconds));
96
+ function perSecondQuantity(pricing, seconds) {
97
+ const p = pricing || {};
98
+ return (p.unit === "per_verified_source_second_plus_image" || WHOLE_SECOND_BILLING.has(billingRule(p)))
99
+ ? clampSeconds(Math.ceil(seconds), p.minimum_billable_duration, p.maximum_billable_duration)
100
+ : seconds;
101
+ }
102
+ function frameLimitedBilling(pricing, fields, seconds) {
103
+ const p = pricing || {}, f = fields || {}, opts = f.modelOpts || {};
104
+ if (billingRule(p) !== FRAME_LIMIT_BILLING) return null;
105
+ // This FPS is the requested output setting, not an inferred source-frame rate.
106
+ const fps = _num(opts.fps ?? p.default_fps);
107
+ const res = opts.target_resolution ?? opts.resolution ?? f.resolution;
108
+ const frames = pickByRes(p.frame_limits_by_resolution, res, p.default_resolution);
109
+ if (!(fps > 0) || !(frames > 2) || (Array.isArray(p.supported_fps) && !p.supported_fps.some((x) => _num(x) === fps))) return null;
110
+ const multiplier = fps === 60 ? _num(p.high_fps_multiplier) : 1;
111
+ if (!(multiplier > 0)) return null;
112
+ return { seconds: Math.ceil(Math.min(seconds, (frames - 2) / fps)), multiplier, resolution: res };
113
+ }
114
+
83
115
  // A LoRA row counts only once it carries a URL. loraParams sends nothing for a
84
116
  // blank row, so a blank row must not flip the estimate onto the LoRA tier.
85
117
  function videoLoraOn(fields) {
@@ -116,6 +148,23 @@ function videoAudioOn(fields, audioCtx) {
116
148
  return false;
117
149
  }
118
150
 
151
+ // Source-video billing is distinct from a requested output duration. Never use
152
+ // maximum_seconds (an input limit) or the node's legacy five-second default as money.
153
+ function inputVideoPriceFields(pricing, fields, source, measuredSeconds) {
154
+ if (!pricing || pricing.unit !== "input_video_second") return fields;
155
+ const measured = _num(measuredSeconds), hint = _num(source && source.fields && source.fields.duration);
156
+ const seconds = measured > 0 ? measured : (hint > 0 ? hint : null);
157
+ return Object.assign({}, fields || {}, { inputVideoSeconds: seconds });
158
+ }
159
+ function inputVideoSecondRate(pricing, fields, ctx) {
160
+ const p = pricing || {}, f = fields || {}, c = ctx || {}, pp = c.params || {};
161
+ const res = f.resolution || (f.modelOpts || {}).resolution
162
+ || (pp.resolution && pp.resolution.default) || (c.defaults || {}).resolution || p.default_resolution;
163
+ const rates = p.per_second_by_output_resolution;
164
+ const rate = rates && _num(rates[res]);
165
+ return rate != null && rate >= 0 ? rate : null;
166
+ }
167
+
119
168
  // A video run bills a HIGHER tier when reference images are wired or the model's
120
169
  // audio switch is on. refWired comes from the graph wiring; the audio switch /
121
170
  // reference mode ride in fields.modelOpts. refWired may be a boolean (legacy
@@ -129,7 +178,7 @@ function videoUnitUsd(pricing, fields, refWired, audioCtx) {
129
178
  const audioOn = videoAudioOn(f, audioCtx);
130
179
  const refCount = typeof refWired === "number" ? Math.max(0, refWired | 0) : (refWired ? 1 : 0);
131
180
  const refOn = refCount > 0 || /reference/i.test(String(opts.mode || ""));
132
- let usd = videoBaseUsd(p, f, audioOn, refOn);
181
+ let usd = videoBaseUsd(p, f, audioOn, refOn, audioCtx);
133
182
  if (usd != null && isFinite(usd) && audioOn && p.audio_multiplier != null) usd *= (_num(p.audio_multiplier) ?? 1);
134
183
  // MiniMax H3 LoRA: each wired reference image/audio adds
135
184
  // pricing.lora.reference_image_or_audio ($0.02). This number is the quote,
@@ -147,31 +196,50 @@ function videoUnitUsd(pricing, fields, refWired, audioCtx) {
147
196
  }
148
197
  return usd;
149
198
  }
150
- function videoBaseUsd(pricing, fields, audioOn, refOn) {
199
+ function videoBaseUsd(pricing, fields, audioOn, refOn, audioCtx) {
151
200
  const p = pricing || {}, raw = (p.raw && typeof p.raw === "object") ? p.raw : {};
152
201
  const f = fields || {};
153
202
  const res = f.resolution, defRes = p.default_resolution ?? raw.defaultResolution;
203
+ if (p.unit === "input_video_second") {
204
+ const seconds = _num(f.inputVideoSeconds), rate = inputVideoSecondRate(p, f, audioCtx);
205
+ const max = _num(p.maximum_seconds);
206
+ return seconds > 0 && (max == null || seconds <= max) && rate != null ? seconds * rate : null;
207
+ }
154
208
  const dur = pickDur(p, raw, f);
155
- const rp = (m) => pickByRes(m, res, defRes);
209
+ const frameBill = frameLimitedBilling(p, f, dur);
210
+ const billDur = frameBill ? frameBill.seconds * frameBill.multiplier : perSecondQuantity(p, dur);
211
+ const rp = (m) => pickByRes(m, frameBill ? frameBill.resolution : res, defRes);
156
212
  let v;
157
- if ((v = rp(p.per_second_by_resolution)) != null) return v * dur;
158
- if ((v = rp(p.standard_prices_per_second)) != null) return v * dur;
213
+ if ((v = rp(p.per_requested_second)) != null) return Math.max(v * dur, _num(p.minimum) || 0);
214
+ if (p.per_megapixel != null && p.megapixels_by_resolution) {
215
+ const opts = f.modelOpts || {};
216
+ const mp = rp(p.megapixels_by_resolution);
217
+ const fps = _num(opts.frames_per_second ?? opts.fps ?? p.default_frames_per_second) || 24;
218
+ // LTX generates the terminal frame as well as duration × FPS frames.
219
+ const frames = Math.round(dur * fps) + 1;
220
+ const premium = opts.mode === "hdr" || videoLoraOn(f) || [1, 2, 3].some(i => String(opts[`lora_url_${i}`] || "").trim());
221
+ const rate = _num(premium ? p.hdr_or_lora_per_megapixel : p.per_megapixel);
222
+ if (mp != null && rate != null) return rate * Math.ceil(frames * mp);
223
+ return null;
224
+ }
225
+ if ((v = rp(p.per_second_by_resolution)) != null) return v * billDur;
226
+ if ((v = rp(p.standard_prices_per_second)) != null) return v * billDur;
159
227
  if (p.per_second_by_mode) {
160
228
  const mm = p.per_second_by_mode;
161
229
  v = refOn ? (_num(mm.reference_to_video_image) ?? _num(mm.reference_to_video_video)) : null;
162
230
  if (v == null) v = _num(mm.text_to_video) ?? pickByRes(mm);
163
- if (v != null) return v * dur;
231
+ if (v != null) return v * billDur;
164
232
  }
165
233
  if (audioOn) {
166
- for (const k of ["text_image_with_audio_per_second", "image_to_video_with_audio_per_second", "text_to_video_with_audio_per_second"]) {
167
- if (p[k] != null) { v = (typeof p[k] === "object") ? rp(p[k]) : _num(p[k]); if (v != null) return v * dur; }
234
+ for (const k of ["text_image_with_audio_per_second", "image_to_video_with_audio_per_second", "text_to_video_with_audio_per_second", "per_second_with_audio"]) {
235
+ if (p[k] != null) { v = (typeof p[k] === "object") ? rp(p[k]) : _num(p[k]); if (v != null) return v * billDur; }
168
236
  }
169
237
  }
170
- for (const k of ["text_to_video_per_second", "text_image_without_audio_per_second", "image_to_video_without_audio_per_second"]) {
171
- if (p[k] != null) { v = (typeof p[k] === "object") ? rp(p[k]) : _num(p[k]); if (v != null) return v * dur; }
238
+ for (const k of ["text_to_video_per_second", "text_image_without_audio_per_second", "image_to_video_without_audio_per_second", "per_second_without_audio"]) {
239
+ if (p[k] != null) { v = (typeof p[k] === "object") ? rp(p[k]) : _num(p[k]); if (v != null) return v * billDur; }
172
240
  }
173
- if (p.base_price_per_second != null) { const m = p.resolution_multipliers ? (rp(p.resolution_multipliers) ?? 1) : 1; v = _num(p.base_price_per_second); if (v != null) return v * dur * m; }
174
- if (p.per_second != null) { v = _num(p.per_second); if (v != null) return v * dur; }
241
+ if (p.base_price_per_second != null) { const m = p.resolution_multipliers ? (rp(p.resolution_multipliers) ?? 1) : 1; v = _num(p.base_price_per_second); if (v != null) return v * billDur * m; }
242
+ if (p.per_second != null) { v = _num(p.per_second); if (v != null) return v * billDur; }
175
243
  if (p.per_duration) { const dk = String(Math.round(dur)); v = _num(p.per_duration[dk]) ?? _num(p.per_duration[String(dur)]) ?? pickByRes(p.per_duration); if (v != null) return v; }
176
244
  if (p.without_audio != null || p.with_audio != null) { v = audioOn ? (_num(p.with_audio) ?? _num(p.without_audio)) : (_num(p.without_audio) ?? _num(p.with_audio)); if (v != null) return v; }
177
245
  if (p.base_prices_by_resolution) {
@@ -184,9 +252,9 @@ function videoBaseUsd(pricing, fields, audioOn, refOn) {
184
252
  if (base != null) return base * mult;
185
253
  }
186
254
  if ((v = rp(p.per_resolution)) != null) return v;
187
- if (p.base_price != null && p.per_extra_second != null) { const bd = _num(p.base_duration) || 0; return _num(p.base_price) + Math.max(0, dur - bd) * _num(p.per_extra_second); }
255
+ if (p.base_price != null && p.per_extra_second != null) { const bd = _num(p.base_duration) || 0; return _num(p.base_price) + Math.max(0, billDur - bd) * _num(p.per_extra_second); }
188
256
  if (p.per_video != null) { v = _num(p.per_video); if (v != null) return v; }
189
- if (p.per_target_megapixel_second != null) { const mp = _num(p.default_target_megapixels) || 1; v = _num(p.per_target_megapixel_second) * mp * dur; return Math.max(v, _num(p.minimum_price) || 0); }
257
+ if (p.per_target_megapixel_second != null) { const mp = _num(p.default_target_megapixels) || 1; v = _num(p.per_target_megapixel_second) * mp * billDur; return Math.max(v, _num(p.minimum_price) || 0); }
190
258
  if (p.per_frame_unit != null) { const fpu = _num(p.frames_per_unit) || 1; return (dur * EST.videoFps / fpu) * _num(p.per_frame_unit); }
191
259
  if (p.base_price != null) { v = _num(p.base_price); if (v != null) return v; }
192
260
  if (Object.keys(raw).length) {
@@ -194,16 +262,16 @@ function videoBaseUsd(pricing, fields, audioOn, refOn) {
194
262
  if (raw.referenceToVideoPrices) { const inner = pickObjByRes(raw.referenceToVideoPrices, res, defRes); if (inner) { const dk = String(Math.round(dur)); v = _num(inner[dk]) ?? pickByRes(inner); if (v != null) return v; } }
195
263
  for (const k of ["textToVideoWithReferenceVideoPricesPerSecond", "standardTextToVideoWithReferenceVideoPricesPerSecond", "turboTextToVideoWithReferenceVideoPricesPerSecond",
196
264
  "standardReferenceVideoPricesPerSecond", "fastReferenceVideoPricesPerSecond"]) {
197
- if (raw[k]) { v = pickByRes(raw[k], res, defRes); if (v != null) return v * dur; }
265
+ if (raw[k]) { v = pickByRes(raw[k], res, defRes); if (v != null) return v * billDur; }
198
266
  }
199
267
  }
200
268
  if (audioOn) {
201
- if (raw.withAudioPricesPerSecond) { v = pickByRes(raw.withAudioPricesPerSecond, res, defRes); if (v != null) return v * dur; }
269
+ if (raw.withAudioPricesPerSecond) { v = pickByRes(raw.withAudioPricesPerSecond, res, defRes); if (v != null) return v * billDur; }
202
270
  if (raw.withAudioPrices) { const inner = pickObjByRes(raw.withAudioPrices, res, defRes); if (inner) { const dk = String(Math.round(dur)); v = _num(inner[dk]) ?? pickByRes(inner); if (v != null) return v; } }
203
271
  }
204
272
  for (const k of ["pricesPerSecond", "textToVideoPricesPerSecond", "withoutAudioPricesPerSecond",
205
273
  "standardPricesPerSecond", "standardTextToVideoPricesPerSecond", "outputPricesPerSecond", "fastPricesPerSecond"]) {
206
- if (raw[k]) { v = pickByRes(raw[k], res, defRes); if (v != null) return v * dur; }
274
+ if (raw[k]) { v = pickByRes(raw[k], res, defRes); if (v != null) return v * billDur; }
207
275
  }
208
276
  for (const k of ["withoutAudioPrices", "withAudioPrices", "referenceToVideoPrices"]) {
209
277
  if (raw[k]) { const inner = pickObjByRes(raw[k], res, defRes); if (inner) { const dk = String(Math.round(dur)); v = _num(inner[dk]) ?? pickByRes(inner); if (v != null) return v; } }
@@ -221,12 +289,11 @@ function videoBaseUsd(pricing, fields, audioOn, refOn) {
221
289
  // once refs are wired. The per-ref surcharge is added in videoUnitUsd.
222
290
  if (p.output_per_second != null && p.lora && typeof p.lora === "object" && videoLoraOn(f)) {
223
291
  const L = p.lora;
224
- const billSecs = (d, lo, hi) => Math.min(_num(hi) ?? d, Math.max(_num(lo) ?? d, d));
225
292
  const tbl = (refOn && L.reference_per_second) ? L.reference_per_second : L.text_or_image_per_second;
226
293
  v = (tbl && typeof tbl === "object") ? rp(tbl) : _num(tbl);
227
- if (v != null) return v * billSecs(dur, L.min_duration, L.max_duration);
294
+ if (v != null) return v * perSecondQuantity(L.billing ? L : p, clampSeconds(dur, L.min_duration, L.max_duration));
228
295
  }
229
- return genericScanUsd(p, dur);
296
+ return genericScanUsd(p, billDur);
230
297
  }
231
298
  // Last resort so a never-seen pricing shape estimates SOMETHING rather than
232
299
  // blanking: the smallest per-second number scaled by duration, else the
@@ -254,7 +321,7 @@ function audioUnitUsd(pricing, chars, seconds) {
254
321
  if (p.per_thousand_chars != null) { let cost = _num(p.per_thousand_chars) * (c / 1000); if (p.per_generation != null) cost += _num(p.per_generation); return Math.max(cost, _num(p.minimum) || 0); }
255
322
  if (p.per_prompt_char_block != null) { const bs = _num(p.prompt_char_block_size) || 1; return Math.max(Math.ceil(c / bs) * _num(p.per_prompt_char_block), _num(p.minimum) || 0); }
256
323
  if (p.per_generation != null) return _num(p.per_generation);
257
- if (p.per_second != null) return Math.max(_num(p.per_second) * secs, _num(p.minimum) || 0);
324
+ if (p.per_second != null) return Math.max(_num(p.per_second) * perSecondQuantity(p, secs), _num(p.minimum) || 0);
258
325
  // per started billing interval (ElevenLabs Music / VEED Clean Audio: $/started minute)
259
326
  if (p.per_billing_interval != null) {
260
327
  const iv = _num(p.billing_interval_seconds) || 60;
@@ -279,6 +346,25 @@ function imageUsd(pricing, size, count) {
279
346
  return (v != null && isFinite(+v)) ? +v * (count || 1) : null;
280
347
  }
281
348
 
349
+ // TRELLIS.2 publishes an explicit resolution tier and a 4K-texture surcharge
350
+ // tier. Keep this mapping scoped to its documented contract; arbitrary variant
351
+ // labels on other models must not be guessed from unrelated option values.
352
+ function model3dVariantPrice(model, fields) {
353
+ if (model.id !== "wavespeed-ai/trellis-2/image-to-3d") return null;
354
+ const p = model.pricing || {}, by = p.per_run_by_variant;
355
+ if (!by || typeof by !== "object") return null;
356
+ const sp = model.supported_parameters || {}, defs = sp.defaults || {}, params = sp.parameters || {};
357
+ const opts = (fields && fields.modelOpts) || {};
358
+ const pick = (key) => opts[key] ?? defs[key] ?? (params[key] && params[key].default);
359
+ const resolution = pick("resolution") ?? p.default_variant;
360
+ const texture = pick("texture_size");
361
+ // Unknown sizes are not certified as a known variant, even if they would
362
+ // happen to select an existing base-resolution entry.
363
+ if (!["1024", "2048", "4096"].includes(String(texture))) return null;
364
+ const key = String(resolution) + (String(texture) === "4096" ? "+4k-texture" : "");
365
+ return Object.hasOwn(by, key) ? _num(by[key]) : null;
366
+ }
367
+
282
368
  /** Which pricing kinds a graph touches — so a caller fetches only the catalogs it needs. */
283
369
  export function graphModelKinds(graph) {
284
370
  const kinds = new Set();
@@ -286,6 +372,47 @@ export function graphModelKinds(graph) {
286
372
  return kinds;
287
373
  }
288
374
 
375
+ // 🎬 Avatar / lip-sync models bill the AUDIO's length, not the 5 s video default
376
+ // (twin of the app's avatarAudioEstSeconds, nanoodle #782). Seconds the forecast
377
+ // assumes for the wired audio source: its measured length when known, else its
378
+ // duration knob, else (a Speech/tts node) the words it will speak at ~2.8 words/s —
379
+ // the wired/typed text, or EST.ttsChars at ~15 chars/s when the text isn't known.
380
+ // Whole seconds, rounded up (LongCat billed 14 s for a 13.1 s voice). null =
381
+ // nothing usable wired → keep the model default.
382
+ export function avatarAudioEstSeconds(src, srcText, measuredSecs) {
383
+ if (!src) return null;
384
+ const m = +measuredSecs; if (isFinite(m) && m > 0) return Math.max(1, Math.ceil(m - 1e-6));
385
+ const d = parseFloat(src.fields && src.fields.duration); if (isFinite(d) && d > 0) return Math.max(1, Math.ceil(d - 1e-6));
386
+ if (src.type !== "tts") return null;
387
+ const txt = String(srcText || (src.fields && src.fields.prompt) || "").trim();
388
+ const secs = txt ? txt.split(/\s+/).length / 2.8 : EST.ttsChars / 15;
389
+ return Math.max(1, Math.ceil(secs - 1e-6));
390
+ }
391
+ // LongCat Avatar bills whole voice seconds clamped to the catalog's minimum/
392
+ // maximum_billable_duration (longcat-avatar-1.5 = 3–30 s); fall back to 3–30 s for
393
+ // longcat-avatar-1.5 when the catalog omits them. Other avatar models: unchanged.
394
+ // (Twin of the app's avatarClampSecs.)
395
+ export function avatarClampSecs(model, secs, pricing) {
396
+ if (secs == null || !isFinite(secs)) return secs;
397
+ const p = pricing || {};
398
+ let lo = +p.minimum_billable_duration, hi = +p.maximum_billable_duration;
399
+ if (!(lo > 0) || !(hi >= lo)) { if (!/^longcat-avatar-1\.5(?!\/)/i.test(String(model || ""))) return secs; lo = 3; hi = 30; }
400
+ return Math.min(hi, Math.max(lo, secs));
401
+ }
402
+ // Seconds the wired audio of a lipsync node will run, from the static graph
403
+ // (Node has no media element, so no measured length; a run's actual audio is not inferred).
404
+ function lipsyncAudioSeconds(node, graph) {
405
+ if (!graph || !Array.isArray(graph.links) || !Array.isArray(graph.nodes)) return null;
406
+ const byId = (id) => graph.nodes.find((x) => x.id === id);
407
+ const al = graph.links.find((l) => l.to && l.to.node === node.id && l.to.port === "audio");
408
+ const src = al && al.from && byId(al.from.node);
409
+ if (!src) return null;
410
+ const tl = graph.links.find((l) => l.to && l.to.node === src.id && l.to.port === "prompt");
411
+ const ts = tl && tl.from && byId(tl.from.node);
412
+ const txt = ts ? ((ts.out && typeof ts.out.text === "string" && ts.out.text) || (ts.type === "text" && ts.fields && ts.fields.text) || "") : "";
413
+ return avatarAudioEstSeconds(src, txt, null);
414
+ }
415
+
289
416
  // One node's USD/run from its chosen model + settings. `catItem` is the raw
290
417
  // catalog entry for node.fields.model (null → unpriceable). `graph` is needed
291
418
  // only to detect wired reference-image ports (video ref tier).
@@ -308,22 +435,37 @@ function nodeUnitUsd(node, catItem, graph) {
308
435
  ? graph.links.filter((l) => l.to && l.to.node === node.id && REF_PORT_RE.test(l.to.port)).length
309
436
  : 0;
310
437
  const audioCtx = { params: (sp.parameters && typeof sp.parameters === "object") ? sp.parameters : {}, defaults: sp.defaults || {} };
311
- const u = videoUnitUsd(pricing, f, refCount, audioCtx);
438
+ const sourceLink = (graph?.links || []).find(l => l.to?.node === node.id && l.to.port === "video");
439
+ const source = sourceLink && (graph.nodes || []).find(n => n.id === sourceLink.from.node);
440
+ let quoteFields = inputVideoPriceFields(pricing, f, source, null);
441
+ if (node.type === "lipsync") {
442
+ const secs = lipsyncAudioSeconds(node, graph);
443
+ if (secs != null) quoteFields = { ...quoteFields, duration: avatarClampSecs(id, secs, pricing) };
444
+ }
445
+ let u = videoUnitUsd(pricing, quoteFields, refCount, audioCtx);
446
+ // OpenJutsu's primary character/object image is the image port, not a refN.
447
+ // Count only inputs that this runner forwards, not arbitrary stale ref wires.
448
+ if (u != null && pricing?.unit === "per_verified_source_second_plus_image") {
449
+ const imageCount = (graph?.links || []).filter(l => l.to?.node === node.id && l.to.port === "image").length;
450
+ u += imageCount * (_num(pricing.per_image) || 0);
451
+ }
312
452
  return (u != null && isFinite(u)) ? u : null;
313
453
  }
314
- if (kind === "model3d") return _num(pricing && pricing.per_run);
315
- if (node.type === "decide") {
454
+ if (kind === "model3d") return model3dVariantPrice(m, f) ?? _num(pricing && pricing.per_run);
455
+ if (node.type === "decide" || node.type === "decide-branch") {
316
456
  // input tokens only (twin of the editor's Decide estimate); pick asks twice (in order + reversed)
317
457
  const imgs = (graph && Array.isArray(graph.links))
318
458
  ? graph.links.filter((l) => l.to && l.to.node === node.id && /^img\d+$/.test(l.to.port)).length : 0;
319
459
  const inTok = 120 + Math.round(((f.question || "").length + (f.options || "").length + (f.levels || "").length) / 4) + 250 + imgs * 400;
320
460
  const u = chatUnitUsd(pricing, inTok, 0);
321
- const pick = !(f.mode === "choose" || f.mode === "score" || f.mode === "yesno");
461
+ const pick = !(node.type === "decide-branch" || f.branch === true || f.mode === "choose" || f.mode === "score" || f.mode === "yesno");
322
462
  return u == null ? null : u * (pick ? 2 : 1);
323
463
  }
324
464
  if (kind === "chat") {
325
465
  const inTok = Math.max(200, Math.round(((f.system || "").length + (f.prompt || "").length) / 4) + 200);
326
- const outTok = f.maxTokens ? +f.maxTokens : EST.llmOutTokens;
466
+ // An explicit maxTokens cap prices the output at the cap (D1 ruling);
467
+ // absent, the default estimate applies — twin of nanoodle-py estimate.py.
468
+ const outTok = f.maxTokens && Number.isFinite(+f.maxTokens) ? Math.trunc(+f.maxTokens) : EST.llmOutTokens;
327
469
  return chatUnitUsd(pricing, inTok, outTok);
328
470
  }
329
471
  if (kind === "audio") {
@@ -348,7 +490,7 @@ function nodeUnitUsd(node, catItem, graph) {
348
490
  * Forecast a graph's per-run cost from the public catalog.
349
491
  *
350
492
  * @param {{nodes:Array, links?:Array}} graph a materialized graph (Workflow#graph)
351
- * @param {{chat?:Array, image?:Array, video?:Array, audio?:Array, model3d?:Array}} catalogs
493
+ * @param {{chat?:Array, decision?:Array, image?:Array, video?:Array, audio?:Array, model3d?:Array}} catalogs
352
494
  * raw catalog arrays (as /api/v1/*-models return them, `.data`), indexed here by model id
353
495
  * @returns {{usd:number, exact:boolean, priced:number, unpriced:number}}
354
496
  * usd = sum over priced billable nodes; exact = every priced node was image
@@ -357,7 +499,7 @@ function nodeUnitUsd(node, catItem, graph) {
357
499
  export function estimateGraphCost(graph, catalogs = {}) {
358
500
  const nodes = (graph && Array.isArray(graph.nodes)) ? graph.nodes : [];
359
501
  const byKind = {};
360
- for (const kind of ["chat", "image", "video", "audio", "model3d"]) {
502
+ for (const kind of ["chat", "decision", "image", "video", "audio", "model3d"]) {
361
503
  const arr = Array.isArray(catalogs[kind]) ? catalogs[kind] : [];
362
504
  const map = new Map();
363
505
  for (const m of arr) if (m && m.id != null) map.set(String(m.id), m);
@@ -375,7 +517,7 @@ export function estimateGraphCost(graph, catalogs = {}) {
375
517
  const by = m.pricing && m.pricing.per_run_by_variant;
376
518
  if (by && typeof by === "object") {
377
519
  const vals = Object.values(by).map(_num).filter((v) => v != null);
378
- if (vals.length && Math.min(...vals) !== Math.max(...vals)) exact = false;
520
+ if (vals.length && Math.min(...vals) !== Math.max(...vals) && model3dVariantPrice(m, n.fields) == null) exact = false;
379
521
  }
380
522
  } else if (kind !== "image") exact = false;
381
523
  }
package/src/graph.mjs CHANGED
@@ -52,7 +52,7 @@ export const NODE_TYPES = {
52
52
  decide: { title: "Decide", inputs: ["text"], outputs: [{ name: "text", type: "text" }, { name: "image", type: "image" }], network: true }, // img1… candidates (IMG_PORT_RE)
53
53
  tvideo: { title: "Text→Video", inputs: [], outputs: [{ name: "video", type: "video" }], network: true },
54
54
  ivideo: { title: "Image→Video", inputs: ["image"], outputs: [{ name: "video", type: "video" }], network: true },
55
- model3d: { title: "3D model", inputs: ["image"], outputs: [{ name: "model", type: "model3d" }], network: true },
55
+ model3d: { title: "3D model", inputs: ["image", "model"], outputs: [{ name: "model", type: "model3d" }], network: true },
56
56
  vedit: { title: "Video edit", inputs: ["video"], outputs: [{ name: "video", type: "video" }], network: true },
57
57
  vframes: { title: "Video → frames", inputs: ["video"], outputs: [{ name: "frame1", type: "image" }], local: true, framesOut: true }, // dynamic frame1..N
58
58
  combine: { title: "Combine videos", inputs: [], outputs: [{ name: "video", type: "video" }], local: true },
@@ -150,10 +150,15 @@ export function materialize(data) {
150
150
  }
151
151
  const warnings = [];
152
152
  const nodes = [];
153
+ const seenIds = new Set();
153
154
  for (const raw of data.nodes) {
154
155
  if (!raw || raw.id == null || !raw.type) continue;
155
- const type = raw.type === "audio" ? "tts" : raw.type;
156
+ const id = String(raw.id);
157
+ if (seenIds.has(id)) throw new NanoodleError(`duplicate node id "${id}" — every node must have a unique id`);
158
+ seenIds.add(id);
159
+ const type = raw.type === "audio" ? "tts" : raw.type === "decide-branch" ? "decide" : raw.type;
156
160
  const n = { id: String(raw.id), type, name: raw.name, fields: { ...(raw.fields || {}) } };
161
+ if (raw.type === "decide-branch") n.fields.branch = true;
157
162
  if (!NODE_TYPES[type]) {
158
163
  n.unknown = true;
159
164
  warnings.push(`unknown node type "${raw.type}" (node ${n.id}) — kept, but running this workflow will fail; you may need a newer nanoodle library`);
@@ -0,0 +1,11 @@
1
+ // Model knobs may tune generation, but cannot replace node-owned request fields
2
+ // or smuggle routing/authentication settings into an image request.
3
+ export function imageModelOpts(opts) {
4
+ const out = {};
5
+ if (!opts || typeof opts !== "object" || Array.isArray(opts)) return out;
6
+ for (const [key, value] of Object.entries(opts)) {
7
+ if (/^(?:model|prompt|size|n|responseformat|image|images|imageurl|imagedataurl|mask|maskurl|maskdataurl|key|apikey|xapikey|token|accesstoken|authorization|auth|headers|url|endpoint|baseurl|method|body|credentials|proxy|runid|requestid|isapirequest|paymentsource|paymentid|tojson|proto|prototype|constructor)$/i.test(key.replace(/[_-]/g, ""))) continue;
8
+ out[key] = value;
9
+ }
10
+ return out;
11
+ }
package/src/index.mjs CHANGED
@@ -6,6 +6,7 @@ export {
6
6
  } from "./media.mjs";
7
7
  export { NanoClient } from "./client.mjs";
8
8
  export { NODE_TYPES, displayName, materialize, topoSort, wiredFramesFloor, MAX_FRAMES } from "./graph.mjs";
9
+ export { planBranches } from "./branches.mjs";
9
10
  // edit models whose image ports are ORDERED roles — a caller building graphs needs the slot order
10
11
  export { IMG_INPUT_ROLES } from "./nodes.mjs";
11
12
  export { deriveInputs, deriveOutputs, deriveSettings, INPUT_SPECS, SETTING_SPECS } from "./io.mjs";
package/src/io.mjs CHANGED
@@ -2,6 +2,15 @@ import { NanoodleError } from "./errors.mjs";
2
2
  import { NODE_TYPES, displayName, lockedNode, optionalNode, topoSort, wiredFramesFloor, MAX_FRAMES } from "./graph.mjs";
3
3
  import { endpointOutPort } from "./endpoint.mjs";
4
4
 
5
+ // Allocate the final key, not just a count of the unsuffixed name: an authored
6
+ // "Out 2" can otherwise collide with the suffix generated for a second "Out".
7
+ function uniqueKey(base, used, reserved = new Set()) {
8
+ let key = base;
9
+ for (let suffix = 2; used.has(key.toLowerCase()) || reserved.has(key.toLowerCase()); suffix++) key = base + " " + suffix;
10
+ used.add(key.toLowerCase());
11
+ return key;
12
+ }
13
+
5
14
  /* ============================== INPUTS ============================== */
6
15
 
7
16
  /** Which node types contribute user inputs, and with what fields (mirrors play.html INPUT_SPECS). */
@@ -76,19 +85,14 @@ export function deriveInputs(graph) {
76
85
  // REQUIRED input (app PR #138) — or exactly one input at all, so an author-optional
77
86
  // renamed node (e.g. an optional "Style reference" upload) keeps its name as the key.
78
87
  // Otherwise the generic spec label. Dedupe with " 2", " 3".
79
- const used = new Map();
88
+ const used = new Set();
80
89
  for (const e of entries) {
81
90
  const nodeEntries = entries.filter((x) => x.nodeId === e.nodeId);
82
91
  const required = nodeEntries.filter((x) => !x.optional);
83
92
  const custom = (e._node.name || "").trim();
84
93
  const names = (required.length === 1 && required[0] === e) ||
85
94
  (required.length === 0 && nodeEntries.length === 1);
86
- let key = custom && names ? custom : e.label;
87
- const lower = key.toLowerCase();
88
- const count = (used.get(lower) || 0) + 1;
89
- used.set(lower, count);
90
- if (count > 1) key = key + " " + count;
91
- e.key = key;
95
+ e.key = uniqueKey(custom && names ? custom : e.label, used);
92
96
  }
93
97
  for (const e of entries) delete e._node;
94
98
  return entries;
@@ -155,13 +159,10 @@ export function deriveOutputs(graph) {
155
159
  if (!t.outputs || !t.outputs.length) return false;
156
160
  return !graph.links.some((l) => l.from.node === n.id);
157
161
  });
158
- const used = new Map();
162
+ const used = new Set();
159
163
  return sinks.map((n) => {
160
- let key = displayName(n);
161
- const lower = key.toLowerCase();
162
- const count = (used.get(lower) || 0) + 1;
163
- used.set(lower, count);
164
- if (count > 1) key = key + " " + count;
164
+ const aliases = new Set(sinks.filter(other => other.id !== n.id).map(other => other.id.toLowerCase()));
165
+ const key = uniqueKey(displayName(n), used, aliases);
165
166
  const t = NODE_TYPES[n.type];
166
167
  let ports = t.outputs.map((p) => ({ ...p }));
167
168
  // vframes grows frame1..frameN from max(fields.frames, wired floor) (mirrors browser)
@@ -15,7 +15,7 @@
15
15
  */
16
16
  import { inflate, deflate } from "./zlib.mjs";
17
17
  import { NanoodleError } from "./errors.mjs";
18
- import { bytesToDataUrl, dataUrlBytes, sniffMime, MEDIA_INLINE_MAX } from "./media.mjs";
18
+ import { bytesToDataUrl, dataUrlBytes, downloadMedia, sniffMime, MEDIA_INLINE_MAX } from "./media.mjs";
19
19
  import { MP4CAT } from "./mp4cat.mjs";
20
20
 
21
21
  const MAX_FRAMES = 12;
@@ -114,23 +114,21 @@ async function withTemp(fn) {
114
114
  }
115
115
 
116
116
  /** data:/https URL (or raw string MediaRef url) → bytes. */
117
- async function urlBytes(url, fetchFn) {
117
+ async function urlBytes(url, fetchFn, signal) {
118
118
  if (url == null) throw new NanoodleError("no media input");
119
119
  const u = typeof url === "object" && url.url != null ? url.url : String(url);
120
120
  if (/^data:/i.test(u)) return dataUrlBytes(u).bytes;
121
121
  if (/^https?:/i.test(u)) {
122
122
  const fetchImpl = fetchFn || globalThis.fetch;
123
123
  if (!fetchImpl) throw new NanoodleError("can't download media: no fetch available");
124
- const r = await fetchImpl(u);
125
- if (!r.ok) throw new NanoodleError(`couldn't download media (${r.status}): ${u.slice(0, 120)}`);
126
- return new Uint8Array(await r.arrayBuffer());
124
+ return (await downloadMedia(u, { fetch: fetchImpl, signal })).bytes;
127
125
  }
128
126
  throw new NanoodleError("media must be a data: or http(s) URL");
129
127
  }
130
128
 
131
- async function writeInput(dir, name, url, fetchFn) {
129
+ async function writeInput(dir, name, url, fetchFn, signal) {
132
130
  await ensureNodeDeps();
133
- const bytes = await urlBytes(url, fetchFn);
131
+ const bytes = await urlBytes(url, fetchFn, signal);
134
132
  // preserve a sensible extension so ffmpeg picks the demuxer
135
133
  let ext = ".bin";
136
134
  if (/^data:/i.test(String(typeof url === "object" ? url.url : url))) {
@@ -374,9 +372,9 @@ export async function maskToSource(maskUrl, sourceUrl, { fetch: fetchFn, signal
374
372
  if (!maskUrl) throw new NanoodleError("couldn't read the mask");
375
373
  if (!sourceUrl) throw new NanoodleError("couldn't read the source image");
376
374
 
377
- const srcBytes = await urlBytes(sourceUrl, fetchFn);
375
+ const srcBytes = await urlBytes(sourceUrl, fetchFn, signal);
378
376
  throwIfAborted(signal);
379
- const maskBytes = await urlBytes(maskUrl, fetchFn);
377
+ const maskBytes = await urlBytes(maskUrl, fetchFn, signal);
380
378
  throwIfAborted(signal);
381
379
 
382
380
  const srcMime = sniffMime(srcBytes);
@@ -445,8 +443,8 @@ async function maskToSourcePngPure(maskBytes, srcBytes) {
445
443
  async function maskToSourceFfmpeg(maskUrl, sourceUrl, { fetch: fetchFn, signal } = {}) {
446
444
  return withTemp(async (dir) => {
447
445
  throwIfAborted(signal);
448
- const srcPath = await writeInput(dir, "src", sourceUrl, fetchFn);
449
- const maskPath = await writeInput(dir, "mask", maskUrl, fetchFn);
446
+ const srcPath = await writeInput(dir, "src", sourceUrl, fetchFn, signal);
447
+ const maskPath = await writeInput(dir, "mask", maskUrl, fetchFn, signal);
450
448
  const probe = await runProc("ffprobe", [
451
449
  "-v", "error", "-select_streams", "v:0",
452
450
  "-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", srcPath,
@@ -663,7 +661,7 @@ export async function resizeCropImage(url, mode, tw, th, { fetch: fetchFn, signa
663
661
  if (!w && !h) throw new NanoodleError("set a width or height to resize to");
664
662
  const m = mode || "fit";
665
663
 
666
- const bytes = await urlBytes(url, fetchFn);
664
+ const bytes = await urlBytes(url, fetchFn, signal);
667
665
  throwIfAborted(signal);
668
666
  const mime = sniffMime(bytes);
669
667
 
@@ -738,7 +736,7 @@ export async function fitImageInline(url, { budget = INLINE_IMAGE_BUDGET, fetch:
738
736
  export async function fitImageJpeg(url, maxDim, budget, { fetch: fetchFn, signal } = {}) {
739
737
  return withTemp(async (dir) => {
740
738
  throwIfAborted(signal);
741
- const inPath = await writeInput(dir, "in", url, fetchFn);
739
+ const inPath = await writeInput(dir, "in", url, fetchFn, signal);
742
740
  const probe = await runProc("ffprobe", [
743
741
  "-v", "error", "-select_streams", "v:0",
744
742
  "-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", inPath,
@@ -770,7 +768,7 @@ export async function fitImageJpeg(url, maxDim, budget, { fetch: fetchFn, signal
770
768
  async function resizeCropImageFfmpeg(url, m, w, h, { fetch: fetchFn, signal } = {}) {
771
769
  return withTemp(async (dir) => {
772
770
  throwIfAborted(signal);
773
- const inPath = await writeInput(dir, "in", url, fetchFn);
771
+ const inPath = await writeInput(dir, "in", url, fetchFn, signal);
774
772
  const probe = await runProc("ffprobe", [
775
773
  "-v", "error", "-select_streams", "v:0",
776
774
  "-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", inPath,
@@ -814,7 +812,7 @@ async function resizeCropImageFfmpeg(url, m, w, h, { fetch: fetchFn, signal } =
814
812
  */
815
813
  export async function trimAudioToWav(url, start, len, rate = 16000, { fetch: fetchFn, wholeIfBlank = false, signal } = {}) {
816
814
  throwIfAborted(signal);
817
- const bytes = await urlBytes(url, fetchFn);
815
+ const bytes = await urlBytes(url, fetchFn, signal);
818
816
  throwIfAborted(signal);
819
817
  const mime = sniffMime(bytes);
820
818
 
@@ -840,7 +838,7 @@ export async function trimAudioToWav(url, start, len, rate = 16000, { fetch: fet
840
838
  async function trimAudioToWavFfmpeg(url, start, len, rate = 16000, { fetch: fetchFn, wholeIfBlank = false, signal } = {}) {
841
839
  return withTemp(async (dir) => {
842
840
  throwIfAborted(signal);
843
- const inPath = await writeInput(dir, "in", url, fetchFn);
841
+ const inPath = await writeInput(dir, "in", url, fetchFn, signal);
844
842
  const outPath = join(dir, "out.wav");
845
843
  const s = Math.max(0, Number(start) || 0);
846
844
 
@@ -903,7 +901,7 @@ export async function extractVideoFrames(url, { count = 1, gap = 0.5, dir = "end
903
901
  const fromEnd = (dir || "end") === "end";
904
902
 
905
903
  return withTemp(async (dir) => {
906
- const inPath = await writeInput(dir, "in", url, fetchFn);
904
+ const inPath = await writeInput(dir, "in", url, fetchFn, signal);
907
905
  throwIfAborted(signal);
908
906
  const pr = await runProc("ffprobe", [
909
907
  "-v", "error", "-select_streams", "v:0",
@@ -972,7 +970,7 @@ export async function concatVideos(urls, dedup = true, { fetch: fetchFn, onProgr
972
970
  for (let i = 0; i < urls.length; i++) {
973
971
  throwIfAborted(signal);
974
972
  if (onProgress) onProgress(`loading clip ${i + 1}/${urls.length}…`);
975
- bufs.push(await urlBytes(urls[i], fetchFn));
973
+ bufs.push(await urlBytes(urls[i], fetchFn, signal));
976
974
  }
977
975
  if (bufs.every((b) => MP4CAT.isMp4(b)) && MP4CAT.mp4ParamsMatch(bufs)) {
978
976
  if (onProgress) onProgress("combining…");
@@ -998,7 +996,7 @@ async function concatVideosFfmpeg(urls, dedup = true, { fetch: fetchFn, onProgre
998
996
  for (let i = 0; i < urls.length; i++) {
999
997
  throwIfAborted(signal);
1000
998
  if (onProgress) onProgress(`loading clip ${i + 1}/${urls.length}…`);
1001
- paths.push(await writeInput(dir, `c${i}`, urls[i], fetchFn));
999
+ paths.push(await writeInput(dir, `c${i}`, urls[i], fetchFn, signal));
1002
1000
  }
1003
1001
 
1004
1002
  // When dedup: trim ~1/30s from the start of clips 2..N (approximate seam-frame drop —
@@ -1052,8 +1050,8 @@ export async function muxSoundtrack(videoUrl, audioUrl, loop = false, { fetch: f
1052
1050
  return withTemp(async (dir) => {
1053
1051
  throwIfAborted(signal);
1054
1052
  if (onProgress) onProgress("adding soundtrack…");
1055
- const vPath = await writeInput(dir, "v", videoUrl, fetchFn);
1056
- const aPath = await writeInput(dir, "a", audioUrl, fetchFn);
1053
+ const vPath = await writeInput(dir, "v", videoUrl, fetchFn, signal);
1054
+ const aPath = await writeInput(dir, "a", audioUrl, fetchFn, signal);
1057
1055
  const outPath = join(dir, "out.mp4");
1058
1056
 
1059
1057
  let vdur = null;