nanoodle 0.13.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/README.md +64 -1
- package/bin/nanoodle.mjs +14 -4
- package/package.json +2 -2
- package/src/branches.mjs +55 -0
- package/src/browser.mjs +1 -0
- package/src/client.mjs +161 -73
- package/src/decide.mjs +12 -1
- package/src/errors.mjs +1 -1
- package/src/estimate.mjs +171 -29
- package/src/graph.mjs +7 -2
- package/src/index.mjs +1 -0
- package/src/io.mjs +14 -13
- package/src/local-media.mjs +19 -26
- package/src/media.mjs +66 -19
- package/src/nodes.mjs +35 -16
- package/src/workflow.mjs +57 -29
- package/src/x402.mjs +9 -2
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
|
-
/**
|
|
157
|
-
async bytes() {
|
|
158
|
-
|
|
159
|
-
let
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
@@ -129,7 +129,10 @@ function audioInputPart(url) {
|
|
|
129
129
|
function llmOpts(n) {
|
|
130
130
|
const f = n.fields, o = {};
|
|
131
131
|
if (f.temperature != null && f.temperature !== "") o.temperature = +f.temperature;
|
|
132
|
-
|
|
132
|
+
// maxTokens is opt-in (D1 ruling, 2026-11-18): absent by default, honored
|
|
133
|
+
// exactly when the node sets it — twin of nanoodle-py _run_llm (truthy +
|
|
134
|
+
// numeric → int(float(v)); non-numeric degrades gracefully, sends nothing).
|
|
135
|
+
if (f.maxTokens && Number.isFinite(+f.maxTokens)) o.max_tokens = Math.trunc(+f.maxTokens);
|
|
133
136
|
if (f.format === "JSON") o.response_format = { type: "json_object" };
|
|
134
137
|
if (f.reasoningEffort && f.reasoningEffort !== "default") o.reasoning_effort = f.reasoningEffort;
|
|
135
138
|
if (f.showThinking === true || f.showThinking === "true") o.showThinking = true;
|
|
@@ -165,6 +168,7 @@ function normalizeLoraUrl(raw) {
|
|
|
165
168
|
function loraFamily(model) {
|
|
166
169
|
const m = String(model || "");
|
|
167
170
|
if (/spicy/i.test(m)) return null;
|
|
171
|
+
if (/p-h3-image/i.test(m)) return "ph3"; // wavespeed p-h3-image: lora_url_1..3 (ids lack "lora")
|
|
168
172
|
if (/p-image/i.test(m)) return "pimage";
|
|
169
173
|
if (/klein/i.test(m)) return "flux2klein";
|
|
170
174
|
if (/flux-2/i.test(m)) return "flux2dev";
|
|
@@ -188,6 +192,7 @@ function imageTakesLora(id) {
|
|
|
188
192
|
if (/flux-2-klein/i.test(id)) return true;
|
|
189
193
|
if (/flux-3\/klein\/(base\/)?text-to-image/i.test(id)) return true;
|
|
190
194
|
if (/minimax-h3\/(text-to-image|image-edit)/i.test(id)) return true;
|
|
195
|
+
if (/p-h3-image/i.test(id)) return true; // Pruna P-H3 Image (2026-11-05): lora_url_1..3
|
|
191
196
|
return /(^|[-\/])lora($|[-\/])/i.test(id);
|
|
192
197
|
}
|
|
193
198
|
|
|
@@ -201,7 +206,7 @@ function modelTakesLora(kind, id) {
|
|
|
201
206
|
function loraCap(model) {
|
|
202
207
|
switch (loraFamily(model)) {
|
|
203
208
|
case "flux2dev": return 4;
|
|
204
|
-
case "flux2klein": case "zimage": case "ltx": case "krea": case "h3": case "anima": case "qwen21": return 3;
|
|
209
|
+
case "flux2klein": case "zimage": case "ltx": case "krea": case "h3": case "anima": case "qwen21": case "ph3": return 3;
|
|
205
210
|
default: return 1; // flux-lora, pimage — single slot
|
|
206
211
|
}
|
|
207
212
|
}
|
|
@@ -217,7 +222,7 @@ function nodeLoras(n) {
|
|
|
217
222
|
function loraBodyFor(model, items) {
|
|
218
223
|
const fam = loraFamily(model), sc = (v) => (isNaN(v) ? 1 : v);
|
|
219
224
|
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") {
|
|
225
|
+
if (fam === "flux2dev" || fam === "flux2klein" || fam === "zimage" || fam === "ltx" || fam === "krea" || fam === "h3" || fam === "anima" || fam === "qwen21" || fam === "ph3") {
|
|
221
226
|
const b = {};
|
|
222
227
|
items.forEach((it, i) => { b["lora_url_" + (i + 1)] = it.url; b["lora_scale_" + (i + 1)] = sc(it.scale); });
|
|
223
228
|
return b;
|
|
@@ -336,6 +341,7 @@ function refMaxFor(model, pricing) {
|
|
|
336
341
|
const id = String(model || "");
|
|
337
342
|
if (/seedance/i.test(id)) return 9;
|
|
338
343
|
if (/minimax-h3/i.test(id)) return 9; // upstream cap; the first 5 are included, 6-9 bill extra_reference_image each
|
|
344
|
+
if (/gemini-omni-flash\/v1\.2/i.test(id)) return 6;
|
|
339
345
|
if (/luma|ray/i.test(id)) return 4;
|
|
340
346
|
const inc = pricing && +pricing.included_reference_images;
|
|
341
347
|
if (inc > 0) return inc; // no family entry: the included count is the only number the catalog gives us
|
|
@@ -352,8 +358,12 @@ function modelRefSpec(model, ctx) {
|
|
|
352
358
|
const m = catItem(ctx && ctx.catalog, "video", model);
|
|
353
359
|
if (!m) return { key: "reference_images", cap: refMaxFor(model) };
|
|
354
360
|
const sp = m.supported_parameters || {}, pp = sp.parameters || sp;
|
|
355
|
-
const
|
|
356
|
-
|
|
361
|
+
const modeOptions = pp.mode && pp.mode.options;
|
|
362
|
+
const referenceMode = Array.isArray(modeOptions) && modeOptions.some((o) =>
|
|
363
|
+
o && /^reference\b/i.test(String(o.value != null ? o.value : "")));
|
|
364
|
+
const key = keys.find((k) => k in pp) ||
|
|
365
|
+
(referenceMode || pricingAdvertisesRefs(m.pricing) ? "reference_images" : null);
|
|
366
|
+
if (!key) return null; // known model with no ref-image param, reference mode, or ref pricing
|
|
357
367
|
const d = pp[key];
|
|
358
368
|
let cap = null;
|
|
359
369
|
if (d && typeof d === "object") {
|
|
@@ -774,7 +784,7 @@ export const RUNNERS = {
|
|
|
774
784
|
} catch (e) {
|
|
775
785
|
if (attempt > 0) throw e;
|
|
776
786
|
const msg = (e && e.message) || "";
|
|
777
|
-
if (/^video failed:/i.test(msg)) throw e; // post-submit poll failure: already charged — no second job
|
|
787
|
+
if ((e && e.runId != null) || /^video failed:/i.test(msg)) throw e; // post-submit poll failure: already charged — no second job
|
|
778
788
|
const cap = /up to\s+(\d+(?:\.\d+)?)\s*second/i.exec(msg);
|
|
779
789
|
if (cap && /INVALID_AUDIO_DURATION|audio.{0,15}duration/i.test(msg)) {
|
|
780
790
|
trimSec = Math.min(60, Math.max(1, parseFloat(cap[1]) - 0.1)); // the model told us its real cap
|
|
@@ -823,24 +833,33 @@ export const RUNNERS = {
|
|
|
823
833
|
return cleanVoiceRun(model, inp, n.fields, (m, extra) => ctx.audio(m, "", extra));
|
|
824
834
|
},
|
|
825
835
|
|
|
826
|
-
// 🧊 3D model: image and/or text →
|
|
836
|
+
// 🧊 3D model: image and/or text → model asset via the video submit/poll API.
|
|
837
|
+
// Mesh-processing models (e.g. Hyper3D Rigging) instead take an existing
|
|
838
|
+
// model on the `model` wire and receive it as the `model_url` parameter.
|
|
827
839
|
async model3d(n, inp, ctx) {
|
|
828
840
|
const model = String((n.fields && n.fields.model) || "").trim() || MODEL3D_IMAGE_DEFAULT;
|
|
829
841
|
const mods = model3dInputMods(ctx && ctx.catalog, model);
|
|
830
842
|
const prompt = promptOf(n, inp);
|
|
831
843
|
let image = mods.image ? (inp.image || "") : "";
|
|
844
|
+
const mesh = mods.mesh ? (inp.model || "") : "";
|
|
832
845
|
if (inp.image && !mods.image && ctx && ctx.progress) {
|
|
833
846
|
ctx.progress("This model takes text only — the image wire stays, but this run ignores it.");
|
|
834
847
|
}
|
|
848
|
+
if (inp.model && !mods.mesh && ctx && ctx.progress) {
|
|
849
|
+
ctx.progress("This model generates from scratch — the model wire stays, but this run ignores it.");
|
|
850
|
+
}
|
|
835
851
|
if (prompt && !mods.text && ctx && ctx.progress) {
|
|
836
852
|
ctx.progress("This model takes an image only — the prompt stays, but this run ignores it.");
|
|
837
853
|
}
|
|
838
|
-
if (mods.
|
|
839
|
-
if (mods.
|
|
840
|
-
if (mods.
|
|
854
|
+
if (mods.mesh && !mesh) throw new NanoodleError("Connect a model first.");
|
|
855
|
+
if (!mods.mesh && mods.image && !mods.text && !image) throw new NanoodleError("Connect an image first.");
|
|
856
|
+
if (!mods.mesh && mods.text && !mods.image && !prompt) throw new NanoodleError("Add a prompt first.");
|
|
857
|
+
if (!mods.mesh && mods.image && mods.text && !image && !prompt) throw new NanoodleError("Add a prompt or connect an image first.");
|
|
841
858
|
if (image) image = await fitImage(image, ctx, "source image");
|
|
859
|
+
const extra = { ...(n.fields.modelOpts || {}) };
|
|
860
|
+
if (mesh) extra.model_url = mesh; // the wire wins over a static modelOpts copy
|
|
842
861
|
const url = await ctx.video(model, mods.text ? prompt : "", {
|
|
843
|
-
extra
|
|
862
|
+
extra,
|
|
844
863
|
mediaKind: "model3d",
|
|
845
864
|
}, image || null);
|
|
846
865
|
return { model: url };
|
|
@@ -887,10 +906,10 @@ function model3dInputMods(catalog, id) {
|
|
|
887
906
|
|| (it.architecture && Array.isArray(it.architecture.input_modalities) && it.architecture.input_modalities)
|
|
888
907
|
);
|
|
889
908
|
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") };
|
|
909
|
+
const mods = raw.filter((x) => x === "image" || x === "text" || x === "3d");
|
|
910
|
+
if (mods.length) return { image: mods.includes("image"), text: mods.includes("text"), mesh: mods.includes("3d") };
|
|
892
911
|
}
|
|
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 };
|
|
912
|
+
if (id === MODEL3D_IMAGE_DEFAULT) return { image: true, text: false, mesh: false };
|
|
913
|
+
if (id === MODEL3D_TEXT_DEFAULT) return { image: true, text: true, mesh: false };
|
|
914
|
+
return { image: true, text: true, mesh: false };
|
|
896
915
|
}
|
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
|
|
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
|
-
|
|
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
|
-
//
|
|
456
|
-
//
|
|
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
|
|
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
|
-
|
|
466
|
-
|
|
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
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
}
|