cheapgen 0.1.1 → 0.2.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.
@@ -19,6 +19,31 @@ export function frameSize(request, frameSizes) {
19
19
  */
20
20
  export function cost(pricing, request, frameSizes) {
21
21
  const count = request.count ?? 1;
22
+ return baseCost(pricing, request, frameSizes, count) + inputFee(pricing.inputFee, request) * count;
23
+ }
24
+
25
+ /**
26
+ * What the input images of an edit add to one output: a fee per image (after any free ones),
27
+ * or a fee per megapixel of input.
28
+ */
29
+ function inputFee(fee, request) {
30
+ const images = request.images;
31
+ if (!fee || !images?.length) return 0;
32
+ let usd = 0;
33
+ if (fee.usdPerImage) usd += Math.max(0, images.length - (fee.free ?? 0)) * fee.usdPerImage;
34
+ if (fee.usdPerMp) {
35
+ const mp = fee.mpDefinition ?? 1e6;
36
+ usd += images.reduce((sum, i) => sum + Math.ceil(needPixels(i) / mp - 1e-12), 0) * fee.usdPerMp;
37
+ }
38
+ return usd;
39
+ }
40
+
41
+ function needPixels(image) {
42
+ if (!(image.width > 0) || !(image.height > 0)) throw new Error('the size of an input image given as a URL is unknown');
43
+ return image.width * image.height;
44
+ }
45
+
46
+ function baseCost(pricing, request, frameSizes, count) {
22
47
  switch (pricing.type) {
23
48
  case 'perSecond':
24
49
  return pricing.usd * need(request.duration, 'duration') * count;
@@ -34,6 +59,7 @@ export function cost(pricing, request, frameSizes) {
34
59
  const mpUnit = pricing.mpDefinition ?? 1e6;
35
60
  const round = pricing.roundUp === false ? (x) => x : (x) => Math.ceil(x - 1e-12);
36
61
  const outputMp = round((w * h) / mpUnit);
62
+ if (pricing.usdPerInputMp && request.images?.length) request.images.forEach(needPixels);
37
63
  const inputMp = request.inputPixels ? round(request.inputPixels / mpUnit) : 0;
38
64
  const perImage = (pricing.usdPerRun ?? 0) + outputMp * (pricing.usdPerOutputMp ?? 0)
39
65
  + inputMp * (pricing.usdPerInputMp ?? 0);
@@ -2,6 +2,7 @@
2
2
  // API and a key, else a cached live price younger than 24 hours, else the bundled table.
3
3
  import { cost } from './formulas.js';
4
4
  import { pricedRequest } from '../request.js';
5
+ import { entryFor } from '../catalog.js';
5
6
 
6
7
  export const STALE_AFTER_DAYS = 14;
7
8
  const DAY_MS = 24 * 60 * 60 * 1000;
@@ -46,7 +47,9 @@ export function bundledPrice(catalog, providerId, request, now) {
46
47
 
47
48
  export function cacheKey(providerId, r) {
48
49
  return [providerId, r.model, r.mode, r.resolution ?? r.size, r.aspectRatio,
49
- r.autoDuration ? 'auto' : r.duration, r.audio, r.count, r.image ? 'img' : ''].join('|');
50
+ r.autoDuration ? 'auto' : r.duration, r.audio, r.count, r.image ? 'img' : '',
51
+ ...(r.images ? [`in${r.images.length}`, r.inputPixels ?? '?', r.effectiveAspect ?? '?',
52
+ r.images.map((i) => (i.isLocal ? `${i.width}x${i.height}` : 'url')).join(',')] : [])].join('|');
50
53
  }
51
54
 
52
55
  /**
@@ -66,7 +69,7 @@ export async function priceFor({ adapter, request, catalog, ctx, cache, now }) {
66
69
  const key = cacheKey(adapter.id, request);
67
70
  let live = null;
68
71
  try {
69
- live = await adapter.livePrice(request, ctx, { entry: catalog.models[request.model].providers[adapter.id],
72
+ live = await adapter.livePrice(request, ctx, { entry: entryFor(catalog, adapter.id, request),
70
73
  bundled, frameSizes: catalog.frameSizes });
71
74
  } catch { live = null; }
72
75
  if (live && typeof live.usd === 'number' && Number.isFinite(live.usd)) {
@@ -42,12 +42,18 @@ export function readError(message, status) {
42
42
 
43
43
  const MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
44
44
 
45
- /** Reads a local file into a Blob for multipart uploads, with a MIME type from its extension. */
46
- export function fileBlob(filePath) {
47
- const type = MIME[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';
45
+ /**
46
+ * Reads a local file into a Blob for uploads. The MIME type is `contentType` when the caller
47
+ * read the file's type from its bytes, else it comes from the extension.
48
+ */
49
+ export function fileBlob(filePath, contentType) {
50
+ const type = contentType ?? MIME[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';
48
51
  return { blob: new Blob([fs.readFileSync(filePath)], { type }), name: path.basename(filePath), type };
49
52
  }
50
53
 
54
+ /** What an upload is called in an error message: "the image" or "the audio file". */
55
+ export const uploadLabel = (contentType) => (contentType?.startsWith('audio/') ? 'the audio file' : 'the image');
56
+
51
57
  /** Wraps an upload so any failure counts as a clear rejection: no job exists yet. */
52
58
  export async function asRejection(what, fn) {
53
59
  try {
@@ -81,26 +87,61 @@ export function videoFields(r, { durationAsString = false, entry } = {}) {
81
87
  return fields;
82
88
  }
83
89
 
90
+ /**
91
+ * The media fields of a video request under one provider's field names (`names`: first, last,
92
+ * refImages, refAudio). A reference list with nothing in it is left out, and the entry's
93
+ * `request.referenceFields` (a task type, where the provider has one) is added to a
94
+ * reference-to-video request.
95
+ */
96
+ export function videoMedia(r, entry, names, { imageUrl, lastImageUrl, refImageUrls, refAudioUrls } = {}) {
97
+ if (r.mode === 'reference-to-video') {
98
+ return {
99
+ ...(refImageUrls?.length ? { [names.refImages]: refImageUrls } : {}),
100
+ ...(refAudioUrls?.length ? { [names.refAudio]: refAudioUrls } : {}),
101
+ ...(entry?.request?.referenceFields ?? {}),
102
+ };
103
+ }
104
+ return { ...(imageUrl ? { [names.first]: imageUrl } : {}), ...(lastImageUrl ? { [names.last]: lastImageUrl } : {}) };
105
+ }
106
+
84
107
  /**
85
108
  * Image size and aspect fields from the entry's `request` block. Without one,
86
109
  * the adapter's default size field is used and the canonical size is sent as is.
110
+ *
111
+ * An edit with aspect "auto" uses the provider's own way of following the input image
112
+ * (`edit.follow`): a value for the aspect field, no aspect field at all (`aspect: null`), or a
113
+ * size preset per canonical size. A provider with none gets the ratio worked out from the image.
87
114
  */
88
115
  export function imageFields(r, entry, defaultSizeField) {
89
116
  const req = entry?.request ?? {};
90
117
  const size = req.size ?? { field: defaultSizeField };
118
+ const auto = r.aspectRatio === 'auto';
119
+ const follow = auto ? entry?.edit?.follow : undefined;
120
+ let aspect = auto ? r.effectiveAspect : r.aspectRatio;
121
+ if (follow) aspect = Object.hasOwn(follow, 'aspect') ? follow.aspect : null;
91
122
  let value;
92
- if (size.pixels) {
123
+ if (follow?.size) {
124
+ value = follow.size[r.size] ?? r.size;
125
+ } else if (size.pixels) {
93
126
  if (!Array.isArray(r.pixels)) throw new Error(`no pixel size for ${r.model} ${r.size} ${r.aspectRatio}`);
94
127
  const [width, height] = r.pixels;
95
128
  value = size.pixels === 'object' ? { width, height } : `${width}*${height}`;
96
129
  } else {
97
130
  value = size.values?.[r.size] ?? r.size;
98
131
  }
99
- return { ...(req.aspect === false ? {} : { aspect_ratio: r.aspectRatio }), [size.field]: value };
132
+ return { ...(req.aspect === false || !aspect ? {} : { aspect_ratio: aspect }), [size.field]: value };
100
133
  }
101
134
 
102
- /** "<id>/<suffix>", or the id alone when the entry maps the mode to "". */
135
+ /** The input images of an edit, under the provider's field name; nothing for other modes. */
136
+ export const editImages = (r, entry, imageUrls) =>
137
+ (r.mode === 'image-edit' ? { [entry.edit.field]: imageUrls ?? [] } : {});
138
+
139
+ /** The provider's model id: its edit id for an edit when it has a separate one. */
140
+ export const modelId = (r, entry) => (r.mode === 'image-edit' ? entry.edit?.id ?? entry.id : entry.id);
141
+
142
+ /** "<id>/<suffix>", or the id alone when the entry maps the mode to "". An edit has its own path. */
103
143
  export function endpointPath(r, entry) {
144
+ if (r.mode === 'image-edit' && entry.edit?.id) return entry.edit.id;
104
145
  const suffix = entry.modes?.[r.mode] ?? r.mode;
105
146
  return suffix ? `${entry.id}/${suffix}` : entry.id;
106
147
  }
@@ -10,11 +10,15 @@ export class SubmitRejected extends Error {
10
10
  }
11
11
  }
12
12
 
13
- /** A job may exist and may be billed: never fall back automatically. */
13
+ /**
14
+ * A job may exist and may be billed: never fall back automatically. `details` holds anything that
15
+ * helps find the job later (for example an idempotency key); it goes in the spend log.
16
+ */
14
17
  export class SubmitUnknown extends Error {
15
- constructor(message, { status = null } = {}) {
18
+ constructor(message, { status = null, details = null } = {}) {
16
19
  super(message);
17
20
  this.name = 'SubmitUnknown';
18
21
  this.status = status;
22
+ this.details = details;
19
23
  }
20
24
  }
@@ -3,9 +3,9 @@
3
3
  // The balance needs a key with billing:usage:read; without it the balance is unknown.
4
4
  import { http, describeBody } from '../http.js';
5
5
  import { SubmitUnknown } from './errors.js';
6
- import { postJob, getJson, fileBlob, asRejection, videoFields, imageFields, endpointPath } from './common.js';
6
+ import { postJob, getJson, fileBlob, uploadLabel, asRejection, videoFields, videoMedia, imageFields, editImages, endpointPath } from './common.js';
7
7
  import { cost } from '../pricing/formulas.js';
8
- import { pricedRequest } from '../request.js';
8
+ import { pricedRequest, promptFor } from '../request.js';
9
9
 
10
10
  const QUEUE = 'https://queue.fal.run';
11
11
  const API = 'https://api.fal.ai/v1';
@@ -15,12 +15,22 @@ const auth = (ctx) => ({ Authorization: `Key ${ctx.key}` });
15
15
 
16
16
  const endpointOf = endpointPath;
17
17
 
18
+ const VIDEO_INPUTS = { first: 'image_url', last: 'end_image_url', refImages: 'image_urls', refAudio: 'audio_urls' };
19
+
20
+ /**
21
+ * The endpoint whose unit price applies. fal has one price per endpoint, and a reference
22
+ * endpoint's can't tell a request with reference video from one without; with images and audio
23
+ * only, the rate is the text-to-video one.
24
+ */
25
+ const pricedEndpoint = (r, entry) => endpointOf(r.mode === 'reference-to-video' ? { ...r, mode: 'text-to-video' } : r, entry);
26
+
18
27
  /** fal's queue status URLs use the app id: the first two segments of the endpoint. */
19
28
  const appIdOf = (endpoint) => endpoint.split('/').slice(0, 2).join('/');
20
29
 
21
30
  /**
22
- * fal's API gives one base price per endpoint. Sizes and resolutions billed at a higher rate are
23
- * marked `live.falUnitPrice: false` in the price data, and use the bundled price.
31
+ * fal's API gives one base price per endpoint. Sizes and resolutions billed at another rate (a
32
+ * dearer size, or Seedance's cheaper per-token 4k rate) are marked `live.falUnitPrice: false` in
33
+ * the price data, and use the bundled price.
24
34
  */
25
35
  export const hasLivePrice = (priceEntry) => priceEntry?.live?.falUnitPrice !== false;
26
36
 
@@ -28,7 +38,10 @@ export const hasLivePrice = (priceEntry) => priceEntry?.live?.falUnitPrice !== f
28
38
  export function liveToPricing(unit, unitPrice, bundledPricing) {
29
39
  const u = String(unit ?? '').toLowerCase();
30
40
  if (/^(second|seconds|sec)$/.test(u)) return { type: 'perSecond', usd: unitPrice };
31
- if (/^(image|images)$/.test(u)) return { type: 'perImage', usd: unitPrice };
41
+ if (/^(image|images)$/.test(u)) {
42
+ // The unit price is the output image; an input-image fee on record still applies.
43
+ return { type: 'perImage', usd: unitPrice, ...(bundledPricing?.inputFee ? { inputFee: bundledPricing.inputFee } : {}) };
44
+ }
32
45
  if (/token/.test(u) && bundledPricing?.type === 'perToken') {
33
46
  // fal's units look like "1000 tokens" or "1m tokens" (fal.ai/pricing.md).
34
47
  const per1k = /\b(1m|1 ?million|1,?000,?000)\b/.test(u) ? unitPrice / 1000
@@ -44,10 +57,13 @@ export default {
44
57
  envVar: 'FAL_KEY',
45
58
  billing: { failedJobCharged: false, validationErrorMayCharge: true },
46
59
 
47
- buildRequest(r, { entry, imageUrl }) {
60
+ buildRequest(r, inputs) {
61
+ const { entry, imageUrls } = inputs;
62
+ // fal names inputs in the prompt as @Image1, @Audio1.
48
63
  const body = r.kind === 'image'
49
- ? { prompt: r.prompt, ...imageFields(r, entry, 'resolution') }
50
- : { prompt: r.prompt, ...videoFields(r, { durationAsString: true, entry }), ...(imageUrl ? { image_url: imageUrl } : {}) };
64
+ ? { prompt: r.prompt, ...imageFields(r, entry, 'resolution'), ...editImages(r, entry, imageUrls) }
65
+ : { prompt: promptFor(r, 'plain'), ...videoFields(r, { durationAsString: true, entry }),
66
+ ...videoMedia(r, entry, VIDEO_INPUTS, inputs) };
51
67
  return { method: 'POST', url: `${QUEUE}/${endpointOf(r, entry)}`, body };
52
68
  },
53
69
 
@@ -73,7 +89,7 @@ export default {
73
89
 
74
90
  async livePrice(r, ctx, { entry, bundled, frameSizes }) {
75
91
  if (!hasLivePrice(bundled?.entry)) return null;
76
- const endpoint = endpointOf(r, entry);
92
+ const endpoint = pricedEndpoint(r, entry);
77
93
  const p = (await this.unitPrices([endpoint], ctx)).get(endpoint);
78
94
  if (!p) return null;
79
95
  const pricing = liveToPricing(p.unit, p.unitPrice, bundled?.entry?.pricing);
@@ -87,9 +103,9 @@ export default {
87
103
  return typeof balance === 'number' ? balance : null;
88
104
  },
89
105
 
90
- async upload(filePath, ctx) {
91
- return asRejection('the image to fal', async () => {
92
- const { blob, name, type } = fileBlob(filePath);
106
+ async upload(filePath, ctx, contentType) {
107
+ return asRejection(`${uploadLabel(contentType)} to fal`, async () => {
108
+ const { blob, name, type } = fileBlob(filePath, contentType);
93
109
  const init = await http(ctx, { method: 'POST', url: STORAGE, headers: auth(ctx), timeoutMs: 30_000,
94
110
  json: { content_type: type, file_name: name } });
95
111
  if (!init.ok || !init.json?.upload_url) throw new Error(`HTTP ${init.status}: ${describeBody(init)}`);
@@ -100,8 +116,9 @@ export default {
100
116
  });
101
117
  },
102
118
 
103
- async submit(r, ctx, { entry, imageUrl }) {
104
- const { url, body } = this.buildRequest(r, { entry, imageUrl });
119
+ async submit(r, ctx, inputs) {
120
+ const { entry } = inputs;
121
+ const { url, body } = this.buildRequest(r, inputs);
105
122
  const res = await postJob(ctx, { url, headers: auth(ctx), json: body });
106
123
  const j = res.json;
107
124
  if (!j?.request_id) throw new SubmitUnknown(`no request id in the response: ${describeBody(res)}`);
@@ -0,0 +1,250 @@
1
+ // Higgsfield adapter. API: https://docs.higgsfield.ai (the pay-as-you-go API, not the
2
+ // higgsfield.ai website plans). Higgsfield doesn't charge for failed or moderated (nsfw) jobs, and
3
+ // refunds a cancelled queued job. There's no balance API: an empty balance shows up as a 403 when
4
+ // submitting, which is a clear rejection.
5
+ //
6
+ // Submits carry an Idempotency-Key. After a timeout, network error or 5xx the same request is sent
7
+ // again with the same key, and Higgsfield returns the original request instead of creating a
8
+ // second one (https://docs.higgsfield.ai/docs/concepts/idempotency.md).
9
+ import { randomUUID } from 'node:crypto';
10
+ import { http, NetworkError, describeBody } from '../http.js';
11
+ import { SubmitRejected, SubmitUnknown } from './errors.js';
12
+ import { SUBMIT_TIMEOUT_MS, readError, fileBlob, uploadLabel, asRejection, videoFields, videoMedia, imageFields, editImages, endpointPath } from './common.js';
13
+ import { pricedRequest, promptFor } from '../request.js';
14
+
15
+ const BASE = 'https://api.higgsfield.ai';
16
+ /** Hosts that may receive the key. A status URL from a response is used only on one of these. */
17
+ const API_HOSTS = new Set(['api.higgsfield.ai', 'platform.higgsfield.ai']);
18
+ const auth = (ctx) => ({ Authorization: `Key ${ctx.key}` });
19
+
20
+ /** The estimate endpoint needs a prompt; `quote` may not have one, and the price doesn't depend on it. */
21
+ const ESTIMATE_PROMPT = 'price estimate';
22
+ const RETRY_DELAYS_MS = [1_000, 2_000];
23
+ const MAX_RETRY_AFTER_MS = 30_000;
24
+ /** Each attempt can take up to SUBMIT_TIMEOUT_MS; don't start another one after this long. */
25
+ const RETRY_DEADLINE_MS = 240_000;
26
+
27
+ const STATES = { queued: 'queued', in_progress: 'running', completed: 'succeeded', failed: 'failed', nsfw: 'failed',
28
+ canceled: 'cancelled' };
29
+
30
+ const VIDEO_INPUTS = { first: 'image_url', last: 'end_image_url', refImages: 'image_urls', refAudio: 'audio_urls' };
31
+
32
+ /** Higgsfield documents no way to name an input in the prompt; it gets the plain "@Image1" form. */
33
+ function body(r, entry, inputs = {}) {
34
+ const text = r.kind === 'image' ? r.prompt : promptFor(r, 'plain');
35
+ const prompt = typeof text === 'string' && text.trim() ? { prompt: text } : {};
36
+ if (r.kind === 'image') return { ...prompt, ...imageFields(r, entry, 'resolution'), ...editImages(r, entry, inputs.imageUrls) };
37
+ return { ...prompt, ...videoFields(r, { entry }), ...videoMedia(r, entry, VIDEO_INPUTS, inputs) };
38
+ }
39
+
40
+ /**
41
+ * Stand-in addresses for the reference inputs of an estimate: the price doesn't depend on which
42
+ * files they are, local files aren't uploaded yet, and the user's own addresses needn't be sent
43
+ * for a price.
44
+ */
45
+ function estimateInputs(r) {
46
+ if (r.mode !== 'reference-to-video') return {};
47
+ return {
48
+ refImageUrls: r.refImages.map((_, i) => `https://example.com/reference-image-${i + 1}.png`),
49
+ refAudioUrls: r.refAudio.map((_, i) => `https://example.com/reference-audio-${i + 1}.wav`),
50
+ };
51
+ }
52
+
53
+ function isApiUrl(url) {
54
+ try {
55
+ const u = new URL(url);
56
+ return u.protocol === 'https:' && API_HOSTS.has(u.hostname) && u.port === '' && !u.username && !u.password;
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ const statusUrlFor = (url, id) => (typeof url === 'string' && isApiUrl(url) ? url
63
+ : `${BASE}/requests/${encodeURIComponent(id)}/status`);
64
+
65
+ const correlationOf = (res) => res?.headers?.get?.('x-correlation-id') || null;
66
+
67
+ /**
68
+ * The per-second rate for `resolution` from the description answer that Seedance models get
69
+ * instead of an amount. It comes in two forms:
70
+ * - one list: "Standard self-serve rates in USD per video second: 480p: $0.0804; ... Total price
71
+ * = selected rate × output duration in seconds."
72
+ * - two lists, from the reference endpoint: "... rates in USD per second of generated video.
73
+ * - Without video input: 480p: $0.0804; ... - With video input: 480p: $0.0991; ... Total price
74
+ * = selected rate × output duration in seconds." cheapgen sends no input video, so only the
75
+ * "Without video input" list is read.
76
+ * Null unless the text still says the things this relies on, so changed wording falls back to
77
+ * the bundled price.
78
+ */
79
+ function rateFromDescription(text, resolution) {
80
+ if (typeof text !== 'string' || typeof resolution !== 'string') return null;
81
+ if (!/rate\s*[×x*]\s*output duration in seconds/i.test(text)) return null;
82
+ let rates;
83
+ if (/\bUSD per video second\b/i.test(text)) rates = text;
84
+ else if (/\bUSD per second of generated video\b/i.test(text)) rates = text.match(/^.*\bWithout video input\s*:(.*)$/im)?.[1];
85
+ if (!rates) return null;
86
+ for (const [, label, value] of rates.matchAll(/([0-9][0-9.]*[a-z]+)\s*:\s*\$\s*([0-9][0-9.eE+-]*)/gi)) {
87
+ if (label.toLowerCase() !== resolution.toLowerCase()) continue;
88
+ const rate = Number(value.replace(/\.$/, ''));
89
+ return Number.isFinite(rate) && rate >= 0 ? rate : null;
90
+ }
91
+ return null;
92
+ }
93
+
94
+ /** Seconds from a Retry-After header as milliseconds (capped), or the default delay for this retry. */
95
+ function retryDelay(res, retry) {
96
+ const header = res?.headers?.get?.('retry-after');
97
+ const seconds = typeof header === 'string' && header.trim() ? Number(header) : NaN;
98
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);
99
+ return RETRY_DELAYS_MS[retry];
100
+ }
101
+
102
+ export default {
103
+ id: 'higgsfield',
104
+ displayName: 'Higgsfield',
105
+ envVar: 'HIGGSFIELD_API_KEY',
106
+ billing: { failedJobCharged: false, validationErrorMayCharge: false },
107
+ /** Higgsfield keys are two values joined: the key id and the secret. */
108
+ /** The audio types the upload endpoint accepts: WAV, not MP3. */
109
+ audioUploadTypes: ['wav'],
110
+ keyFormat: {
111
+ prompt: 'Higgsfield key (KEY_ID:KEY_SECRET, hidden): ',
112
+ pattern: /^[^:\s]+:[^:\s]+$/,
113
+ hint: 'a Higgsfield key is the key id and the secret joined by a colon, KEY_ID:KEY_SECRET '
114
+ + '(both from console.higgsfield.ai). Nothing was stored.',
115
+ },
116
+
117
+ buildRequest(r, inputs) {
118
+ return { method: 'POST', url: `${BASE}/${endpointPath(r, inputs.entry)}`, body: body(r, inputs.entry, inputs) };
119
+ },
120
+
121
+ /**
122
+ * The price from Higgsfield's estimate endpoint. Most models get the account's own amount
123
+ * ({type: "estimate", usd}, discounts included); Seedance models get only the standard
124
+ * per-second rates as text ({type: "description"}), priced here as rate × duration.
125
+ * Image-to-video is estimated as text-to-video with the same settings: Higgsfield prices both
126
+ * the same, and an image-to-video estimate would need an uploaded image. An image edit is
127
+ * estimated as text-to-image for the same reason: the price is the same and input images add
128
+ * nothing. The price doesn't depend on the aspect ratio, so "follow the input" is asked as 1:1.
129
+ * A reference-to-video request is estimated on its own endpoint, with stand-in addresses for
130
+ * the inputs; its answer lists rates with and without an input video.
131
+ */
132
+ async livePrice(r, ctx, { entry }) {
133
+ let req = pricedRequest(r);
134
+ if (req.mode === 'image-to-video') {
135
+ req = { ...req, mode: 'text-to-video', image: undefined, imageIsLocal: false, lastImage: undefined };
136
+ }
137
+ if (req.mode === 'image-edit') {
138
+ req = { ...req, mode: 'text-to-image', images: undefined, aspectRatio: req.aspectRatio === 'auto' ? '1:1' : req.aspectRatio };
139
+ }
140
+ if (!(typeof req.prompt === 'string' && req.prompt.trim())) req = { ...req, prompt: ESTIMATE_PROMPT };
141
+ if (entry.modes && typeof entry.modes[req.mode] !== 'string') return null;
142
+ try {
143
+ const res = await http(ctx, { method: 'POST', url: `${BASE}/estimate/${endpointPath(req, entry)}`, headers: auth(ctx),
144
+ json: body(req, entry, estimateInputs(req)), timeoutMs: 10_000, retries: 0 });
145
+ const j = res.ok ? res.json : undefined;
146
+ if (j?.type === 'description') {
147
+ const rate = req.kind === 'video' ? rateFromDescription(j.pricing_description, req.resolution) : null;
148
+ return rate === null || !(req.duration > 0) ? null : { usd: rate * req.duration, unit: 'request' };
149
+ }
150
+ const raw = j?.usd;
151
+ if (!(typeof raw === 'number' || (typeof raw === 'string' && raw.trim()))) return null;
152
+ const usd = Number(raw);
153
+ return Number.isFinite(usd) && usd >= 0 ? { usd, unit: 'request' } : null;
154
+ } catch {
155
+ return null;
156
+ }
157
+ },
158
+
159
+ async balance() {
160
+ return null;
161
+ },
162
+
163
+ async upload(filePath, ctx, contentType) {
164
+ return asRejection(`${uploadLabel(contentType)} to Higgsfield`, async () => {
165
+ const { blob, type } = fileBlob(filePath, contentType);
166
+ const init = await http(ctx, { method: 'POST', url: `${BASE}/files/generate-upload-url`, headers: auth(ctx),
167
+ json: { content_type: type }, timeoutMs: 30_000 });
168
+ const j = init.json;
169
+ if (!init.ok) throw new Error(`HTTP ${init.status}: ${describeBody(init)}`);
170
+ if (typeof j?.upload_url !== 'string' || !/^https:\/\//.test(j.upload_url) || typeof j?.public_url !== 'string') {
171
+ throw new Error('no upload URL in the response');
172
+ }
173
+ // Exactly the headers Higgsfield asked for. The API key must never go to the storage host.
174
+ const headers = Object.fromEntries(Object.entries(j.upload_headers ?? {})
175
+ .filter(([k, v]) => typeof v === 'string' && k.toLowerCase() !== 'authorization'));
176
+ const put = await http(ctx, { method: 'PUT', url: j.upload_url, body: blob, headers, timeoutMs: 300_000 });
177
+ if (!put.ok) throw new Error(`HTTP ${put.status}: ${describeBody(put)}`);
178
+ return j.public_url;
179
+ });
180
+ },
181
+
182
+ async submit(r, ctx, inputs) {
183
+ const { url, body: json } = this.buildRequest(r, inputs);
184
+ const idempotencyKey = randomUUID();
185
+ const headers = { ...auth(ctx), 'Idempotency-Key': idempotencyKey };
186
+ const now = () => (ctx.now ? ctx.now().getTime() : Date.now());
187
+ const started = now();
188
+ let correlationId = null;
189
+ const unknown = (problem, status = null) => new SubmitUnknown(
190
+ `${problem}. Higgsfield idempotency key: ${idempotencyKey}${correlationId ? `, correlation id: ${correlationId}` : ''}`,
191
+ { status, details: { idempotencyKey, correlationId } });
192
+
193
+ for (let attempt = 0; ; attempt += 1) {
194
+ let res = null;
195
+ let problem;
196
+ let status = null;
197
+ try {
198
+ res = await http(ctx, { method: 'POST', url, headers, json, timeoutMs: SUBMIT_TIMEOUT_MS });
199
+ } catch (err) {
200
+ if (!(err instanceof NetworkError)) throw err;
201
+ problem = err.timeout ? 'the submit request timed out' : err.message;
202
+ }
203
+ if (res) {
204
+ correlationId = correlationOf(res) ?? correlationId;
205
+ if (res.status >= 200 && res.status < 300) {
206
+ const id = res.json?.request_id;
207
+ if (!id) throw unknown(`no request id in the response: ${describeBody(res)}`);
208
+ return { nativeId: String(id), meta: { statusUrl: statusUrlFor(res.json.status_url, id), correlationId } };
209
+ }
210
+ const message = `HTTP ${res.status}: ${describeBody(res)}`;
211
+ if (res.status < 500) {
212
+ if (attempt === 0) {
213
+ throw new SubmitRejected(`${message}${correlationId ? ` (correlation id ${correlationId})` : ''}`, { status: res.status });
214
+ }
215
+ // An earlier attempt may have been accepted, so this answer doesn't prove nothing was created.
216
+ throw unknown(`${message}, after an earlier attempt whose outcome is unknown`, res.status);
217
+ }
218
+ problem = message;
219
+ status = res.status;
220
+ }
221
+ if (attempt >= RETRY_DELAYS_MS.length || now() - started >= RETRY_DEADLINE_MS) throw unknown(problem, status);
222
+ await ctx.sleep?.(retryDelay(res, attempt));
223
+ }
224
+ },
225
+
226
+ async status(nativeId, ctx, meta) {
227
+ const res = await http(ctx, { url: statusUrlFor(meta?.statusUrl, nativeId), headers: auth(ctx), timeoutMs: 30_000 });
228
+ if (res.status === 404) {
229
+ return { state: 'failed', outputs: [], error: { code: '404', providerFault: false,
230
+ message: `Higgsfield has no request ${nativeId} for this key. It deletes request data 7 days after a job `
231
+ + 'finishes, so an older job\'s files are gone.' } };
232
+ }
233
+ if (!res.ok) throw readError(`HTTP ${res.status}: ${describeBody(res)}`, res.status);
234
+ const j = res.json ?? {};
235
+ const state = STATES[j.status] ?? 'running';
236
+ if (state === 'succeeded') {
237
+ const outputs = [j.video?.url, ...(Array.isArray(j.images) ? j.images : []).map((i) => i?.url)]
238
+ .filter((u) => typeof u === 'string');
239
+ return { state, outputs };
240
+ }
241
+ if (j.status === 'nsfw') {
242
+ return { state, outputs: [], error: { code: 'nsfw', providerFault: false,
243
+ message: 'Higgsfield\'s content moderation rejected the input or the output. The job wasn\'t charged.' } };
244
+ }
245
+ if (state === 'failed') {
246
+ return { state, outputs: [], error: { code: null, message: j.error ? String(j.error) : 'the job failed', providerFault: false } };
247
+ }
248
+ return { state, outputs: [] };
249
+ },
250
+ };
@@ -3,28 +3,78 @@ import kie from './kie.js';
3
3
  import replicate from './replicate.js';
4
4
  import wavespeed from './wavespeed.js';
5
5
  import fal from './fal.js';
6
+ import higgsfield from './higgsfield.js';
7
+ import { entryFor, variantFor } from '../catalog.js';
6
8
 
7
- export const ADAPTERS = Object.freeze({ kie, replicate, wavespeed, fal });
9
+ export const ADAPTERS = Object.freeze({ kie, replicate, wavespeed, fal, higgsfield });
8
10
 
9
11
  /**
10
12
  * Does `providerId` offer this request, according to data/models.json? A provider-level
11
- * `modes`, `resolutions`, `durations`, `sizes` or `aspectRatios` entry narrows the model's options.
13
+ * `modes`, `resolutions`, `durations`, `sizes` or `aspectRatios` entry narrows the model's options, and
14
+ * `autoDuration: false` means the provider can't let the model pick the length. An image edit
15
+ * also has to fit the provider's edit block: its input count, file size and total-pixel limits,
16
+ * and a way to follow the input image when no aspect ratio was given.
12
17
  * @returns {{ ok: true, entry: object } | { ok: false, reason: string }}
13
18
  */
14
19
  export function supports(catalog, providerId, r) {
15
- const entry = catalog.models[r.model]?.providers?.[providerId];
20
+ const entry = entryFor(catalog, providerId, r);
16
21
  const no = (reason) => ({ ok: false, reason: `${providerId} ${reason}` });
17
22
  if (!entry) return no(`doesn't offer ${r.model}`);
18
- if (entry.modes && typeof entry.modes[r.mode] !== 'string') return no(`doesn't offer ${r.model} as ${r.mode}`);
23
+ if (r.mode === 'image-edit') {
24
+ const why = editProblem(r, entry.edit);
25
+ if (why) return no(why);
26
+ } else if (entry.modes && typeof entry.modes[r.mode] !== 'string') return no(`doesn't offer ${r.model} as ${r.mode}`);
27
+ if (r.mode === 'reference-to-video') {
28
+ const why = referenceProblem(r, entry, ADAPTERS[providerId]);
29
+ if (why) return no(why);
30
+ }
19
31
  if (r.resolution && entry.resolutions && !entry.resolutions.includes(r.resolution)) {
20
32
  return no(`doesn't offer ${r.model} at ${r.resolution}`);
21
33
  }
34
+ // A resolution the model doesn't list itself is sold only by the provider whose variant has it.
35
+ const model = catalog.models[r.model];
36
+ if (r.resolution && model.resolutions && !model.resolutions.includes(r.resolution)
37
+ && variantFor(model, r.resolution)?.provider !== providerId) {
38
+ return no(`doesn't offer ${r.model} at ${r.resolution}`);
39
+ }
22
40
  if (r.size && entry.sizes && !entry.sizes.includes(r.size)) return no(`doesn't offer ${r.model} at size ${r.size}`);
23
- if (entry.aspectRatios && !entry.aspectRatios.includes(r.aspectRatio)) {
41
+ if (entry.aspectRatios && r.aspectRatio !== 'auto' && !entry.aspectRatios.includes(r.aspectRatio)) {
24
42
  return no(`doesn't offer ${r.model} at ${r.aspectRatio}`);
25
43
  }
44
+ if (entry.autoDuration === false && r.autoDuration) return no(`doesn't offer ${r.model} with --duration auto`);
26
45
  if (entry.durations && !r.autoDuration && (r.duration < entry.durations.min || r.duration > entry.durations.max)) {
27
46
  return no(`offers ${r.model} only from ${entry.durations.min} to ${entry.durations.max} seconds`);
28
47
  }
29
48
  return { ok: true, entry };
30
49
  }
50
+
51
+ /** Why a provider can't take these reference inputs, or null when it can. */
52
+ function referenceProblem(r, entry, adapter) {
53
+ if (!r.refImages?.length && !entry.references?.audioAlone) {
54
+ return `doesn't say it takes reference audio alone for ${r.model} (add a reference image)`;
55
+ }
56
+ const types = adapter?.audioUploadTypes;
57
+ const refused = types && r.refAudio?.find((a) => a.isLocal && !types.includes(a.type));
58
+ if (refused) {
59
+ return `can't take a local ${refused.type.toUpperCase()} file: its upload accepts ${types.map((t) => t.toUpperCase()).join(', ')} `
60
+ + 'audio only (give the file as a URL instead)';
61
+ }
62
+ return null;
63
+ }
64
+
65
+ /** Why a provider can't take this image edit, or null when it can. */
66
+ function editProblem(r, edit) {
67
+ if (!edit) return `doesn't offer ${r.model} with input images`;
68
+ const images = r.images ?? [];
69
+ if (images.length > edit.maxImages) return `takes at most ${edit.maxImages} input images for ${r.model}`;
70
+ if (edit.maxFileMB && images.some((i) => i.bytes > edit.maxFileMB * 1e6)) {
71
+ return `takes input images up to ${edit.maxFileMB} MB each for ${r.model}`;
72
+ }
73
+ if (edit.maxTotalMP && typeof r.inputPixels === 'number' && r.inputPixels > edit.maxTotalMP * 1e6) {
74
+ return `takes at most ${edit.maxTotalMP} megapixels of input images in total for ${r.model}`;
75
+ }
76
+ if (r.aspectRatio === 'auto' && !edit.follow && !r.effectiveAspect) {
77
+ return `needs --aspect for ${r.model}: it can't follow an input image given as a URL`;
78
+ }
79
+ return null;
80
+ }