nanoodle 0.1.1 → 0.4.0

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/workflow.mjs CHANGED
@@ -1,13 +1,42 @@
1
- import { readFile } from "node:fs/promises";
2
1
  import { NanoodleError, RunError, UnsupportedNodeError } from "./errors.mjs";
3
- import { NODE_TYPES, displayName, isInputPort, materialize, topoSort } from "./graph.mjs";
2
+ import { NODE_TYPES, displayName, isInputPort, materialize, topoSort, wiredFramesFloor, MAX_FRAMES } from "./graph.mjs";
4
3
  import { deriveInputs, deriveOutputs, deriveSettings, resolveInputKey, resolveSettingKey } from "./io.mjs";
5
4
  import { NanoClient } from "./client.mjs";
6
5
  import { MediaRef, coerceMediaInput } from "./media.mjs";
7
- import { RUNNERS, unsupportedNodeError } from "./nodes.mjs";
6
+ import { RUNNERS } from "./nodes.mjs";
7
+ import { decodeShareUrl, isShareRef } from "./share.mjs";
8
+
9
+ /** Env / process access — safe when `process` is missing (browsers, some workers). */
10
+ function envApiKey() {
11
+ try {
12
+ return typeof process !== "undefined" && process.env ? process.env.NANOGPT_API_KEY : undefined;
13
+ } catch {
14
+ return undefined;
15
+ }
16
+ }
17
+
18
+ function warnGraph(msg) {
19
+ try {
20
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
21
+ process.emitWarning(msg, { code: "NANOODLE_GRAPH" });
22
+ return;
23
+ }
24
+ } catch { /* ignore */ }
25
+ if (typeof console !== "undefined" && console.warn) console.warn("[nanoodle]", msg);
26
+ }
8
27
 
9
28
  const MEDIA_KINDS = new Set(["image", "audio", "video", "inpaint"]);
10
29
 
30
+ function abortReason(signal) {
31
+ const r = signal && signal.reason;
32
+ if (r instanceof Error) return r;
33
+ return new NanoodleError(r != null ? String(r) : "run aborted", { code: "aborted" });
34
+ }
35
+
36
+ function throwIfAborted(signal) {
37
+ if (signal && signal.aborted) throw abortReason(signal);
38
+ }
39
+
11
40
  /** The outcome of Workflow.run(). Media values are MediaRef; text values plain strings. */
