nanoodle 0.13.0 → 0.13.3

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/media.mjs CHANGED
@@ -48,7 +48,7 @@ const EXT_MIME = {
48
48
  ".mp3": "audio/mpeg", ".wav": "audio/wav", ".ogg": "audio/ogg", ".opus": "audio/ogg",
49
49
  ".aac": "audio/aac", ".flac": "audio/flac", ".m4a": "audio/mp4",
50
50
  ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".mkv": "video/x-matroska",
51
- ".glb": "model/gltf-binary",
51
+ ".glb": "model/gltf-binary", ".ply": "model/ply",
52
52
  ".txt": "text/plain", ".json": "application/json",
53
53
  };
54
54
 
@@ -57,7 +57,7 @@ const MIME_EXT = {
57
57
  "audio/mpeg": "mp3", "audio/wav": "wav", "audio/ogg": "ogg", "audio/aac": "aac",
58
58
  "audio/flac": "flac", "audio/mp4": "m4a",
59
59
  "video/mp4": "mp4", "video/webm": "webm", "video/quicktime": "mov",
60
- "model/gltf-binary": "glb",
60
+ "model/gltf-binary": "glb", "model/ply": "ply", "application/ply": "ply", "application/x-ply": "ply",
61
61
  "text/plain": "txt", "application/json": "json",
62
62
  };
63
63
 
@@ -105,6 +105,7 @@ export function sniffMime(bytes) {
105
105
  if (b.length >= 12 && ascii(4, "ftyp")) return "video/mp4";
106
106
  if (b.length >= 4 && b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3) return "video/webm";
107
107
  if (b.length >= 4 && ascii(0, "glTF")) return "model/gltf-binary";
108
+ if (/^ply\r?\nformat (?:ascii|binary_little_endian|binary_big_endian) 1\.0\r?\n/.test(new TextDecoder().decode(b.subarray(0, 64)))) return "model/ply";
108
109
  return "application/octet-stream";
109
110
  }
110
111
 
@@ -127,6 +128,47 @@ export function dataUrlBytes(url) {
127
128
  return { bytes, mime };
128
129
  }
129
130
 
