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/client.mjs CHANGED
@@ -1,5 +1,6 @@
1
+ import { imageModelOpts } from "./image-options.mjs";
1
2
  import { NanoodleError } from "./errors.mjs";
2
- import { b64ImageMime, bytesToDataUrl, dataUrlBytes, MEDIA_INLINE_MAX } from "./media.mjs";
3
+ import { b64ImageMime, bytesToDataUrl, dataUrlBytes, downloadMedia, sniffMime, MEDIA_INLINE_MAX } from "./media.mjs";
3
4
  import { assertPaymentOption, parseNanoInvoice, looksLikeResult } from "./x402.mjs";
4
5
 
5
6
  const AUDIO_MIME = { mp3: "audio/mpeg", opus: "audio/ogg", aac: "audio/aac", flac: "audio/flac", wav: "audio/wav", pcm: "audio/wav" };
@@ -9,7 +10,12 @@ const AUDIO_PROMPT_MODEL_RE = /(?:^|\/)(?:prompt-to-song|generate-bgm)$|(?:^|\/)
9
10
  const AUDIO_STYLE_MODEL_RE = /yue2-3b\/(?:text|music)-to-music$/i;
10
11
 
11
12
  /** Map an HTTP failure to an actionable error (mirrors the app's httpRunError). Never leaks the key. */