12
41
  export class RunResult {
13
42
  constructor({ outputs, nodes, errors, costUsd, costExact, remainingBalance }) {
@@ -46,19 +75,24 @@ function isPlainObject(v) {
46
75
  export class Workflow {
47
76
  /**
48
77
  * @param {object} graphData parsed noodle-graph.json
49
- * @param {{ apiKey?, baseUrl?, fetch?, pollIntervals?, timeouts?, quiet? }} [opts]
78
+ * @param {{ apiKey?, payment?, baseUrl?, fetch?, pollIntervals?, timeouts?, quiet?, catalog? }} [opts]
79
+ * catalog: opt-in raw model-catalog arrays ({ chat, image, video, audio }) enabling
80
+ * the same payload gates play RUNTIME_JS applies (see src/catalog.mjs) — data only,
81
+ * never fetched by the library
50
82
  */
51
83
  constructor(graphData, opts = {}) {
52
84
  const { nodes, links, warnings } = materialize(graphData);
53
85
  this.graph = { nodes, links };
86
+ this.catalog = opts.catalog || null;
54
87
  /** Load-time warnings (unknown / unsupported node types). load() only warns; run() fails fast. */
55
88
  this.warnings = warnings;
56
89
  this.client = new NanoClient({
57
- apiKey: opts.apiKey !== undefined ? opts.apiKey : process.env.NANOGPT_API_KEY,
90
+ apiKey: opts.apiKey !== undefined ? opts.apiKey : envApiKey(),
58
91
  baseUrl: opts.baseUrl,
59
92
  fetch: opts.fetch,
60
93
  pollIntervals: opts.pollIntervals,
61
94
  timeouts: opts.timeouts,
95
+ payment: opts.payment, // accountless x402: a callback that sends the Nano invoice (never a seed)
62
96
  });
63
97
  /** [{ key, nodeId, field, kind, label, optional, def, options? }] */
64
98
  this.inputs = deriveInputs(this.graph);
@@ -67,13 +101,30 @@ export class Workflow {
67
101
  /** [{ key, nodeId, field, kind, def, options? }] */
68
102
  this.settings = deriveSettings(this.graph);
69
103
  if (warnings.length && !opts.quiet) {
70
- for (const w of warnings) process.emitWarning(w, { code: "NANOODLE_GRAPH" });
104
+ for (const w of warnings) warnGraph(w);
71
105
  }
72
106
  }
73
107
 
74
- /** Load a downloaded noodle-graph.json save from disk. */
75
- static async load(path, opts = {}) {
76
- return Workflow.fromJSON(await readFile(path, "utf8"), opts);
108
+ /**
109
+ * Load a workflow from a noodle-graph.json file on disk, or from any nanoodle
110
+ * share link — a full URL (nanoodle.com/#g=…, /play.html#a=…, a da.gd/TinyURL
111
+ * short link) or a bare #g=/#j=/#a= fragment. Direct fragment links decode
112
+ * offline; only fragment-less short links touch the network (redirect-header
113
+ * reads, no credentials attached).
114
+ *
115
+ * File paths use Node's `fs` (dynamic import). In browsers, pass a parsed
116
+ * object / JSON string to `Workflow.fromJSON`, or a share URL/fragment.
117
+ */
118
+ static async load(src, opts = {}) {
119
+ if (isShareRef(src)) {
120
+ const { graph } = await decodeShareUrl(src, { fetch: opts.fetch });
121
+ return new Workflow(graph, opts);
122
+ }
123
+ if (typeof src === "string" && /^\s*[\[{]/.test(src)) {
124
+ return Workflow.fromJSON(src, opts);
125
+ }
126
+ const { readFile } = await import("node:fs/promises");
127
+ return Workflow.fromJSON(await readFile(src, "utf8"), opts);
77
128
  }
78
129
 
79
130
  /** Build from a parsed object or a JSON string. */
@@ -86,11 +137,14 @@ export class Workflow {
86
137
  * Execute the whole graph.
87
138
  * @param {object|string|Uint8Array|MediaRef} inputs friendly-keyed values, or a bare scalar
88
139
  * when the workflow has exactly one required input
89
- * @param {{ settings?, timeoutMs?, signal?, onProgress? }} [runOpts]
140
+ * @param {{ settings?, defaults?, timeoutMs?, signal?, onProgress? }} [runOpts]
141
+ * defaults: false treats graph fields as authoritative — no def backfill for
142
+ * unsupplied inputs (the play UI materializes defs into fields itself, so a
143
+ * deliberately blank field must stay blank when it delegates to this engine)
90
144
  * @returns {Promise<RunResult>} rejects with RunError (carrying .result) when a sink failed
91
145
  */
92
146
  async run(inputs = {}, runOpts = {}) {
93
- const { settings = {}, timeoutMs, signal, onProgress } = runOpts;
147
+ const { settings = {}, defaults = true, timeoutMs, signal, onProgress } = runOpts;
94
148
  const graph = this.graph;
95
149
 
96
150
  // bare scalar → the single required input
@@ -116,18 +170,22 @@ export class Workflow {
116
170
  settingAssignments.push({ entry, value });
117
171
  }
118
172
 
119
- // unsupported / unknown node types fail fast — before any network call
173
+ // unknown node types fail fast — before any network call
120
174
  for (const n of graph.nodes) {
121
175
  if (n.unknown) {
122
176
  throw new UnsupportedNodeError(
123
177
  `node ${n.id}: unknown node type '${n.type}' — this graph needs a newer nanoodle library`,
124
178
  { nodeId: n.id, nodeType: n.type });
125
179
  }
126
- if (NODE_TYPES[n.type].unsupported) throw unsupportedNodeError(n);
127
180
  }
128
181
 
129
182
  const order = topoSort(graph); // throws naming cyclic nodes
130
183
 
184
+ // Local-only graphs never POST media — skip the ~4 MB inline cap on inputs.
185
+ // Mixed/network graphs keep the cap so we fail before spending on an oversize body.
186
+ const hasNetwork = graph.nodes.some((n) => NODE_TYPES[n.type] && NODE_TYPES[n.type].network);
187
+ const mediaCoerceOpts = { enforceInlineMax: hasNetwork };
188
+
131
189
  // effective fields: graph fields + settings overrides + user inputs
132
190
  const effFields = new Map(graph.nodes.map((n) => [n.id, { ...n.fields }]));
133
191
  for (const { entry, value } of settingAssignments) {
@@ -135,9 +193,18 @@ export class Workflow {
135
193
  }
136
194
  const explicit = new Set();
137
195
  for (const { entry, value } of inputAssignments) {
138
- effFields.get(entry.nodeId)[entry.field] = this._coerceInput(entry, value);
196
+ effFields.get(entry.nodeId)[entry.field] = this._coerceInput(entry, value, mediaCoerceOpts);
139
197
  explicit.add(entry);
140
198
  }
199
+ // vframes: raise frames to highest wired frameK (play.html wiredFramesFloor) so a
200
+ // persisted frames=1 with frame3 wired doesn't starve the consumer after paid upstream.
201
+ for (const n of graph.nodes) {
202
+ if (n.type !== "vframes") continue;
203
+ const fields = effFields.get(n.id);
204
+ const floor = wiredFramesFloor(graph, n.id);
205
+ const cur = Math.max(1, Math.min(MAX_FRAMES, parseInt(fields.frames, 10) || 1));
206
+ if (floor > cur) fields.frames = String(floor);
207
+ }
141
208
  // defaults + required check
142
209
  for (const entry of this.inputs) {
143
210
  const fields = effFields.get(entry.nodeId);
@@ -145,17 +212,17 @@ export class Workflow {
145
212
  if (v == null || String(v).trim() === "") {
146
213
  // an EXPLICIT empty value clears an optional input (e.g. run with no system prompt) —
147
214
  // the def only backfills when the key wasn't supplied at all (the app's prefilled textarea)
148
- if (entry.optional && explicit.has(entry)) continue;
149
- if (entry.def != null && String(entry.def) !== "") fields[entry.field] = entry.def;
215
+ if (entry.optional && (explicit.has(entry) || !defaults)) continue;
216
+ if (defaults && entry.def != null && String(entry.def) !== "") fields[entry.field] = entry.def;
150
217
  else if (!entry.optional) {
151
218
  throw new NanoodleError(`missing required input "${entry.key}" (${entry.nodeId}.${entry.field})`);
152
219
  }
153
220
  }
154
221
  }
155
222
 
156
- // API key required only when the graph actually calls NanoGPT
157
- if (!this.client.apiKey && graph.nodes.some((n) => NODE_TYPES[n.type].network)) {
158
- throw new NanoodleError("no API key — pass { apiKey } to Workflow.load/fromJSON or set NANOGPT_API_KEY (this workflow calls the NanoGPT API)");
223
+ // API key (or an x402 payment callback) required only when the graph actually calls NanoGPT
224
+ if (!this.client.apiKey && !this.client.payment && hasNetwork) {
225
+ throw new NanoodleError("no API key — pass { apiKey } to Workflow.load/fromJSON, set NANOGPT_API_KEY, or pass { payment } for accountless x402 runs (this workflow calls the NanoGPT API)");
159
226
  }
160
227
 
161
228
  // ---- execution ----
@@ -176,6 +243,7 @@ export class Workflow {
176
243
  const cost = { total: 0, exact: true, balance: null };
177
244
  const byId = new Map(graph.nodes.map((n) => [n.id, n]));
178
245
  const promises = new Map();
246
+ const mediaFetch = this.client.fetch;
179
247
 
180
248
  const ctxFor = (node, rec) => {
181
249
  const onCost = (c) => {
@@ -194,12 +262,18 @@ export class Workflow {
194
262
  audio: (model, input, extra) => this.client.audio(model, input, extra, io),
195
263
  transcribe: (model, audioUrl, language) => this.client.transcribe(model, audioUrl, language, io),
196
264
  fetchMedia: (url) => this.client.fetchMediaDataUrl(url, io),
265
+ // local media (resize/combine/…) — same fetch + signal as network I/O
266
+ fetch: mediaFetch,
267
+ signal: ac.signal,
268
+ catalog: this.catalog,
269
+ progress: (msg) => emit({ type: "node-progress", nodeId: node.id, name: displayName(node), message: msg }),
197
270
  };
198
271
  };
199
272
 
200
273
  const execNode = async (n) => {
201
274
  const rec = nodesRec[n.id];
202
275
  try {
276
+ throwIfAborted(ac.signal);
203
277
  const inbound = graph.links.filter((l) => l.to.node === n.id);
204
278
  const inp = {};
205
279
  let fields = effFields.get(n.id);
@@ -215,9 +289,11 @@ export class Workflow {
215
289
  else if (v != null) fields = { ...fields, [l.to.port]: v };
216
290
  }
217
291
  if (upstreamFail) throw new NanoodleError("upstream failed: " + upstreamFail);
292
+ throwIfAborted(ac.signal);
218
293
  emit({ type: "node-start", nodeId: n.id, name: displayName(n) });
219
294
  const t0 = Date.now();
220
295
  const out = await RUNNERS[n.type]({ ...n, fields }, inp, ctxFor(n, rec));
296
+ throwIfAborted(ac.signal);
221
297
  rec.status = "done";
222
298
  rec.out = out;
223
299
  rec.ms = Date.now() - t0;
@@ -263,6 +339,25 @@ export class Workflow {
263
339
  remainingBalance: cost.balance,
264
340
  });
265
341
 
342
+ // timeout/abort must fail the run even when local media finished after the deadline
343
+ // (or nodes never observed the signal). Prefer the abort reason when present.
344
+ if (ac.signal.aborted) {
345
+ const reason = abortReason(ac.signal);
346
+ const msg = reason.message || "run aborted";
347
+ // mark any still-pending nodes so result.errors is complete
348
+ for (const n of order) {
349
+ const rec = nodesRec[n.id];
350
+ if (rec && rec.status === "pending") {
351
+ rec.status = "error";
352
+ rec.error = msg;
353
+ if (!errors.some((e) => e.nodeId === n.id)) {
354
+ errors.push({ nodeId: n.id, name: displayName(n), message: msg });
355
+ }
356
+ }
357
+ }
358
+ throw new RunError(msg, result, reason.code ? { code: reason.code } : {});
359
+ }
360
+
266
361
  const failedSinks = this.outputs.filter((o) => nodesRec[o.nodeId] && nodesRec[o.nodeId].status === "error");
267
362
  if (failedSinks.length) {
268
363
  const detail = failedSinks.map((o) => `"${o.key}": ${nodesRec[o.nodeId].error}`).join("; ");
@@ -271,9 +366,9 @@ export class Workflow {
271
366
  return result;
272
367
  }
273
368
 
274
- _coerceInput(entry, value) {
369
+ _coerceInput(entry, value, mediaOpts) {
275
370
  if (MEDIA_KINDS.has(entry.kind)) {
276
- return coerceMediaInput(value, `input "${entry.key}"`);
371
+ return coerceMediaInput(value, `input "${entry.key}"`, mediaOpts);
277
372
  }
278
373
  if (entry.kind === "choice") {
279
374
  const v = String(value);
package/src/x402.mjs ADDED
@@ -0,0 +1,77 @@
1
+ import { NanoodleError } from "./errors.mjs";
2
+
3
+ /**
4
+ * x402 accountless payments (NanoGPT) — request with `x-x402: true` and no key,
5
+ * get HTTP 402 with payment options, pay in Nano (XNO), call the complete URL,
6
+ * receive the original response.
7
+ *
8
+ * The library NEVER holds funds or keys: the actual send happens inside the
9
+ * user-supplied `payment` callback (their own wallet, signer, or a human
10
+ * scanning a QR). Wire shape live-verified against nano-gpt.com 2026-07-12
11
+ * (tests/fixtures/x402/402.json is a real captured response).
12
+ */
13
+
14
+ /** Reject anything that isn't a callback — a seed/private key must never reach this library. */
15
+ export function assertPaymentOption(payment) {
16
+ if (payment == null) return;
17
+ if (typeof payment !== "function") {
18
+ throw new NanoodleError(
19
+ "payment must be a callback function — nanoodle never accepts wallet seeds or private keys. " +
20
+ "Do the send inside your callback with your own wallet/signer (it receives the invoice: " +
21
+ "{ payTo, amountRaw, uri, ... }).", { code: "x402" });
22
+ }
23
+ }
24
+
25
+ /** ISO string or unix seconds → epoch ms (null when absent/unparsable). */
26
+ function toMs(v) {
27
+ if (v == null) return null;
28
+ if (typeof v === "number") return v < 1e12 ? v * 1000 : v; // seconds vs ms
29
+ const t = Date.parse(v);
30
+ return isNaN(t) ? null : t;
31
+ }
32
+
33
+ /**
34
+ * Pull the Nano payment option out of a 402 response body.
35
+ * Looks in the x402-standard `accepts` array first, then the NanoGPT
36
+ * `payment.accepted` list. Returns a frozen invoice for the payment callback.
37
+ */
38
+ export function parseNanoInvoice(body, baseUrl) {
39
+ const pay = body && body.payment;
40
+ const pool = [
41
+ ...(Array.isArray(body && body.accepts) ? body.accepts : []),
42
+ ...(Array.isArray(pay && pay.accepted) ? pay.accepted : []),
43
+ ];
44
+ const nano = pool.find((a) => a && a.scheme === "nano" && /^nano_[a-z0-9]+$/.test(String(a.payTo || "")));
45
+ if (!nano) return null;
46
+ const paymentId = nano.paymentId || (pay && pay.paymentId) || null;
47
+ const abs = (u) => (u ? new URL(u, baseUrl).href : null);
48
+ const amountRaw = String(nano.maxAmountRequired || nano.amount || "");
49
+ const usd = nano.maxAmountRequiredUSD != null ? Number(nano.maxAmountRequiredUSD)
50
+ : nano.amountUsd != null ? Number(nano.amountUsd)
51
+ : pay && pay.amountUsd != null ? Number(pay.amountUsd) : null;
52
+ return Object.freeze({
53
+ scheme: "nano",
54
+ paymentId,
55
+ payTo: nano.payTo,
56
+ /** integer raw units (1 XNO = 10^30 raw), as a string */
57
+ amountRaw,
58
+ /** human string, e.g. "0.00018406 XNO" */
59
+ amount: nano.maxAmountRequiredFormatted || nano.amountFormatted || null,
60
+ amountUsd: usd != null && isFinite(usd) ? usd : null,
61
+ /** ready-to-scan/click nano: URI */
62
+ uri: "nano:" + nano.payTo + (amountRaw ? "?amount=" + amountRaw : ""),
63
+ expiresAt: toMs(nano.expiresAt != null ? nano.expiresAt : pay && pay.expiresAt),
64
+ statusUrl: abs(nano.statusUrl || nano.callbackUrl || (pay && pay.statusUrl) || (paymentId && "/api/x402/status/" + paymentId)),
65
+ completeUrl: abs(nano.completeUrl || (pay && pay.completeUrl) || (paymentId && "/api/x402/complete/" + paymentId)),
66
+ explorerUrl: (nano.extra && nano.extra.explorerUrl) || null,
67
+ description: nano.description || null,
68
+ requestHash: (pay && pay.requestHash) || body.requestHash || null,
69
+ });
70
+ }
71
+
72
+ const RESULT_KEYS = ["choices", "data", "output", "runId", "url", "audioUrl", "transcription", "text"];
73
+
74
+ /** Does a complete-endpoint body already carry the replayed API result? */
75
+ export function looksLikeResult(j) {
76
+ return !!j && typeof j === "object" && RESULT_KEYS.some((k) => j[k] != null);
77
+ }
package/src/zlib.mjs ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Env-adaptive zlib: node:zlib in Node (dynamic import, cached), Compression/
3
+ * DecompressionStream in the browser. Everything is async because browsers have
4
+ * no synchronous form — callers (PNG codec, share links) are async paths anyway.
5
+ */
6
+
7
+ let _zlib; // undefined = untried, null = unavailable (browser)
8
+ async function nodeZlib() {
9
+ if (_zlib === undefined) {
10
+ try { _zlib = await import("node:zlib"); } catch { _zlib = null; }
11
+ }
12
+ return _zlib;
13
+ }
14
+
15
+ async function pipeThrough(bytes, stream) {
16
+ const out = new Blob([bytes]).stream().pipeThrough(stream);
17
+ return new Uint8Array(await new Response(out).arrayBuffer());
18
+ }
19
+
20
+ export async function inflate(bytes) {
21
+ const z = await nodeZlib();
22
+ if (z) return new Uint8Array(z.inflateSync(bytes));
23
+ return streamZlib.inflate(bytes);
24
+ }
25
+
26
+ export async function deflate(bytes, { level = 9 } = {}) {
27
+ const z = await nodeZlib();
28
+ if (z) return new Uint8Array(z.deflateSync(bytes, { level }));
29
+ return streamZlib.deflate(bytes); // level is a Node-only hint
30
+ }
31
+
32
+ export async function gunzip(bytes) {
33
+ const z = await nodeZlib();
34
+ if (z) return new Uint8Array(z.gunzipSync(bytes));
35
+ return streamZlib.gunzip(bytes);
36
+ }
37
+
38
+ // The browser implementations, exported so tests can exercise them in Node
39
+ // (which also ships Compression/DecompressionStream) without hiding node:zlib.
40
+ export const streamZlib = {
41
+ inflate: (b) => pipeThrough(b, new DecompressionStream("deflate")),
42
+ deflate: (b) => pipeThrough(b, new CompressionStream("deflate")),
43
+ gunzip: (b) => pipeThrough(b, new DecompressionStream("gzip")),
44
+ };
@@ -0,0 +1,48 @@
1
+ {
2
+ "v": 1,
3
+ "nodes": [
4
+ {
5
+ "id": "n1",
6
+ "type": "text",
7
+ "x": 60,
8
+ "y": 130,
9
+ "fields": {
10
+ "text": "a cozy ramen shop on a rainy night"
11
+ },
12
+ "w": 220
13
+ },
14
+ {
15
+ "id": "n2",
16
+ "type": "llm",
17
+ "x": 340,
18
+ "y": 70,
19
+ "fields": {
20
+ "model": "zai-org/glm-5.2",
21
+ "system": "You write image prompts. Turn the idea into one vivid, detailed image prompt — scene, lighting, mood, style. Reply with the prompt only."
22
+ },
23
+ "w": 250,
24
+ "sizes": {
25
+ "system": 120
26
+ }
27
+ },
28
+ {
29
+ "id": "n3",
30
+ "type": "image",
31
+ "x": 650,
32
+ "y": 100,
33
+ "fields": {
34
+ "model": "nano-banana-2-lite",
35
+ "size": "1k",
36
+ "variations": "1"
37
+ },
38
+ "w": 250
39
+ }
40
+ ],
41
+ "links": [
42
+ { "id": "l1", "from": { "node": "n1", "port": "text" }, "to": { "node": "n2", "port": "prompt" } },
43
+ { "id": "l2", "from": { "node": "n2", "port": "text" }, "to": { "node": "n3", "port": "prompt" } }
44
+ ],
45
+ "nid": 4,
46
+ "lid": 3,
47
+ "view": { "panX": 40, "panY": 60, "scale": 1 }
48
+ }