131
+ /**
132
+ * Internal hosted-media GET. Retry connection/body interruptions from scratch,
133
+ * never generation POSTs. Keep errors redacted even when fetch includes a signed
134
+ * URL in its exception. HTTP rejections and deliberate cancellation are final.
135
+ */
136
+ export async function downloadMedia(url, { fetch: fetchFn = globalThis.fetch, signal, what = "media" } = {}) {
137
+ const checkAbort = () => {
138
+ if (signal && signal.aborted) throw signal.reason || new NanoodleError("download aborted", { code: "aborted" });
139
+ };
140
+ for (let attempt = 1; attempt <= 3; attempt++) {
141
+ checkAbort();
142
+ try {
143
+ if (typeof fetchFn !== "function") throw new NanoodleError("can't download media: no fetch available");
144
+ const r = await fetchFn(url, { signal }); // CDN: no credentials or API auth headers
145
+ if (!r.ok) throw new NanoodleError(`couldn't download ${what} (${r.status}): ${redactUrl(url)}`, { status: r.status });
146
+ const bytes = new Uint8Array(await r.arrayBuffer());
147
+ checkAbort();
148
+ return { bytes, response: r };
149
+ } catch (e) {
150
+ checkAbort();
151
+ if (e && (e.name === "AbortError" || e.code === "aborted")) throw e;
152
+ if (e instanceof NanoodleError) throw e;
153
+ if (attempt === 3) throw new NanoodleError(`couldn't download ${what}: ${redactUrl(url)}`, { code: "download", attempts: attempt });
154
+ }
155
+ // Short, bounded backoff; cancellation also interrupts the retry delay.
156
+ await new Promise((resolve, reject) => {
157
+ const done = () => { if (signal) signal.removeEventListener("abort", cancel); resolve(); };
158
+ const timer = setTimeout(done, 100 * attempt);
159
+ const cancel = () => {
160
+ clearTimeout(timer);
161
+ signal.removeEventListener("abort", cancel);
162
+ reject(signal.reason || new NanoodleError("download aborted", { code: "aborted" }));
163
+ };
164
+ if (signal) {
165
+ signal.addEventListener("abort", cancel, { once: true });
166
+ if (signal.aborted) cancel();
167
+ }
168
+ });
169
+ }
170
+ }
171
+
130
172
  /**
131
173
  * A media output value: a data: or https URL plus lazy byte access.
132
174
  * String-coerces to the URL so it drops into templates / JSON naturally.
@@ -153,28 +195,33 @@ export class MediaRef {
153
195
  toString() { return this.url; }
154
196
  toJSON() { return this.url; }
155
197
 
156
- /** @returns {Promise<Uint8Array>} the raw media bytes (decodes data:, fetches http(s)). */
157
- async bytes() {
158
- if (this.url.startsWith("data:")) return dataUrlBytes(this.url).bytes;
159
- let r;
160
- try {
161
- r = await this._fetch(this.url);
162
- } catch (e) {
163
- if (e && (e.name === "AbortError" || e.code === "aborted")) throw e;
164
- throw new NanoodleError("couldn't download media: " + redactUrl(this.url));
165
- }
166
- if (!r.ok) throw new NanoodleError("couldn't download media (" + r.status + "): " + redactUrl(this.url));
167
- if (!this._mime) {
168
- const ct = r.headers && r.headers.get && r.headers.get("content-type");
169
- if (ct) this._mime = ct.split(";")[0].trim();
198
+ /** Read the raw media bytes, optionally cancelling the download with a signal. */
199
+ async bytes({ signal } = {}) {
200
+ signal?.throwIfAborted();
201
+ let bytes;
202
+ if (this.url.startsWith("data:")) bytes = dataUrlBytes(this.url).bytes;
203
+ else {
204
+ const downloaded = await downloadMedia(this.url, { fetch: this._fetch, signal });
205
+ bytes = downloaded.bytes;
206
+ if (!this._mime) {
207
+ const r = downloaded.response;
208
+ const ct = r.headers && r.headers.get && r.headers.get("content-type");
209
+ if (ct) this._mime = ct.split(";")[0].trim();
210
+ }
170
211
  }
171
- return new Uint8Array(await r.arrayBuffer());
212
+ // CDNs commonly serve model assets as generic binary. Sniff their actual
213
+ // format before the CLI or save() chooses a filename extension.
214
+ if (!this._mime || /^(?:application|binary)\/octet-stream$/i.test(this._mime)) this._mime = sniffMime(bytes);
215
+ return bytes;
172
216
  }
173
217
 
174
- /** Write the media bytes to `path` (Node only); resolves to the path. */
218
+ /** Write bytes (Node only); append a media extension if absent, and return the saved path. */
175
219
  async save(path) {
176
220
  const { writeFile } = await import("node:fs/promises");
177
- await writeFile(path, await this.bytes());
221
+ const { extname } = await import("node:path");
222
+ const bytes = await this.bytes();
223
+ if (typeof path === "string" && !extname(path)) path += "." + extForMime(this.mime);
224
+ await writeFile(path, bytes);
178
225
  return path;
179
226
  }
180
227
  }
package/src/nodes.mjs CHANGED
@@ -86,14 +86,20 @@ function guardInputRoles(model, inp) {
86
86
  }
87
87
 
88
88
  /**
89
- * edit/inpaint have a single image output, but some models always bill (and return) a fixed
90
- * batch — midjourney/text-to-image and higgsfield-soul declare fixed_image_count: 4. Ask with
91
- * multi so we can SEE the extras and say we dropped them; the return shape stays one url.
89
+ * edit/inpaint surface EVERY image a model returns. `image` stays the first — the
90
+ * long-standing single-output contract, unchanged for existing graphs — `images`
91
+ * carries them all in response order (mirroring the image node's variations
92
+ * output), and when response items carry layer metadata (layer-decomposition
93
+ * models), `layers` carries it aligned by index with `images`. Fixed-batch
94
+ * models (midjourney fixed_image_count: 4) surface their variants the same way;
95
+ * nothing a model returns is dropped silently anymore.
92
96
  */
93
- function keptFirst(urls, ctx) {
94
- if (!Array.isArray(urls)) return urls; // host-injected ctx.image that ignores multi → already one url
95
- if (urls.length > 1 && ctx && ctx.progress) ctx.progress(`model returned ${urls.length} images, kept the first`);
96
- return urls[0];
97
+ function multiOut(res) {
98
+ if (typeof res === "string") return { image: res, images: [res] }; // a host-injected ctx.image that ignores multi/items → already one url
99
+ const urls = Array.isArray(res) ? res : res.urls; // …or one that honors multi but not `items` → bare urls
100
+ const out = { image: urls[0], images: urls };
101
+ if (!Array.isArray(res) && res.layers) out.layers = res.layers;
102
+ return out;
97
103
  }
98
104
 
99
105
  function promptOf(n, inp, errMsg) {
@@ -129,7 +135,10 @@ function audioInputPart(url) {
129
135
  function llmOpts(n) {
130
136
  const f = n.fields, o = {};
131
137
  if (f.temperature != null && f.temperature !== "") o.temperature = +f.temperature;
132
- if (f.maxTokens) o.max_tokens = +f.maxTokens;
138
+ // maxTokens is opt-in (D1 ruling, 2026-11-18): absent by default, honored
139
+ // exactly when the node sets it — twin of nanoodle-py _run_llm (truthy +
140
+ // numeric → int(float(v)); non-numeric degrades gracefully, sends nothing).
141
+ if (f.maxTokens && Number.isFinite(+f.maxTokens)) o.max_tokens = Math.trunc(+f.maxTokens);
133
142
  if (f.format === "JSON") o.response_format = { type: "json_object" };
134
143
  if (f.reasoningEffort && f.reasoningEffort !== "default") o.reasoning_effort = f.reasoningEffort;
135
144
  if (f.showThinking === true || f.showThinking === "true") o.showThinking = true;
@@ -165,6 +174,7 @@ function normalizeLoraUrl(raw) {
165
174
  function loraFamily(model) {
166
175
  const m = String(model || "");
167
176
  if (/spicy/i.test(m)) return null;
177
+ if (/p-h3-image/i.test(m)) return "ph3"; // wavespeed p-h3-image: lora_url_1..3 (ids lack "lora")
168
178
  if (/p-image/i.test(m)) return "pimage";
169
179
  if (/klein/i.test(m)) return "flux2klein";
170
180
  if (/flux-2/i.test(m)) return "flux2dev";
@@ -188,6 +198,7 @@ function imageTakesLora(id) {
188
198
  if (/flux-2-klein/i.test(id)) return true;
189
199
  if (/flux-3\/klein\/(base\/)?text-to-image/i.test(id)) return true;
190
200
  if (/minimax-h3\/(text-to-image|image-edit)/i.test(id)) return true;
201
+ if (/p-h3-image/i.test(id)) return true; // Pruna P-H3 Image (2026-11-05): lora_url_1..3
191
202
  return /(^|[-\/])lora($|[-\/])/i.test(id);
192
203
  }
193
204
 
@@ -201,7 +212,7 @@ function modelTakesLora(kind, id) {
201
212
  function loraCap(model) {
202
213
  switch (loraFamily(model)) {
203
214
  case "flux2dev": return 4;
204
- case "flux2klein": case "zimage": case "ltx": case "krea": case "h3": case "anima": case "qwen21": return 3;
215
+ case "flux2klein": case "zimage": case "ltx": case "krea": case "h3": case "anima": case "qwen21": case "ph3": return 3;
205
216
  default: return 1; // flux-lora, pimage — single slot
206
217
  }
207
218
  }
@@ -217,7 +228,7 @@ function nodeLoras(n) {
217
228
  function loraBodyFor(model, items) {
218
229
  const fam = loraFamily(model), sc = (v) => (isNaN(v) ? 1 : v);
219
230
  if (fam === "pimage") return { lora_weights: items[0].url, lora_scale: sc(items[0].scale) };
220
- if (fam === "flux2dev" || fam === "flux2klein" || fam === "zimage" || fam === "ltx" || fam === "krea" || fam === "h3" || fam === "anima" || fam === "qwen21") {
231
+ if (fam === "flux2dev" || fam === "flux2klein" || fam === "zimage" || fam === "ltx" || fam === "krea" || fam === "h3" || fam === "anima" || fam === "qwen21" || fam === "ph3") {
221
232
  const b = {};
222
233
  items.forEach((it, i) => { b["lora_url_" + (i + 1)] = it.url; b["lora_scale_" + (i + 1)] = sc(it.scale); });
223
234
  return b;
@@ -336,6 +347,7 @@ function refMaxFor(model, pricing) {
336
347
  const id = String(model || "");
337
348
  if (/seedance/i.test(id)) return 9;
338
349
  if (/minimax-h3/i.test(id)) return 9; // upstream cap; the first 5 are included, 6-9 bill extra_reference_image each
350
+ if (/gemini-omni-flash\/v1\.2/i.test(id)) return 6;
339
351
  if (/luma|ray/i.test(id)) return 4;
340
352
  const inc = pricing && +pricing.included_reference_images;
341
353
  if (inc > 0) return inc; // no family entry: the included count is the only number the catalog gives us
@@ -352,8 +364,12 @@ function modelRefSpec(model, ctx) {
352
364
  const m = catItem(ctx && ctx.catalog, "video", model);
353
365
  if (!m) return { key: "reference_images", cap: refMaxFor(model) };
354
366
  const sp = m.supported_parameters || {}, pp = sp.parameters || sp;
355
- const key = keys.find((k) => k in pp) || (pricingAdvertisesRefs(m.pricing) ? "reference_images" : null);
356
- if (!key) return null; // known model with no ref-image param and no ref pricing
367
+ const modeOptions = pp.mode && pp.mode.options;
368
+ const referenceMode = Array.isArray(modeOptions) && modeOptions.some((o) =>
369
+ o && /^reference\b/i.test(String(o.value != null ? o.value : "")));
370
+ const key = keys.find((k) => k in pp) ||
371
+ (referenceMode || pricingAdvertisesRefs(m.pricing) ? "reference_images" : null);
372
+ if (!key) return null; // known model with no ref-image param, reference mode, or ref pricing
357
373
  const d = pp[key];
358
374
  let cap = null;
359
375
  if (d && typeof d === "object") {
@@ -683,8 +699,7 @@ export const RUNNERS = {
683
699
  imgs = await Promise.all(imgs.map((u) => fitImage(u, ctx, "source image")));
684
700
  guardRefsSize(imgs);
685
701
  const src = imgs.length > 1 ? imgs : imgs[0]; // array → multi-image composite; string → single edit
686
- const urls = await ctx.image({ prompt, model: mdl(n), size: n.fields.size || "1024x1024", imageDataUrl: src, extra: imgExtra(n), multi: true });
687
- return { image: keptFirst(urls, ctx) };
702
+ return multiOut(await ctx.image({ prompt, model: mdl(n), size: n.fields.size || "1024x1024", imageDataUrl: src, extra: imgExtra(n), multi: true, items: true }));
688
703
  },
689
704
 
690
705
  async inpaint(n, inp, ctx) {
@@ -697,8 +712,7 @@ export const RUNNERS = {
697
712
  // ctx.maskToSource lets a browser host inject its canvas compositor (handles JPEG/WebP
698
713
  // sources the pure-PNG path can't, where ffmpeg isn't an option).
699
714
  const mask = await (ctx.maskToSource || maskToSource)(rawMask, source, mediaOpts(ctx));
700
- const urls = await ctx.image({ prompt, model: mdl(n), size: n.fields.size || "1024x1024", imageDataUrl: source, maskDataUrl: mask, extra: imgExtra(n), multi: true });
701
- return { image: keptFirst(urls, ctx) };
715
+ return multiOut(await ctx.image({ prompt, model: mdl(n), size: n.fields.size || "1024x1024", imageDataUrl: source, maskDataUrl: mask, extra: imgExtra(n), multi: true, items: true }));
702
716
  },
703
717
 
704
718
  async tvideo(n, inp, ctx) {
@@ -774,7 +788,7 @@ export const RUNNERS = {
774
788
  } catch (e) {
775
789
  if (attempt > 0) throw e;
776
790
  const msg = (e && e.message) || "";
777
- if (/^video failed:/i.test(msg)) throw e; // post-submit poll failure: already charged — no second job
791
+ if ((e && e.runId != null) || /^video failed:/i.test(msg)) throw e; // post-submit poll failure: already charged — no second job
778
792
  const cap = /up to\s+(\d+(?:\.\d+)?)\s*second/i.exec(msg);
779
793
  if (cap && /INVALID_AUDIO_DURATION|audio.{0,15}duration/i.test(msg)) {
780
794
  trimSec = Math.min(60, Math.max(1, parseFloat(cap[1]) - 0.1)); // the model told us its real cap
@@ -823,24 +837,33 @@ export const RUNNERS = {
823
837
  return cleanVoiceRun(model, inp, n.fields, (m, extra) => ctx.audio(m, "", extra));
824
838
  },
825
839
 
826
- // 🧊 3D model: image and/or text → GLB via the video submit/poll API (mediaKind model3d).
840
+ // 🧊 3D model: image and/or text → model asset via the video submit/poll API.
841
+ // Mesh-processing models (e.g. Hyper3D Rigging) instead take an existing
842
+ // model on the `model` wire and receive it as the `model_url` parameter.
827
843
  async model3d(n, inp, ctx) {
828
844
  const model = String((n.fields && n.fields.model) || "").trim() || MODEL3D_IMAGE_DEFAULT;
829
845
  const mods = model3dInputMods(ctx && ctx.catalog, model);
830
846
  const prompt = promptOf(n, inp);
831
847
  let image = mods.image ? (inp.image || "") : "";
848
+ const mesh = mods.mesh ? (inp.model || "") : "";
832
849
  if (inp.image && !mods.image && ctx && ctx.progress) {
833
850
  ctx.progress("This model takes text only — the image wire stays, but this run ignores it.");
834
851
  }
852
+ if (inp.model && !mods.mesh && ctx && ctx.progress) {
853
+ ctx.progress("This model generates from scratch — the model wire stays, but this run ignores it.");
854
+ }
835
855
  if (prompt && !mods.text && ctx && ctx.progress) {
836
856
  ctx.progress("This model takes an image only — the prompt stays, but this run ignores it.");
837
857
  }
838
- if (mods.image && !mods.text && !image) throw new NanoodleError("Connect an image first.");
839
- if (mods.text && !mods.image && !prompt) throw new NanoodleError("Add a prompt first.");
840
- if (mods.image && mods.text && !image && !prompt) throw new NanoodleError("Add a prompt or connect an image first.");
858
+ if (mods.mesh && !mesh) throw new NanoodleError("Connect a model first.");
859
+ if (!mods.mesh && mods.image && !mods.text && !image) throw new NanoodleError("Connect an image first.");
860
+ if (!mods.mesh && mods.text && !mods.image && !prompt) throw new NanoodleError("Add a prompt first.");
861
+ if (!mods.mesh && mods.image && mods.text && !image && !prompt) throw new NanoodleError("Add a prompt or connect an image first.");
841
862
  if (image) image = await fitImage(image, ctx, "source image");
863
+ const extra = { ...(n.fields.modelOpts || {}) };
864
+ if (mesh) extra.model_url = mesh; // the wire wins over a static modelOpts copy
842
865
  const url = await ctx.video(model, mods.text ? prompt : "", {
843
- extra: n.fields.modelOpts || {},
866
+ extra,
844
867
  mediaKind: "model3d",
845
868
  }, image || null);
846
869
  return { model: url };
@@ -887,10 +910,10 @@ function model3dInputMods(catalog, id) {
887
910
  || (it.architecture && Array.isArray(it.architecture.input_modalities) && it.architecture.input_modalities)
888
911
  );
889
912
  if (raw && raw.length) {
890
- const mods = raw.filter((x) => x === "image" || x === "text");
891
- if (mods.length) return { image: mods.includes("image"), text: mods.includes("text") };
913
+ const mods = raw.filter((x) => x === "image" || x === "text" || x === "3d");
914
+ if (mods.length) return { image: mods.includes("image"), text: mods.includes("text"), mesh: mods.includes("3d") };
892
915
  }
893
- if (id === MODEL3D_IMAGE_DEFAULT) return { image: true, text: false };
894
- if (id === MODEL3D_TEXT_DEFAULT) return { image: true, text: true };
895
- return { image: true, text: true };
916
+ if (id === MODEL3D_IMAGE_DEFAULT) return { image: true, text: false, mesh: false };
917
+ if (id === MODEL3D_TEXT_DEFAULT) return { image: true, text: true, mesh: false };
918
+ return { image: true, text: true, mesh: false };
896
919
  }
package/src/workflow.mjs CHANGED
@@ -7,6 +7,7 @@ import { MediaRef, coerceMediaInput } from "./media.mjs";
7
7
  import { RUNNERS } from "./nodes.mjs";
8
8
  import { learnPromptCap, withFittedPrompt } from "./prompt-caps.mjs";
9
9
  import { decodeShareUrl, isShareRef } from "./share.mjs";
10
+ import { isBranchDecider, planBranches } from "./branches.mjs";
10
11
 
11
12
  /** Env / process access — safe when `process` is missing (browsers, some workers). */
12
13
  function envApiKey() {
@@ -101,6 +102,18 @@ function throwIfAborted(signal) {
101
102
  if (signal && signal.aborted) throw abortReason(signal);
102
103
  }
103
104
 
105
+ /** Bound an async stage even when injected I/O ignores AbortSignal. Always observe late rejection. */
106
+ function withSignal(work, signal) {
107
+ return new Promise((resolve, reject) => {
108
+ const onAbort = () => reject(abortReason(signal));
109
+ signal.addEventListener("abort", onAbort, { once: true });
110
+ Promise.resolve().then(() => {
111
+ throwIfAborted(signal);
112
+ return work();
113
+ }).then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
114
+ });
115
+ }
116
+
104
117
  /** The outcome of Workflow.run(). Media values are MediaRef; text values plain strings. */
105
118
  /** Internal: thrown by a node skipped behind a closed gate, so ITS dependents skip too. Never surfaced. */
106
119
  class GateSkip extends Error {
@@ -112,7 +125,9 @@ export class RunResult {
112
125
  /** { [friendlyKey | nodeId]: value } — sink node primary outputs (a sink skipped by a closed gate has none) */
113
126
  this.outputs = outputs;
114
127
  /**
115
- * per-node { status: "done"|"error"|"gated"|"skipped", out, error, costUsd, ms }.
128
+ * per-node { status: "done"|"error"|"gated"|"skipped", out, error, costUsd, ms, runId }.
129
+ * runId: the provider's async video/3D/audio job ID, or null when none was returned.
130
+ * Retained on failure/timeout too, so an accepted job can be traced without resubmitting.
116
131
  * "gated": a ⚖️ Decide yes/no gate that answered no — it ran and billed, `out` holds its answer
117
132
  * ({ text: "no", decision }), and it carries `gate: { yes, message }`. Not an error.
118
133
  * "skipped" + `gatedBy: <decide node id>`: downstream of a closed gate — never ran, never billed.
@@ -278,6 +293,7 @@ export class Workflow {
278
293
  }
279
294
 
280
295
  const order = topoSort(graph); // throws naming cyclic nodes
296
+ const branches = planBranches(graph, order.map(n => n.id));
281
297
 
282
298
  // Local-only graphs never POST media — skip the ~4 MB inline cap on inputs.
283
299
  // Mixed/network graphs keep the cap so we fail before spending on an oversize body.
@@ -336,7 +352,7 @@ export class Workflow {
336
352
  }
337
353
 
338
354
  const emit = (evt) => { if (onProgress) { try { onProgress(evt); } catch { /* listener errors never kill the run */ } } };
339
- const nodesRec = {};
355
+ const nodesRec = Object.fromEntries(graph.nodes.map(n => [n.id, null]));
340
356
  const errors = [];
341
357
  const cost = { total: 0, exact: true, balance: null };
342
358
  const byId = new Map(graph.nodes.map((n) => [n.id, n]));
@@ -355,7 +371,14 @@ export class Workflow {
355
371
  if (c.balance != null) cost.balance = c.balance;
356
372
  };
357
373
  const onPoll = (info) => frozen(rec) ? undefined : emit({ type: "poll", nodeId: node.id, name: displayName(node), ...info });
358
- const io = { onCost, onPoll, signal: nodeSignal };
374
+ const onRunId = (job) => {
375
+ if (frozen(rec)) return;
376
+ const runId = job && typeof job === "object" ? (job.runId || job.id) : job;
377
+ if (runId == null) return;
378
+ rec.runId = runId;
379
+ emit({ type: "node-run-id", nodeId: node.id, name: displayName(node), runId });
380
+ };
381
+ const io = { onCost, onPoll, onRunId, signal: nodeSignal };
359
382
  return {
360
383
  chat: (messages, model, opts) => this.client.chat(messages, model, opts, io),
361
384
  decide: (body) => this.client.decide(body, io),
@@ -386,7 +409,17 @@ export class Workflow {
386
409
  let nodeTimer = null, unlinkNode = null;
387
410
  try {
388
411
  throwIfAborted(ac.signal);
389
- const inbound = graph.links.filter((l) => l.to.node === n.id);
412
+ let inbound = graph.links.filter((l) => l.to.node === n.id);
413
+ if (branches) {
414
+ await Promise.allSettled(inbound.map(l => promises.get(l.from.node)));
415
+ inbound = branches.activeLinks(n.id, id => nodesRec[id]?.status === "done" ? nodesRec[id].out : null);
416
+ if (inbound === null) {
417
+ rec.status = "skipped";
418
+ rec.skipReason = "branch";
419
+ emit({ type: "node-skipped", nodeId: n.id, name: displayName(n), reason: "branch" });
420
+ return {};
421
+ }
422
+ }
390
423
  const inp = {};
391
424
  let fields = effFields.get(n.id);
392
425
  let upstreamFail = null, gatedBy = null, skippedIn = 0;
@@ -407,7 +440,7 @@ export class Workflow {
407
440
  // resolved (authed redirect → absolute file URL, or inlined bytes)
408
441
  // before this node builds videoUrl / videoDataUrl / audio / image.
409
442
  inp[l.to.port] = (typeof v === "string" && v && HANDED_MEDIA_PORT.test(l.to.port))
410
- ? await this.client.resolveContentUrl(v, { signal: ac.signal })
443
+ ? await withSignal(() => this.client.resolveContentUrl(v, { signal: ac.signal }), ac.signal)
411
444
  : v;
412
445
  }
413
446
  // Custom endpoint url/mode: a Choice path like "/post" must ride inp so
@@ -441,6 +474,7 @@ export class Workflow {
441
474
  // prompt at the route, and in a graph the prompt is WRITTEN by an upstream LLM — so a
442
475
  // caller has nothing to shorten. Trim it to fit rather than send a request certain to 400,
443
476
  // and report it below. The graph's own prompts are never rewritten to avoid this.
477
+ if (n.type === "decide" && fields.branch !== n.fields.branch) fields = { ...fields, branch: n.fields.branch };
444
478
  const fit = withFittedPrompt(n, fields, { catalog: this.catalog, learned: this._promptCaps });
445
479
  fields = fit.fields;
446
480
  rec.started = true;
@@ -451,34 +485,28 @@ export class Workflow {
451
485
  warnGraph(`node ${n.id}: prompt trimmed ${fit.trimmed.from} → ${fit.trimmed.to} characters — ` +
452
486
  `${fields.model} rejects prompts over ${fit.trimmed.cap}`);
453
487
  }
488
+ throwIfAborted(ac.signal);
454
489
  const t0 = Date.now();
455
- // Per-node timeout (fields.timeoutMs): a child controller linked to the run signal.
456
- // The race guarantees the deadline even if a runner never observes its signal.
490
+ // The node deadline covers the runner AND publication of provider media.
491
+ // Race every active stage with cancellation so an injected fetch cannot hold the run open.
457
492
  const timeoutMs = Number(fields.timeoutMs);
458
- let nodeSignal = ac.signal, deadline = null;
493
+ let nodeSignal = ac.signal;
459
494
  if (Number.isFinite(timeoutMs) && timeoutMs > 0) {
460
495
  const nac = new AbortController();
461
496
  const onRunAbort = () => nac.abort(ac.signal.reason);
462
497
  ac.signal.addEventListener("abort", onRunAbort, { once: true });
463
498
  unlinkNode = () => ac.signal.removeEventListener("abort", onRunAbort);
464
499
  nodeSignal = nac.signal;
465
- deadline = new Promise((_, reject) => {
466
- nodeTimer = setTimeout(() => {
467
- const err = new NanoodleError(`node timed out after ${timeoutMs}ms`, { code: "timeout" });
468
- nac.abort(err);
469
- reject(err);
470
- }, timeoutMs);
471
- });
472
- deadline.catch(() => {});
500
+ nodeTimer = setTimeout(() => nac.abort(new NanoodleError(
501
+ `node timed out after ${timeoutMs}ms`, { code: "timeout" })), timeoutMs);
473
502
  }
474
503
  const nodeForRun = { ...n, fields };
475
- const work = RUNNERS[n.type](nodeForRun, inp, ctxFor(n, rec, nodeSignal));
476
- const rawOut = deadline ? await Promise.race([work, deadline]) : await work;
477
- if (deadline) throwIfAborted(nodeSignal);
478
- throwIfAborted(ac.signal);
479
- // Final outputs of this node are absolute usable URLs, not the relative
480
- // content path the provider returned. Downstream reads this same object.
481
- const out = await publishNodeMedia(this.client, nodeForRun, rawOut, nodeSignal);
504
+ const out = await withSignal(async () => {
505
+ const rawOut = await RUNNERS[n.type](nodeForRun, inp, ctxFor(n, rec, nodeSignal));
506
+ throwIfAborted(nodeSignal);
507
+ return publishNodeMedia(this.client, nodeForRun, rawOut, nodeSignal);
508
+ }, nodeSignal);
509
+ throwIfAborted(nodeSignal);
482
510
  throwIfAborted(ac.signal);
483
511
  rec.final = true;
484
512
  rec.status = "done";
@@ -509,7 +537,7 @@ export class Workflow {
509
537
  // fields.onError:"skip" — a failed (or timed-out) node is recorded and skipped; its
510
538
  // dependents see undefined ports. A run-level abort/timeout is never skipped.
511
539
  const onError = (effFields.get(n.id) || {}).onError;
512
- if (onError === "skip" && !ac.signal.aborted) {
540
+ if (onError === "skip" && !isBranchDecider(n) && !ac.signal.aborted) {
513
541
  rec.status = "skipped";
514
542
  rec.skippedOnError = true;
515
543
  rec.out = {};
@@ -527,8 +555,8 @@ export class Workflow {
527
555
 
528
556
  try {
529
557
  for (const n of order) {
530
- if (NODE_TYPES[n.type].note) { nodesRec[n.id] = { status: "skipped", out: null, error: null, costUsd: null, ms: null }; continue; }
531
- nodesRec[n.id] = { status: "pending", out: null, error: null, costUsd: null, ms: null };
558
+ if (NODE_TYPES[n.type].note) { nodesRec[n.id] = { status: "skipped", out: null, error: null, costUsd: null, ms: null, runId: null }; continue; }
559
+ nodesRec[n.id] = { status: "pending", out: null, error: null, costUsd: null, ms: null, runId: null };
532
560
  promises.set(n.id, execNode(n)); // siblings run concurrently; a node starts when ITS deps finish
533
561
  }
534
562
  await Promise.allSettled([...promises.values()]);
@@ -547,15 +575,15 @@ export class Workflow {
547
575
  cost.exact = false;
548
576
  }
549
577
  // ---- result ----
550
- const outputsMap = {};
578
+ const outputEntries = [];
551
579
  for (const o of this.outputs) {
552
580
  const rec = nodesRec[o.nodeId];
553
581
  if (!rec || !(rec.status === "done" || (rec.status === "gated" && rec.out))) continue;
554
582
  const primary = o.ports[0];
555
583
  const value = this._wrapValue(rec.out[primary.name], primary.type);
556
- outputsMap[o.key] = value;
557
- outputsMap[o.nodeId] = value;
584
+ outputEntries.push([o.key, value], [o.nodeId, value]);
558
585
  }
586
+ const outputsMap = Object.fromEntries(outputEntries);
559
587
  const result = new RunResult({
560
588
  outputs: outputsMap,
561
589
  nodes: nodesRec,
package/src/x402.mjs CHANGED
@@ -71,7 +71,14 @@ export function parseNanoInvoice(body, baseUrl) {
71
71
 
72
72
  const RESULT_KEYS = ["choices", "data", "output", "runId", "url", "audioUrl", "transcription", "text"];
73
73
 
74
- /** Does a complete-endpoint body already carry the replayed API result? */
74
+ /**
75
+ * Does a complete-endpoint body already carry the replayed API result?
76
+ * A paid decision comes back as { answers, usage }. That is success. Treating
77
+ * it as a bare receipt makes the client resend the original request, and the
78
+ * API answers 402 because the payment was already consumed.
79
+ */
75
80
  export function looksLikeResult(j) {
76
- return !!j && typeof j === "object" && RESULT_KEYS.some((k) => j[k] != null);
81
+ if (!j || typeof j !== "object") return false;
82
+ if (RESULT_KEYS.some((k) => j[k] != null)) return true;
83
+ return j.answers != null && j.usage != null && typeof j.usage === "object";
77
84
  }
@@ -31,7 +31,7 @@
31
31
  "x": 650,
32
32
  "y": 100,
33
33
  "fields": {
34
- "model": "nano-banana-2-lite",
34
+ "model": "nano-banana-2-fast",
35
35
  "size": "1k",
36
36
  "variations": "1"
37
37
  },