12
- export function httpError(status, bodyText) {
13
+ export function httpError(status, bodyText, headers) {
14
+ if (status === 403 && (headers?.get?.("x-vercel-mitigated") === "challenge" ||
15
+ (/^\s*<(?:!doctype\s+html\b|html\b)/i.test(bodyText) &&
16
+ /<title>\s*Vercel Security Checkpoint\s*<\/title>/i.test(bodyText)))) {
17
+ return new NanoodleError("NanoGPT's automated traffic protection challenged this request (HTTP 403).", { code: "blocked", status });
18
+ }
13
19
  if (status === 401 || status === 403) {
14
20
  return new NanoodleError(`API key rejected (HTTP ${status}) — check your NanoGPT key / NANOGPT_API_KEY`, { code: "auth", status });
15
21
  }
@@ -80,15 +86,17 @@ export function sleep(ms, signal) {
80
86
  * pollIntervals / timeouts are per-media-kind knobs (ms).
81
87
  */
82
88
  /**
83
- * GLB URL from a 3D status poll. A completed payload is 3D only when
89
+ * Model URL from a 3D status poll. A completed payload is 3D only when
84
90
  * output.kind is "3d" or output.format is "glb" — a bare video url is not a model.
85
- * Prefers model_url, then model.url, video.url, then videoUrls[0].
91
+ * Idol's model_url is only a point-cloud preview: its real Gaussian splat is
92
+ * model_mesh.url. Other models retain model_url, model.url, video.url, videoUrls[0].
86
93
  */
87
- export function model3dStatusUrl(s) {
94
+ export function model3dStatusUrl(s, model) {
88
95
  const out = (s && s.data && s.data.output) || (s && s.output) || {};
89
96
  const kind = String(out.kind || "").toLowerCase();
90
97
  const format = String(out.format || "").toLowerCase();
91
98
  if (kind !== "3d" && format !== "glb") return "";
99
+ if (model === "speridlabs/idol") return (out.model_mesh && out.model_mesh.url) || "";
92
100
  const list = Array.isArray(out.videoUrls) ? out.videoUrls : [];
93
101
  const first = list.length ? list[0] : null;
94
102
  const fromList = typeof first === "string" ? first : (first && first.url) || "";
@@ -127,10 +135,12 @@ export class NanoClient {
127
135
  * at most once; a second 402 after settling is an error, never a second send.
128
136
  */
129
137
  async _paidFetch(url, init, signal) {
138
+ if (signal && signal.aborted) throw abortError(signal.reason);
130
139
  const r = await this.fetch(url, init);
131
140
  if (r.status !== 402 || !this.payment || this.apiKey) return r;
132
141
  const settled = await this._settle402(r, signal);
133
142
  if (settled.response) return settled.response; // complete replayed the stored request
143
+ if (signal && signal.aborted) throw abortError(signal.reason);
134
144
  const r2 = await this.fetch(url, { ...init, headers: { ...init.headers, "x-x402-payment-id": settled.paymentId } });
135
145
  if (r2.status === 402) {
136
146
  throw new NanoodleError(
@@ -150,10 +160,15 @@ export class NanoClient {
150
160
  "payment required, but the 402 response offered no usable Nano option" +
151
161
  (body ? " — " + JSON.stringify(body).slice(0, 200) : ""), { code: "x402", status: 402 });
152
162
  }
163
+ if (signal && signal.aborted) throw abortError(signal.reason);
164
+ if (invoice.expiresAt && invoice.expiresAt <= Date.now()) {
165
+ throw new NanoodleError("payment window expired before payment (" + invoice.paymentId + ", to " + invoice.payTo + ") — request a fresh invoice", { code: "x402-expired", paymentId: invoice.paymentId });
166
+ }
153
167
  await this.payment(invoice); // ← the callback does the actual XNO send
154
168
  // The complete endpoint doubles as the poll: 402 = not seen on-chain yet.
155
169
  const deadline = invoice.expiresAt || Date.now() + 15 * 60 * 1000;
156
170
  while (true) {
171
+ if (signal && signal.aborted) throw abortError(signal.reason);
157
172
  const cr = await this.fetch(invoice.completeUrl, {
158
173
  method: "POST", headers: { "Content-Type": "application/json", "x-x402": "true" }, body: "{}", signal,
159
174
  });
@@ -181,7 +196,13 @@ export class NanoClient {
181
196
  { code: "x402", status: cr.status, paymentId: invoice.paymentId });
182
197
  }
183
198
  let cj = null;
184
- if (ct.includes("json")) { try { cj = await cr.json(); } catch { /* treat as settle-only */ } }
199
+ if (mime.includes("json")) { try { cj = await cr.json(); } catch { /* fail closed below */ } }
200
+ if (!cj || typeof cj !== "object") {
201
+ throw new NanoodleError(
202
+ "payment " + invoice.paymentId + " was sent, but completion returned no readable JSON receipt — check " +
203
+ (invoice.statusUrl || "the payment status") + " before paying again",
204
+ { code: "x402", paymentId: invoice.paymentId });
205
+ }
185
206
  if (looksLikeResult(cj)) {
186
207
  // wrap so call sites keep their Response contract (ok/json/text/headers)
187
208
  const response = { ok: true, status: 200, headers: cr.headers, json: async () => cj, text: async () => JSON.stringify(cj) };
@@ -189,7 +210,7 @@ export class NanoClient {
189
210
  }
190
211
  return { paymentId: invoice.paymentId, statusUrl: invoice.statusUrl };
191
212
  }
192
- if (cr.status !== 402) throw httpError(cr.status, await cr.text());
213
+ if (cr.status !== 402) throw httpError(cr.status, await cr.text(), cr.headers);
193
214
  await cr.text().catch(() => {}); // drain the "not verified yet" body
194
215
  if (Date.now() >= deadline) {
195
216
  throw new NanoodleError(
@@ -214,6 +235,35 @@ export class NanoClient {
214
235
  }, signal);
215
236
  }
216
237
 
238
+ async _pollJson(path, signal, remainingMs) {
239
+ const ac = new AbortController();
240
+ const onAbort = () => ac.abort(abortError(signal.reason));
241
+ if (signal) {
242
+ if (signal.aborted) onAbort();
243
+ else signal.addEventListener("abort", onAbort, { once: true });
244
+ }
245
+ const timer = Number.isFinite(remainingMs) ? setTimeout(() => ac.abort(
246
+ new NanoodleError("poll deadline reached", { code: "poll-timeout" })), Math.max(0, remainingMs)) : null;
247
+ let rejectAbort;
248
+ const aborted = new Promise((_, reject) => {
249
+ rejectAbort = () => reject(ac.signal.reason);
250
+ ac.signal.addEventListener("abort", rejectAbort, { once: true });
251
+ if (ac.signal.aborted) rejectAbort();
252
+ });
253
+ const work = Promise.resolve().then(async () => {
254
+ if (ac.signal.aborted) throw ac.signal.reason;
255
+ const r = await this._get(path, ac.signal);
256
+ if (!r.ok) throw httpError(r.status, await r.text(), r.headers);
257
+ return r.json();
258
+ });
259
+ try { return await Promise.race([work, aborted]); }
260
+ finally {
261
+ if (timer) clearTimeout(timer);
262
+ if (signal) signal.removeEventListener("abort", onAbort);
263
+ ac.signal.removeEventListener("abort", rejectAbort);
264
+ }
265
+ }
266
+
217
267
  async _get(path, signal) {
218
268
  return this.fetch(this.baseUrl + path, { headers: this._auth(), signal });
219
269
  }
@@ -221,12 +271,19 @@ export class NanoClient {
221
271
  /** POST /api/v1/chat/completions (non-streaming). Returns the assistant text. */
222
272
  async chat(messages, model, opts = {}, { onCost, signal } = {}) {
223
273
  const body = { model, messages };
224
- body.temperature = opts.temperature != null && opts.temperature !== "" ? +opts.temperature : 0.8;
225
- if (opts.max_tokens) body.max_tokens = +opts.max_tokens;
274
+ // Carbon has no sampling-temperature control; omit it rather than restoring a default.
275
+ if (model !== "google/gemini-4-carbon") body.temperature = opts.temperature != null && opts.temperature !== "" ? +opts.temperature : 0.8;
226
276
  if (opts.response_format) body.response_format = opts.response_format;
227
- if (opts.reasoning_effort) body.reasoning_effort = opts.reasoning_effort;
277
+ // Carbon's selected NanoGPT provider rejects explicit thinking controls (HTTP 400).
278
+ // Let the provider use its default rather than forwarding reasoning_effort.
279
+ if (model !== "google/gemini-4-carbon" && opts.reasoning_effort) body.reasoning_effort = opts.reasoning_effort;
280
+ // max_tokens is the one token budget forwarded, and only when a runner
281
+ // explicitly opts in via opts (the graph's maxTokens field, D1 ruling).
282
+ // The legacy spellings (max_completion_tokens, max_output_tokens,
283
+ // maxTokens) are never read here, so they can never leak into the body.
284
+ if (opts.max_tokens != null) body.max_tokens = opts.max_tokens;
228
285
  const r = await this._postJson("/api/v1/chat/completions", body, signal);
229
- if (!r.ok) throw httpError(r.status, await r.text());
286
+ if (!r.ok) throw httpError(r.status, await r.text(), r.headers);
230
287
  const j = await r.json();
231
288
  if (onCost) onCost(costWithHeaders(j, r));
232
289
  const msg = (j.choices && j.choices[0] && j.choices[0].message) || {};
@@ -247,7 +304,7 @@ export class NanoClient {
247
304
  */
248
305
  async decide(body, { onCost, signal } = {}) {
249
306
  const r = await this._postJson("/api/v1/decisions", body, signal);
250
- if (!r.ok) throw httpError(r.status, await r.text());
307
+ if (!r.ok) throw httpError(r.status, await r.text(), r.headers);
251
308
  const j = await r.json();
252
309
  const c = j && j.usage && typeof j.usage.cost === "number" ? j.usage.cost : null;
253
310
  if (onCost) onCost(costWithHeaders(c != null ? { ...j, cost: c } : j, r));
@@ -260,9 +317,9 @@ export class NanoClient {
260
317
  if (prompt) body.prompt = prompt; // omit when blank — upscalers run with no instruction
261
318
  if (imageDataUrl) body.imageDataUrl = imageDataUrl; // string OR array (edit multi-reference)
262
319
  if (maskDataUrl) body.maskDataUrl = maskDataUrl; // white = repaint
263
- if (extra) Object.assign(body, extra);
320
+ Object.assign(body, imageModelOpts(extra));
264
321
  const r = await this._postJson("/v1/images/generations", body, signal);
265
- if (!r.ok) throw httpError(r.status, await r.text());
322
+ if (!r.ok) throw httpError(r.status, await r.text(), r.headers);
266
323
  const j = await r.json();
267
324
  const urls = (j.data || [])
268
325
  .map((d) => (d.b64_json ? "data:" + b64ImageMime(d.b64_json) + ";base64," + d.b64_json : d.url))
@@ -308,7 +365,7 @@ export class NanoClient {
308
365
  let runId = resume || null;
309
366
  if (!runId) {
310
367
  const r = await this._postJson("/api/generate-video", body, signal);
311
- if (!r.ok) throw httpError(r.status, await r.text());
368
+ if (!r.ok) throw httpError(r.status, await r.text(), r.headers);
312
369
  const j = await r.json();
313
370
  if (onCost) onCost(costWithHeaders(j, r));
314
371
  runId = j.runId || j.id;
@@ -316,39 +373,50 @@ export class NanoClient {
316
373
  if (onRunId) onRunId(runId);
317
374
  }
318
375
 
319
- const t0 = Date.now();
320
- const videoCap = is3d ? this.timeouts.model3d : this.timeouts.video;
321
- const pollEvery = is3d ? (this.pollIntervals.model3d || this.pollIntervals.video) : this.pollIntervals.video;
322
- // Infinity/non-finite = wait forever (default). Finite ms = headless/CI cap.
323
- while (!Number.isFinite(videoCap) || Date.now() - t0 < videoCap) {
324
- await sleep(pollEvery, signal);
325
- let s;
326
- try {
327
- s = await (await this._get("/api/video/status?requestId=" + encodeURIComponent(runId), signal)).json();
328
- } catch (e) {
329
- if (signal && signal.aborted) throw abortError(signal.reason);
330
- continue; // transient poll failure — keep polling until complete or optional cap
331
- }
332
- const st = String((s.data && s.data.status) || s.status || "").toUpperCase();
333
- if (onPoll) onPoll({ status: st, elapsedMs: Date.now() - t0, runId });
334
- if (st === "COMPLETED" || st === "SUCCEEDED") {
335
- if (is3d) {
336
- const url = model3dStatusUrl(s);
337
- if (!url) throw new NanoodleError("completed but no model url");
376
+ try {
377
+ const t0 = Date.now();
378
+ const videoCap = is3d ? this.timeouts.model3d : this.timeouts.video;
379
+ const pollEvery = is3d ? (this.pollIntervals.model3d || this.pollIntervals.video) : this.pollIntervals.video;
380
+ // Infinity/non-finite = wait forever (default). Finite ms = headless/CI cap.
381
+ while (!Number.isFinite(videoCap) || Date.now() - t0 < videoCap) {
382
+ await sleep(Number.isFinite(videoCap) ? Math.min(pollEvery, Math.max(0, videoCap - (Date.now() - t0))) : pollEvery, signal);
383
+ if (Number.isFinite(videoCap) && Date.now() - t0 >= videoCap) break;
384
+ let s;
385
+ try {
386
+ s = await this._pollJson("/api/video/status?requestId=" + encodeURIComponent(runId), signal, videoCap - (Date.now() - t0));
387
+ } catch (e) {
388
+ if (signal && signal.aborted) throw abortError(signal.reason);
389
+ if (e.code === "poll-timeout") break;
390
+ if (e.status >= 400 && e.status < 500 && ![408, 429].includes(e.status)) throw e;
391
+ continue; // transient poll failure — keep polling until complete or optional cap
392
+ }
393
+ const st = String((s.data && s.data.status) || s.status || "").toUpperCase();
394
+ if (onPoll) onPoll({ status: st, elapsedMs: Date.now() - t0, runId });
395
+ if (st === "COMPLETED" || st === "SUCCEEDED") {
396
+ if (is3d) {
397
+ const url = model3dStatusUrl(s, model);
398
+ if (!url) throw new NanoodleError("completed but no model url");
399
+ return url;
400
+ }
401
+ const out = (s.data && s.data.output) || s.output || {};
402
+ const url = (out.video && out.video.url) || out.url || (Array.isArray(out.video) ? out.video[0] && out.video[0].url : null);
403
+ if (!url) throw new NanoodleError("completed but no video url");
338
404
  return url;
339
405
  }
340
- const out = (s.data && s.data.output) || s.output || {};
341
- const url = (out.video && out.video.url) || out.url || (Array.isArray(out.video) ? out.video[0] && out.video[0].url : null);
342
- if (!url) throw new NanoodleError("completed but no video url");
343
- return url;
344
- }
345
- if (["FAILED", "ERROR", "CANCELED"].includes(st)) {
346
- const why = (s.data && s.data.error) || st;
347
- throw new NanoodleError((is3d ? "3D failed: " : "video failed: ") + why);
406
+ if (["FAILED", "ERROR", "CANCELED", "CANCELLED", "CONTENT_POLICY_VIOLATION"].includes(st)) {
407
+ const why = (s.data && s.data.error) || st;
408
+ throw new NanoodleError((is3d ? "3D failed: " : "video failed: ") + why);
409
+ }
348
410
  }
411
+ const label = is3d ? "3D" : "video";
412
+ throw new NanoodleError(`${label} timed out (${Math.round(videoCap / 1000)}s) — the job may still be running on NanoGPT's side`, { code: "timeout" });
413
+ } catch (e) {
414
+ if (signal && signal.aborted) throw e;
415
+ throw new NanoodleError(e && e.message ? e.message : String(e), {
416
+ ...(e && e.code ? { code: e.code } : {}),
417
+ ...(e && e.status ? { status: e.status } : {}), runId, cause: e,
418
+ });
349
419
  }
350
- const label = is3d ? "3D" : "video";
351
- throw new NanoodleError(`${label} timed out (${Math.round(videoCap / 1000)}s) — the job may still be running on NanoGPT's side`, { code: "timeout" });
352
420
  }
353
421
 
354
422
  /**
@@ -373,7 +441,7 @@ export class NanoClient {
373
441
  delete body.prompt;
374
442
  }
375
443
  const r = await this._postJson("/api/v1/audio/speech", body, signal);
376
- if (!r.ok) throw httpError(r.status, await r.text());
444
+ if (!r.ok) throw httpError(r.status, await r.text(), r.headers);
377
445
  const ct = (r.headers && r.headers.get && r.headers.get("content-type")) || "";
378
446
  if (ct.includes("application/json")) {
379
447
  const j = await r.json();
@@ -404,12 +472,15 @@ export class NanoClient {
404
472
  if (j.isApiRequest != null) qs.set("isApiRequest", String(j.isApiRequest));
405
473
  const t0 = Date.now();
406
474
  while (Date.now() - t0 < this.timeouts.audio) {
407
- await sleep(this.pollIntervals.audio, signal);
475
+ await sleep(Math.min(this.pollIntervals.audio, Math.max(0, this.timeouts.audio - (Date.now() - t0))), signal);
476
+ if (Date.now() - t0 >= this.timeouts.audio) break;
408
477
  let s;
409
478
  try {
410
- s = await (await this._get("/api/tts/status?" + qs, signal)).json();
479
+ s = await this._pollJson("/api/tts/status?" + qs, signal, this.timeouts.audio - (Date.now() - t0));
411
480
  } catch (e) {
412
481
  if (signal && signal.aborted) throw abortError(signal.reason);
482
+ if (e.code === "poll-timeout") break;
483
+ if (e.status >= 400 && e.status < 500 && ![408, 429].includes(e.status)) throw e;
413
484
  continue;
414
485
  }
415
486
  const st = String(s.status || "").toLowerCase();
@@ -419,7 +490,7 @@ export class NanoClient {
419
490
  if (!url) throw new NanoodleError("completed but no audio url");
420
491
  return url;
421
492
  }
422
- if (["error", "failed", "content_policy_violation"].includes(st)) {
493
+ if (["error", "failed", "canceled", "cancelled", "content_policy_violation"].includes(st)) {
423
494
  throw new NanoodleError("audio failed: " + (s.error || s.message || st));
424
495
  }
425
496
  }
@@ -432,9 +503,9 @@ export class NanoClient {
432
503
  if (/^data:/i.test(audioUrl)) {
433
504
  ({ bytes, mime } = dataUrlBytes(audioUrl));
434
505
  } else {
435
- const r = await this.fetch(audioUrl, { signal }); // media CDN — no auth headers
436
- if (!r.ok) throw new NanoodleError("couldn't download the audio to transcribe (" + r.status + ")");
437
- bytes = new Uint8Array(await r.arrayBuffer());
506
+ const downloaded = await downloadMedia(audioUrl, { fetch: this.fetch, signal, what: "the audio to transcribe" });
507
+ const r = downloaded.response;
508
+ bytes = downloaded.bytes;
438
509
  mime = ((r.headers && r.headers.get && r.headers.get("content-type")) || "audio/mpeg").split(";")[0];
439
510
  }
440
511
  if (bytes.length > 3.5 * 1024 * 1024) {
@@ -447,7 +518,7 @@ export class NanoClient {
447
518
  if (language) fd.append("language", language);
448
519
  // no explicit Content-Type — fetch sets the multipart boundary
449
520
  const r = await this._paidFetch(this.baseUrl + "/api/v1/audio/transcriptions", { method: "POST", headers: this._auth(), body: fd, signal }, signal);
450
- if (!r.ok) throw httpError(r.status, await r.text());
521
+ if (!r.ok) throw httpError(r.status, await r.text(), r.headers);
451
522
  const j = await r.json();
452
523
  if (onCost) onCost(costWithHeaders(j, r));
453
524
  const txt = j.transcription != null ? j.transcription
@@ -462,18 +533,208 @@ export class NanoClient {
462
533
  * Used when a chat audio part needs base64 bytes but the upstream node produced an https URL.
463
534
  */
464
535
  async fetchMediaDataUrl(url, { signal } = {}) {
465
- const r = await this.fetch(url, { signal });
466
- if (!r.ok) throw new NanoodleError("couldn't download media to inline (" + r.status + "): " + url);
467
- const bytes = new Uint8Array(await r.arrayBuffer());
536
+ const { bytes, response: r } = await downloadMedia(url, { fetch: this.fetch, signal, what: "media to inline" });
468
537
  const ct = (((r.headers && r.headers.get && r.headers.get("content-type")) || "").split(";")[0] || "").trim().toLowerCase();
469
538
  const mime = ct && ct !== "application/octet-stream" && ct !== "binary/octet-stream" ? ct : undefined;
470
539
  return bytesToDataUrl(bytes, mime); // sniffs magic bytes when the CDN's content-type is generic
471
540
  }
472
541
 
542
+ /**
543
+ * Resolve a provider media URL before it is handed to another node or returned
544
+ * as a node output. Relative content paths (Grok Imagine's
545
+ * `/api/generate-video/content?...`) and the exact same-origin content paths
546
+ * in CONTENT_API_PATHS are joined onto `baseUrl` and fetched with the API key,
547
+ * redirects manual so the key is never forwarded to the file host. Any other
548
+ * same-origin `/api` or `/v1` URL, including a user-supplied upload URL, is
549
+ * refused and not fetched — a 200 from those paths must not be inlined with
550
+ * the caller's credentials. A redirect Location becomes the
551
+ * absolute file URL (presigned queries stay on that URL — the next provider
552
+ * needs them — and are never put in errors). A direct 200 is inlined as a
553
+ * data URL only when it fits MEDIA_INLINE_MAX; an over-cap clip must come
554
+ * back as a redirect URL rather than failing the inline budget.
555
+ */
556
+ async resolveContentUrl(url, { signal } = {}) {
557
+ return resolveProviderMediaUrl(url, {
558
+ baseUrl: this.baseUrl,
559
+ fetch: this.fetch,
560
+ authHeaders: this._auth(),
561
+ apiKey: this.apiKey,
562
+ signal,
563
+ });
564
+ }
565
+
473
566
  /** Optional helper: POST /api/check-balance → { usd_balance }. */
474
567
  async checkBalance(signal) {
475
568
  const r = await this._postJson("/api/check-balance", {}, signal);
476
- if (!r.ok) throw httpError(r.status, await r.text());
569
+ if (!r.ok) throw httpError(r.status, await r.text(), r.headers);
477
570
  return r.json();
478
571
  }
479
572
  }
573
+
574
+ /**
575
+ * Exact content paths that return provider media. Credentials are sent only here.
576
+ * A prefix (`/api/…`, `/v1/…`) is not enough: `/api/v1/models`, an upload URL, or
577
+ * `/api/generate-video/content/extra` would otherwise be fetched with the key and
578
+ * a 200 body inlined into the graph output.
579
+ */
580
+ const CONTENT_API_PATHS = new Set([
581
+ "/api/generate-video/content",
582
+ "/api/images/content",
583
+ "/v1/audio/content",
584
+ ]);
585
+
586
+ function isContentApiPath(pathname) {
587
+ return CONTENT_API_PATHS.has(pathname);
588
+ }
589
+
590
+ /** Same-origin API surface. These are not fetched unless the path is allowlisted. */
591
+ function isSameOriginApiPath(pathname) {
592
+ return pathname === "/api" || pathname.startsWith("/api/")
593
+ || pathname === "/v1" || pathname.startsWith("/v1/");
594
+ }
595
+
596
+ function refuseNonContentApi(pathname) {
597
+ if (!isSameOriginApiPath(pathname) || isContentApiPath(pathname)) return;
598
+ throw new NanoodleError("that URL is not a provider content file, so it was not fetched");
599
+ }
600
+
601
+ function apiBase(baseUrl) {
602
+ const base = String(baseUrl || "https://nano-gpt.com").replace(/\/+$/, "");
603
+ const origin = new URL(base + "/").origin;
604
+ return { base, origin };
605
+ }
606
+
607
+ /** Estimated data-URL length for `byteLength` raw bytes. Matches the inline cap's string check. */
608
+ function dataUrlWouldExceed(byteLength, mime) {
609
+ const header = ("data:" + (mime || "application/octet-stream") + ";base64,").length;
610
+ return header + Math.ceil(Math.max(0, byteLength) / 3) * 4 > MEDIA_INLINE_MAX;
611
+ }
612
+
613
+ /** Drop the API key, bearer tokens, and query strings from text that may be shown. */
614
+ function scrubSecrets(text, apiKey) {
615
+ let s = String(text || "");
616
+ if (apiKey && String(apiKey).length >= 4) s = s.split(String(apiKey)).join("[redacted]");
617
+ s = s.replace(/bearer\s+\S+/gi, "Bearer [redacted]");
618
+ s = s.replace(/[?#][^\s)"']*/g, "");
619
+ s = s.replace(/(?:X-Amz-[A-Za-z-]*|Signature|sig|token|api_key|apikey)\s*[:=]\s*\S+/gi, (m) => m.split(/[:=]/)[0] + "=[redacted]");
620
+ return s.replace(/\s+/g, " ").trim().slice(0, 160);
621
+ }
622
+
623
+ function authHeadersFor(url, origin, authHeaders) {
624
+ try {
625
+ if (new URL(url).origin !== origin) return {};
626
+ } catch {
627
+ return {};
628
+ }
629
+ return authHeaders ? { ...authHeaders } : {};
630
+ }
631
+
632
+ async function drainBody(r) {
633
+ try {
634
+ if (r && r.body && typeof r.body.cancel === "function") await r.body.cancel();
635
+ else if (r && typeof r.arrayBuffer === "function") await r.arrayBuffer();
636
+ } catch { /* already consumed, or the peer hung up */ }
637
+ }
638
+
639
+ function responseMime(r) {
640
+ const ct = ((r && r.headers && r.headers.get && r.headers.get("content-type")) || "").split(";")[0].trim().toLowerCase();
641
+ if (!ct || ct === "application/octet-stream" || ct === "binary/octet-stream") return "";
642
+ return ct;
643
+ }
644
+
645
+ /**
646
+ * Resolve one provider media URL.
647
+ * - data:, blob:, and ordinary http(s) URLs pass through (no fetch, no key).
648
+ * - A path-absolute URL is joined onto the NanoGPT base. Non-API paths become
649
+ * that absolute URL and are not fetched (the next node can GET them).
650
+ * - `/api` and `/v1` URLs (relative, or already on the API origin) are fetched
651
+ * with the key and `redirect: "manual"`. An off-origin or non-API Location is
652
+ * the fetchable file URL and is returned without downloading it — so a clip
653
+ * over the ~4.4 MB inline cap still chains. A 200 body is inlined only when
654
+ * the data URL fits MEDIA_INLINE_MAX.
655
+ * Errors never include the API key or a presigned query string.
656
+ */
657
+ export async function resolveProviderMediaUrl(url, { baseUrl, fetch: fetchImpl, authHeaders, apiKey, signal } = {}) {
658
+ if (typeof url !== "string") return url;
659
+ const s = url.trim();
660
+ if (!s || /^(data:|blob:)/i.test(s)) return s;
661
+ const { base, origin } = apiBase(baseUrl);
662
+ let start;
663
+ try {
664
+ if (/^https?:/i.test(s)) {
665
+ const abs = new URL(s);
666
+ if (abs.origin !== origin) return s;
667
+ refuseNonContentApi(abs.pathname);
668
+ if (!isContentApiPath(abs.pathname)) return s;
669
+ start = abs;
670
+ } else if (s.startsWith("/") && !s.startsWith("//")) {
671
+ start = new URL(s, base + "/");
672
+ refuseNonContentApi(start.pathname);
673
+ if (!isContentApiPath(start.pathname)) return start.href;
674
+ } else {
675
+ return s;
676
+ }
677
+ } catch (e) {
678
+ // A refused /api or /v1 URL must not be swallowed as "leave it unchanged".
679
+ if (e && e.name === "NanoodleError") throw e;
680
+ return s;
681
+ }
682
+
683
+ const doFetch = fetchImpl || globalThis.fetch;
684
+ if (!doFetch) throw new NanoodleError("couldn't fetch provider media: no fetch available");
685
+ let current = start.href;
686
+ for (let hop = 0; hop < 5; hop++) {
687
+ let r;
688
+ try {
689
+ r = await doFetch(current, {
690
+ method: "GET",
691
+ headers: authHeadersFor(current, origin, authHeaders),
692
+ redirect: "manual",
693
+ signal,
694
+ });
695
+ } catch (e) {
696
+ if (e && (e.name === "AbortError" || e.code === "aborted")) throw e;
697
+ if (signal && signal.aborted) throw e;
698
+ const detail = scrubSecrets(e && e.message, apiKey);
699
+ throw new NanoodleError("couldn't fetch provider media" + (detail ? " (" + detail + ")" : ""));
700
+ }
701
+ const status = r.status;
702
+ const loc = r.headers && r.headers.get && r.headers.get("location");
703
+ if (loc && (status === 0 || (status >= 300 && status < 400))) {
704
+ await drainBody(r);
705
+ let next;
706
+ try { next = new URL(loc, current); }
707
+ catch { throw new NanoodleError("provider media redirect had no usable location"); }
708
+ // File host or a non-API path: hand back the absolute URL. Do not fetch it
709
+ // (that would pull a multi-megabyte clip and might attach the key).
710
+ // A same-origin /api or /v1 hop that is not itself a content file is refused
711
+ // outright — its body must never be inlined with the caller's credentials.
712
+ if (next.origin === origin) refuseNonContentApi(next.pathname);
713
+ if (next.origin !== origin || !isContentApiPath(next.pathname)) return next.href;
714
+ current = next.href;
715
+ continue;
716
+ }
717
+ if (status >= 300 && status < 400) {
718
+ await drainBody(r);
719
+ throw new NanoodleError("provider media redirect had no location");
720
+ }
721
+ if (!r.ok) {
722
+ const raw = String(await r.text().catch(() => "")).slice(0, 500);
723
+ const snippet = scrubSecrets(raw, apiKey);
724
+ throw new NanoodleError("couldn't fetch provider media (HTTP " + status + ")" + (snippet ? ": " + snippet : ""));
725
+ }
726
+ const mimeHeader = responseMime(r);
727
+ const declared = Number(r.headers && r.headers.get && r.headers.get("content-length"));
728
+ if (Number.isFinite(declared) && declared >= 0 && dataUrlWouldExceed(declared, mimeHeader)) {
729
+ await drainBody(r);
730
+ throw new NanoodleError("provider media is too large to send inline (~4 MB max) and did not redirect to a fetchable file");
731
+ }
732
+ const bytes = new Uint8Array(await r.arrayBuffer());
733
+ const mime = mimeHeader || sniffMime(bytes);
734
+ if (dataUrlWouldExceed(bytes.length, mime)) {
735
+ throw new NanoodleError("provider media is too large to send inline (~4 MB max) and did not redirect to a fetchable file");
736
+ }
737
+ return bytesToDataUrl(bytes, mime);
738
+ }
739
+ throw new NanoodleError("provider media redirect did not resolve to a fetchable file");
740
+ }
package/src/decide.mjs CHANGED
@@ -11,6 +11,7 @@ export const DECIDE_SCALE_DEFAULT = "poor\nokay\ngood\ngreat";
11
11
  export const DECIDE_IMG_FALLBACK = { maxImages: 4, maxDimension: 512, maxEncodedBytes: 240000 };
12
12
 
13
13
  export function decideMode(f) {
14
+ if (f?.branch === true) return "yesno";
14
15
  const m = f && f.mode;
15
16
  return (m === "choose" || m === "score" || m === "yesno") ? m : "pick";
16
17
  }
@@ -154,7 +155,17 @@ export async function decideRun(f, model, text, imgs, lim, send, fit) {
154
155
  } else {
155
156
  j = await send({ model, state: decideState(text, sent), questions: { answer: q } });
156
157
  }
157
- const out = decideOutputs(mode, j && j.answers && j.answers.answer, q, imgs, j && j.usage, model);
158
+ const answer = j?.answers?.answer;
159
+ const branching = f?.branch === true;
160
+ if (branching && (answer?.type !== "noul" || !Number.isFinite(answer.noul) || answer.noul < 0 || answer.noul > 1)) {
161
+ throw new NanoodleError("Decide needs a valid yes/no answer to select a branch", { code: "decide-branch" });
162
+ }
163
+ const out = decideOutputs(mode, answer, q, imgs, j && j.usage, model);
164
+ if (branching) {
165
+ out.decision.branch = out.text;
166
+ out[out.text] = text || out.text;
167
+ return out;
168
+ }
158
169
  if (mode === "yesno" && (f.gate === true || f.gate === "true") && out.decision.yes < 0.5) throw decideGateError(out.decision, out);
159
170
  return out;
160
171
  }
package/src/errors.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  export class NanoodleError extends Error {
3
3
  /**
4
4
  * @param {string} message
5
- * @param {object} [props] extra fields (e.g. { code: "auth" | "funds" | "http", status })
5
+ * @param {object} [props] extra fields (e.g. { code: "auth" | "blocked" | "funds" | "http", status })
6
6
  */
7
7
  constructor(message, props = {}) {
8
8
  super(message);