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.
@@ -0,0 +1,383 @@
1
+ // MCP tools. Each one runs the matching CLI command in-process with --json, so validation,
2
+ // key redaction, the cost limit and the spend log work exactly as they do on the command line.
3
+ // `run` is the only tool that spends money, and it only takes a quoteId from `quote`.
4
+ import crypto from 'node:crypto';
5
+ import path from 'node:path';
6
+ import { main } from '../cli/main.js';
7
+ import { loadCatalog } from '../catalog.js';
8
+ import { RpcError } from './errors.js';
9
+
10
+ export const QUOTE_TTL_MS = 10 * 60_000;
11
+ const STATE_TTL_MS = 5 * 60_000;
12
+ const WAIT_DEFAULT_SECONDS = 60;
13
+
14
+ const str = (description) => ({ type: 'string', description });
15
+ const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
16
+
17
+ const REQUEST_PROPERTIES = {
18
+ model: str('Model id from the `models` tool, e.g. seedance-2.0-mini or seedream-5.5.'),
19
+ prompt: str('What to generate. Needed before the quote can be used with `run`.'),
20
+ image: str('Video models only. First frame for image-to-video: an https URL or an absolute local file path.'),
21
+ images: { type: 'array', items: { type: 'string' }, description: 'Image models only. Input images to edit or combine: '
22
+ + 'https URLs or absolute local file paths (PNG, JPEG or WebP), in order. Local files are uploaded to the chosen provider. '
23
+ + 'Without an aspect the result follows the first image.' },
24
+ lastImage: str('Video models only. Last frame of the video, used together with `image` (the first frame): an https URL or an '
25
+ + 'absolute local file path (PNG, JPEG or WebP).'),
26
+ refImages: { type: 'array', items: { type: 'string' }, description: 'Video models only. Reference images the video should '
27
+ + 'follow (characters, products, style): https URLs or absolute local file paths (PNG, JPEG or WebP), in order. Name them in '
28
+ + 'the prompt as @image1, @image2. Not together with `image` or `lastImage`. The models tool shows how many a model takes.' },
29
+ refAudio: { type: 'array', items: { type: 'string' }, description: 'Video models only. Reference audio for the video (voice, '
30
+ + 'music, sound): https URLs or absolute local file paths (WAV or MP3, 2 to 15 seconds, 30 on the 2.5 models), in order. '
31
+ + 'Name them in the prompt as @audio1. The Seedance 2.0 models also need at least one reference image.' },
32
+ resolution: str('Video resolution: 480p, 720p, 1080p or 4k (only some models; the models tool shows which, and which are a provider\'s upscaled variant that the user must allow first). Default 720p.'),
33
+ size: str('Image size, e.g. 1K, 2K or 4K. Default 1K, or the model\'s smallest.'),
34
+ duration: { type: 'number', description: 'Video length in seconds. Default 5.' },
35
+ aspect: str('Aspect ratio, e.g. 16:9, 9:16 or 1:1. Default 16:9.'),
36
+ audio: { type: 'boolean', description: 'Generate audio with the video (models that support it). Default true.' },
37
+ provider: str('Use only this provider: kie, replicate, wavespeed, fal or higgsfield.'),
38
+ exclude: { type: 'array', items: { type: 'string' }, description: 'Providers to skip.' },
39
+ };
40
+
41
+ const closed = (properties, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
42
+
43
+ export const TOOL_DEFINITIONS = [
44
+ {
45
+ name: 'models',
46
+ title: 'List models',
47
+ description: 'Lists the video and image models cheapgen supports, with their resolutions or sizes and the providers that offer each.',
48
+ inputSchema: closed({ search: str('Only models whose id or name contains this text.') }),
49
+ annotations: { title: 'List models', ...READ_ONLY },
50
+ },
51
+ {
52
+ name: 'providers',
53
+ title: 'List providers',
54
+ description: 'Lists the providers (Kie, Replicate, WaveSpeed, fal, Higgsfield), whether each has a key, and their balances where the provider reports one.',
55
+ inputSchema: closed({}),
56
+ annotations: { title: 'List providers', ...READ_ONLY },
57
+ },
58
+ {
59
+ name: 'quote',
60
+ title: 'Price a generation',
61
+ description: 'Prices a generation on every provider and picks the cheapest connected one. Spends nothing. Returns a quoteId, '
62
+ + 'valid for 10 minutes, that `run` needs. Tell the user the provider and price before running.',
63
+ inputSchema: closed(REQUEST_PROPERTIES, ['model']),
64
+ annotations: { title: 'Price a generation', ...READ_ONLY },
65
+ },
66
+ {
67
+ name: 'run',
68
+ title: 'Start a generation (spends money)',
69
+ description: 'Starts the generation priced by a quote, on the cheapest provider. This spends the user\'s money (provider credits, '
70
+ + 'in USD). Call it only after the user agreed to the quoted price. Above the user\'s cost limit the user is asked to confirm. '
71
+ + 'Returns a job id at once; use `wait_job` for the result. Never call it again after an unknown_outcome error.',
72
+ inputSchema: closed({ quoteId: str('The quoteId returned by `quote`.') }, ['quoteId']),
73
+ annotations: { title: 'Start a generation', readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
74
+ },
75
+ {
76
+ name: 'job_status',
77
+ title: 'Check a job',
78
+ description: 'Checks a job once and returns its state (running, succeeded, failed) and any result URLs. Job ids look like kie:task_123.',
79
+ inputSchema: closed({ job: str('Job id from `run`, e.g. kie:task_123.') }, ['job']),
80
+ annotations: { title: 'Check a job', ...READ_ONLY },
81
+ },
82
+ {
83
+ name: 'wait_job',
84
+ title: 'Wait for a job',
85
+ description: 'Waits for a job to finish, up to timeoutSeconds, then saves the results to the cheapgen-out folder and returns the file paths. '
86
+ + 'If the job is still running when the time is up, it returns state "running"; call it again to keep waiting.',
87
+ inputSchema: closed({
88
+ job: str('Job id from `run`, e.g. kie:task_123.'),
89
+ timeoutSeconds: { type: 'integer', minimum: 1, maximum: 120, description: `How long to wait. Default ${WAIT_DEFAULT_SECONDS}.` },
90
+ }, ['job']),
91
+ annotations: { title: 'Wait for a job', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
92
+ },
93
+ {
94
+ name: 'spend',
95
+ title: 'Summarize spending',
96
+ description: 'Summarizes the local spend log: each job with its estimate, the actual charge where the provider reports it, and totals.',
97
+ inputSchema: closed({ since: str('Only jobs from this date on, e.g. 2026-11-01.') }),
98
+ annotations: { title: 'Summarize spending', ...READ_ONLY },
99
+ },
100
+ ];
101
+
102
+ const BY_NAME = new Map(TOOL_DEFINITIONS.map((t) => [t.name, t]));
103
+
104
+ // ---------------------------------------------------------------------------------------------
105
+ // Results
106
+
107
+ const textOf = (obj) => JSON.stringify(obj, null, 2);
108
+
109
+ function result(structured, { isError = false, notes = '' } = {}) {
110
+ const content = [{ type: 'text', text: textOf(structured) }];
111
+ if (notes.trim()) content.push({ type: 'text', text: notes.trim() });
112
+ return { content, structuredContent: structured, ...(isError ? { isError: true } : {}) };
113
+ }
114
+
115
+ const failure = (code, message, extra = {}) => result({ error: { code, message, provider: null, job: null, ...extra } }, { isError: true });
116
+
117
+ // ---------------------------------------------------------------------------------------------
118
+ // Arguments
119
+
120
+ /** Checks arguments against the tool's (simple, flat) schema. Returns an error message or null. */
121
+ function invalidArguments(schema, args) {
122
+ if (!args || typeof args !== 'object' || Array.isArray(args)) return 'arguments must be an object';
123
+ for (const key of Object.keys(args)) {
124
+ if (!(key in schema.properties)) return `unknown argument "${key}"`;
125
+ }
126
+ for (const key of schema.required) {
127
+ if (args[key] === undefined) return `missing required argument "${key}"`;
128
+ }
129
+ for (const [key, value] of Object.entries(args)) {
130
+ const p = schema.properties[key];
131
+ const bad = (want) => `"${key}" must be ${want}`;
132
+ if (p.type === 'string' && typeof value !== 'string') return bad('a string');
133
+ if (p.type === 'boolean' && typeof value !== 'boolean') return bad('true or false');
134
+ if (p.type === 'number' && (typeof value !== 'number' || !Number.isFinite(value))) return bad('a number');
135
+ if (p.type === 'integer' && !Number.isInteger(value)) return bad('a whole number');
136
+ if (p.type === 'array' && (!Array.isArray(value) || value.some((v) => typeof v !== p.items.type))) return bad('a list of strings');
137
+ if (p.minimum !== undefined && value < p.minimum) return bad(`at least ${p.minimum}`);
138
+ if (p.maximum !== undefined && value > p.maximum) return bad(`at most ${p.maximum}`);
139
+ }
140
+ return null;
141
+ }
142
+
143
+ function requestArgs(a) {
144
+ const args = [a.model];
145
+ const opt = (flag, v) => { if (v !== undefined) args.push(flag, String(v)); };
146
+ opt('--prompt', a.prompt);
147
+ opt('--image', a.image);
148
+ for (const img of a.images ?? []) args.push('--image', img);
149
+ opt('--last-image', a.lastImage);
150
+ for (const img of a.refImages ?? []) args.push('--ref-image', img);
151
+ for (const clip of a.refAudio ?? []) args.push('--ref-audio', clip);
152
+ opt('--res', a.resolution);
153
+ opt('--size', a.size);
154
+ opt('--duration', a.duration);
155
+ opt('--aspect', a.aspect);
156
+ if (a.audio !== undefined) args.push(a.audio ? '--audio' : '--no-audio');
157
+ opt('--provider', a.provider);
158
+ for (const id of a.exclude ?? []) args.push('--exclude', id);
159
+ return args;
160
+ }
161
+
162
+ /**
163
+ * "image" is a video's first frame and "images" are an image model's inputs. Says which one to
164
+ * use when the other was given, and that a last frame and references are for video models; null
165
+ * when the fields fit the model (or the model is unknown, which the command reports itself).
166
+ */
167
+ function wrongImageField(ctx, a) {
168
+ const videoOnly = ['lastImage', 'refImages', 'refAudio'].find((field) => a[field] !== undefined);
169
+ if (a.image === undefined && a.images === undefined && !videoOnly) return null;
170
+ let kind;
171
+ try { kind = loadCatalog(ctx.io.dataDir).models[a.model]?.kind; } catch { return null; }
172
+ if (kind === 'image' && videoOnly) return `"${videoOnly}" is for video models, and ${a.model} is an image model`;
173
+ if (kind === 'image' && a.image !== undefined) {
174
+ return `${a.model} is an image model: pass its input images in "images" (a list), not "image"`;
175
+ }
176
+ if (kind === 'video' && a.images !== undefined) {
177
+ return `${a.model} is a video model: pass its first frame in "image" (one value), not "images"`;
178
+ }
179
+ return null;
180
+ }
181
+
182
+ /** True when `dir` is `parent` or inside it. */
183
+ function isInside(dir, parent) {
184
+ const rel = path.relative(path.resolve(parent), path.resolve(dir));
185
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
186
+ }
187
+
188
+ /**
189
+ * Where results are saved: <cwd>/cheapgen-out, or <home>/cheapgen-out when the server runs at a
190
+ * filesystem root or inside a plugin's own folder (some apps start plugin servers there, and that
191
+ * folder is replaced when the plugin updates).
192
+ */
193
+ function downloadDir(io) {
194
+ const cwd = path.resolve(io.cwd);
195
+ const pluginRoots = [io.env?.PLUGIN_ROOT, io.env?.CLAUDE_PLUGIN_ROOT, io.env?.CURSOR_PLUGIN_ROOT]
196
+ .filter((p) => typeof p === 'string' && p);
197
+ const useHome = path.parse(cwd).root === cwd || pluginRoots.some((root) => isInside(cwd, root));
198
+ return path.join(useHome ? io.homedir : cwd, 'cheapgen-out');
199
+ }
200
+
201
+ // ---------------------------------------------------------------------------------------------
202
+ // Running CLI commands
203
+
204
+ /** Runs `cheapgen <args> --json` in-process. Never reads the MCP connection's stdin. */
205
+ async function cli(io, args) {
206
+ let stdout = '';
207
+ let stderr = '';
208
+ const code = await main([...args, '--json'], {
209
+ ...io,
210
+ stdout: { write(s) { stdout += s; return true; } },
211
+ stderr: { write(s) { stderr += s; return true; } },
212
+ stdin: '',
213
+ readStdin: async () => '',
214
+ promptSecret: null,
215
+ });
216
+ let json;
217
+ try { json = JSON.parse(stdout); } catch {
218
+ json = { error: { code: 'bug', message: `cheapgen printed no JSON (exit ${code})`, provider: null, job: null } };
219
+ }
220
+ return { code, json, notes: stderr };
221
+ }
222
+
223
+ const fromCli = ({ code, json, notes }) => result(json, { isError: code !== 0, notes });
224
+
225
+ // ---------------------------------------------------------------------------------------------
226
+ // Tool handlers
227
+
228
+ const HANDLERS = {
229
+ models: (ctx, a) => cli(ctx.io, ['models', ...(a.search === undefined ? [] : ['--search', a.search])]).then(fromCli),
230
+ providers: (ctx) => cli(ctx.io, ['providers']).then(fromCli),
231
+ spend: (ctx, a) => cli(ctx.io, ['spend', ...(a.since === undefined ? [] : ['--since', a.since])]).then(fromCli),
232
+ job_status: (ctx, a) => cli(ctx.io, ['status', a.job]).then(fromCli),
233
+
234
+ async wait_job(ctx, a) {
235
+ const seconds = a.timeoutSeconds ?? WAIT_DEFAULT_SECONDS;
236
+ const r = await cli(ctx.io, ['wait', a.job, '--timeout', String(seconds), '--download', downloadDir(ctx.io)]);
237
+ if (r.code === 7) {
238
+ return result({ job: a.job, provider: r.json.error?.provider ?? null, state: 'running',
239
+ message: `Still running after ${seconds} seconds. Call wait_job again to keep waiting.` }, { notes: r.notes });
240
+ }
241
+ // Absolute paths, so the agent can open them wherever it runs.
242
+ if (r.code === 0 && Array.isArray(r.json.files)) r.json.files = r.json.files.map((p) => path.resolve(ctx.io.cwd, p));
243
+ return fromCli(r);
244
+ },
245
+
246
+ async quote(ctx, a) {
247
+ const wrong = wrongImageField(ctx, a);
248
+ if (wrong) return failure('usage', `quote: ${wrong}`);
249
+ const args = requestArgs(a);
250
+ const r = await cli(ctx.io, ['quote', ...args]);
251
+ if (r.code !== 0) return fromCli(r);
252
+ const now = ctx.io.now().getTime();
253
+ const quoteId = `q_${crypto.randomBytes(12).toString('base64url')}`;
254
+ const chosen = r.json.quotes?.find((q) => q.chosen) ?? null;
255
+ ctx.state.quotes.set(quoteId, {
256
+ args, hasPrompt: typeof a.prompt === 'string' && a.prompt.trim() !== '',
257
+ params: r.json.params ?? null, createdAt: now, used: false, usd: chosen?.usd ?? null,
258
+ });
259
+ return result({ ...r.json, quoteId, expiresAt: new Date(now + QUOTE_TTL_MS).toISOString() }, { notes: r.notes });
260
+ },
261
+
262
+ run: runQuote,
263
+ };
264
+
265
+ /** Calls one tool. Unknown tools and a missing name are JSON-RPC errors; bad arguments are tool errors. */
266
+ export async function callTool(ctx, params, call) {
267
+ const name = params?.name;
268
+ if (typeof name !== 'string' || !name) throw new RpcError(-32602, 'tools/call needs a tool name');
269
+ const tool = BY_NAME.get(name);
270
+ if (!tool) throw new RpcError(-32602, `Unknown tool: ${name}`);
271
+ const args = params.arguments ?? {};
272
+ const bad = invalidArguments(tool.inputSchema, args);
273
+ if (bad) return failure('usage', `${name}: ${bad}`);
274
+ return HANDLERS[name](ctx, args, params, call);
275
+ }
276
+
277
+ // ---------------------------------------------------------------------------------------------
278
+ // run: the only spending tool
279
+
280
+ const fmtUsd = (x) => (x === null || x === undefined ? 'an unknown amount' : `$${x < 0.1 ? x.toFixed(4) : x.toFixed(3)}`);
281
+
282
+ function describeRequest(params) {
283
+ if (!params) return 'this generation';
284
+ return Object.entries(params).filter(([k, v]) => v !== undefined && v !== null && k !== 'prompt')
285
+ .map(([k, v]) => `${k} ${v}`).join(', ');
286
+ }
287
+
288
+ async function runQuote(ctx, a, params, call) {
289
+ const q = ctx.state.quotes.get(a.quoteId);
290
+ const now = ctx.io.now().getTime();
291
+ if (!q || now - q.createdAt > QUOTE_TTL_MS) {
292
+ return failure('quote_expired', 'This quote is unknown or older than 10 minutes. Call `quote` again.');
293
+ }
294
+ if (q.used) return failure('quote_used', 'This quote was already used to start a job. Call `quote` again for another run.');
295
+ if (!q.hasPrompt) return failure('needs_prompt', 'This quote has no prompt. Call `quote` again with a prompt.');
296
+
297
+ // Price it again: live prices and balances can change after the quote.
298
+ const dry = await cli(ctx.io, ['run', ...q.args, '--dry-run']);
299
+ if (dry.code !== 0) return fromCli(dry);
300
+ const d = dry.json;
301
+ if (q.usd !== null && d.estimateUsd !== null && d.estimateUsd > q.usd + 1e-9) {
302
+ return failure('price_changed', `The price went up from ${fmtUsd(q.usd)} to ${fmtUsd(d.estimateUsd)} on ${d.provider}. `
303
+ + 'Call `quote` again and check the new price with the user.', { provider: d.provider });
304
+ }
305
+ if (!d.needsConfirmation) return submit(ctx, q, []);
306
+
307
+ const what = `${fmtUsd(d.estimateUsd)} on ${d.provider} for ${q.args[0]} (${describeRequest(q.params)})`;
308
+ const why = d.estimateUsd === null ? 'Its price is unknown.' : `That is over your cost limit of ${fmtUsd(d.limitUsd)}.`;
309
+ const overrideArgs = ['--yes', ...(d.estimateUsd === null ? [] : ['--max-cost', String(d.estimateUsd)])];
310
+ const elicitation = {
311
+ message: `Spend ${what}? ${why}`,
312
+ requestedSchema: {
313
+ type: 'object',
314
+ properties: { confirm: { type: 'boolean', title: 'Spend this money', description: `Start the run and spend ${fmtUsd(d.estimateUsd)}.` } },
315
+ required: ['confirm'],
316
+ },
317
+ };
318
+
319
+ if (!call.capabilities?.elicitation) {
320
+ const code = d.estimateUsd === null ? 'price_unknown' : 'over_limit';
321
+ return failure(code, `${what}: ${why} This app can't ask you to confirm, so nothing was sent. Raise the limit with `
322
+ + '`cheapgen config set maxCostPerRun <USD>`, or run it from the command line with --yes.', { provider: d.provider });
323
+ }
324
+
325
+ if (call.modern) {
326
+ if (params.requestState === undefined && params.inputResponses === undefined) {
327
+ return {
328
+ resultType: 'input_required',
329
+ inputRequests: { confirm_spend: { method: 'elicitation/create', params: { mode: 'form', ...elicitation } } },
330
+ requestState: signState(ctx, { quoteId: a.quoteId, exp: now + STATE_TTL_MS }),
331
+ };
332
+ }
333
+ const st = verifyState(ctx, params.requestState);
334
+ if (!st || st.quoteId !== a.quoteId || now > st.exp) {
335
+ return failure('bad_request_state', 'The confirmation is invalid or too old. Call `run` again to ask once more.');
336
+ }
337
+ const answer = params.inputResponses?.confirm_spend;
338
+ return accepted(answer) ? submit(ctx, q, overrideArgs) : declined();
339
+ }
340
+
341
+ let answer;
342
+ try {
343
+ const p = ctx.state.legacy?.version === '2025-11-25' ? { mode: 'form', ...elicitation } : elicitation;
344
+ answer = await ctx.requestClient('elicitation/create', p);
345
+ } catch {
346
+ return declined();
347
+ }
348
+ return accepted(answer) ? submit(ctx, q, overrideArgs) : declined();
349
+ }
350
+
351
+ function accepted(answer) {
352
+ const r = answer?.result ?? answer;
353
+ return r?.action === 'accept' && r?.content?.confirm === true;
354
+ }
355
+
356
+ const declined = () => failure('declined', 'The run was not confirmed, so nothing was sent and nothing was spent.');
357
+
358
+ async function submit(ctx, q, extra) {
359
+ q.used = true;
360
+ const r = await cli(ctx.io, ['run', ...q.args, ...extra]);
361
+ // A clean refusal before anything was sent leaves the quote usable. A submit, an unknown
362
+ // outcome (exit 5) or an unexpected error uses it up, so it can never be charged twice.
363
+ if ([2, 3, 4].includes(r.code)) q.used = false;
364
+ return fromCli(r);
365
+ }
366
+
367
+ // requestState: base64url(JSON) + "." + HMAC-SHA256, signed with a random key per server process.
368
+ function signState(ctx, payload) {
369
+ const body = Buffer.from(JSON.stringify({ ...payload, n: crypto.randomBytes(8).toString('base64url') })).toString('base64url');
370
+ return `${body}.${crypto.createHmac('sha256', ctx.state.stateKey).update(body).digest('base64url')}`;
371
+ }
372
+
373
+ function verifyState(ctx, token) {
374
+ if (typeof token !== 'string') return null;
375
+ const [body, mac, more] = token.split('.');
376
+ if (!body || !mac || more !== undefined) return null;
377
+ // Compare the encoded text, not decoded bytes: base64url decoding ignores the spare bits of the
378
+ // last character, so two different strings can decode to the same bytes.
379
+ const want = Buffer.from(crypto.createHmac('sha256', ctx.state.stateKey).update(body).digest('base64url'));
380
+ const got = Buffer.from(mac);
381
+ if (got.length !== want.length || !crypto.timingSafeEqual(got, want)) return null;
382
+ try { return JSON.parse(Buffer.from(body, 'base64url').toString('utf8')); } catch { return null; }
383
+ }
package/src/media.js ADDED
@@ -0,0 +1,231 @@
1
+ // Reads what cheapgen needs to know about a local input file without decoding it: the image
2
+ // type (from the file's first bytes, never its name), its size in bytes, and its width and height.
3
+ import fs from 'node:fs';
4
+
5
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
6
+ /** JPEG markers that start a frame header (SOF0-SOF15), which carries the size. */
7
+ const isFrameMarker = (m) => m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc;
8
+ /** Markers with no length field: the fill byte, TEM, RST0-RST7 and SOI. */
9
+ const isBareMarker = (m) => m === 0x01 || (m >= 0xd0 && m <= 0xd8);
10
+
11
+ export const IMAGE_MIME = Object.freeze({ png: 'image/png', jpeg: 'image/jpeg', webp: 'image/webp' });
12
+
13
+ /** Reads up to `length` bytes at `position`; shorter when the file ends first. */
14
+ function readAt(fd, position, length) {
15
+ const buf = Buffer.alloc(length);
16
+ const n = fs.readSync(fd, buf, 0, length, position);
17
+ return n === length ? buf : buf.subarray(0, n);
18
+ }
19
+
20
+ function pngSize(fd) {
21
+ const head = readAt(fd, 8, 16);
22
+ if (head.length < 16 || head.toString('latin1', 4, 8) !== 'IHDR') return null;
23
+ return { width: head.readUInt32BE(8), height: head.readUInt32BE(12) };
24
+ }
25
+
26
+ /** The Exif orientation (1-8) from an APP1 segment's bytes, or 1 when it has none. */
27
+ function exifOrientation(seg) {
28
+ if (seg.length < 14 || seg.toString('latin1', 0, 6) !== 'Exif\0\0') return 1;
29
+ const tiff = seg.subarray(6);
30
+ const order = tiff.toString('latin1', 0, 2);
31
+ if (order !== 'II' && order !== 'MM') return 1;
32
+ const u16 = (o) => (order === 'II' ? tiff.readUInt16LE(o) : tiff.readUInt16BE(o));
33
+ const u32 = (o) => (order === 'II' ? tiff.readUInt32LE(o) : tiff.readUInt32BE(o));
34
+ const ifd = u32(4);
35
+ if (ifd + 2 > tiff.length) return 1;
36
+ const count = u16(ifd);
37
+ for (let i = 0; i < count; i += 1) {
38
+ const at = ifd + 2 + i * 12;
39
+ if (at + 12 > tiff.length) break;
40
+ if (u16(at) === 0x0112) {
41
+ const value = u16(at + 8);
42
+ return value >= 1 && value <= 8 ? value : 1;
43
+ }
44
+ }
45
+ return 1;
46
+ }
47
+
48
+ /** Walks the segments up to the frame header. Orientations 5-8 turn the picture on its side. */
49
+ function jpegSize(fd, fileBytes) {
50
+ let pos = 2;
51
+ let orientation = 1;
52
+ while (pos + 4 <= fileBytes) {
53
+ const head = readAt(fd, pos, 4);
54
+ if (head.length < 4 || head[0] !== 0xff) return null;
55
+ const marker = head[1];
56
+ if (marker === 0xff) { pos += 1; continue; }
57
+ if (isBareMarker(marker)) { pos += 2; continue; }
58
+ if (marker === 0xd9 || marker === 0xda) return null;
59
+ const length = head.readUInt16BE(2);
60
+ if (length < 2) return null;
61
+ if (isFrameMarker(marker)) {
62
+ const frame = readAt(fd, pos + 4, 5);
63
+ if (frame.length < 5) return null;
64
+ const height = frame.readUInt16BE(1);
65
+ const width = frame.readUInt16BE(3);
66
+ return orientation >= 5 ? { width: height, height: width } : { width, height };
67
+ }
68
+ if (marker === 0xe1 && orientation === 1) orientation = exifOrientation(readAt(fd, pos + 4, Math.min(length - 2, 65_533)));
69
+ pos += 2 + length;
70
+ }
71
+ return null;
72
+ }
73
+
74
+ function webpSize(fd) {
75
+ const head = readAt(fd, 12, 18);
76
+ if (head.length < 18) return null;
77
+ const chunk = head.toString('latin1', 0, 4);
78
+ const data = head.subarray(8);
79
+ if (chunk === 'VP8 ') {
80
+ if (data[3] !== 0x9d || data[4] !== 0x01 || data[5] !== 0x2a) return null;
81
+ return { width: data.readUInt16LE(6) & 0x3fff, height: data.readUInt16LE(8) & 0x3fff };
82
+ }
83
+ if (chunk === 'VP8L') {
84
+ if (data[0] !== 0x2f) return null;
85
+ const bits = data.readUInt32LE(1);
86
+ return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
87
+ }
88
+ if (chunk === 'VP8X') {
89
+ return { width: data.readUIntLE(4, 3) + 1, height: data.readUIntLE(7, 3) + 1 };
90
+ }
91
+ return null;
92
+ }
93
+
94
+ /**
95
+ * @param {string} filePath
96
+ * @returns {{ type: 'png'|'jpeg'|'webp', bytes: number, width: number, height: number } | null}
97
+ * null when the file isn't a PNG, JPEG or WebP image whose size can be read
98
+ */
99
+ export function probeImage(filePath) {
100
+ const fd = fs.openSync(filePath, 'r');
101
+ try {
102
+ const bytes = fs.fstatSync(fd).size;
103
+ const head = readAt(fd, 0, 12);
104
+ let type = null;
105
+ let size = null;
106
+ if (head.length >= 8 && head.subarray(0, 8).equals(PNG_SIGNATURE)) {
107
+ type = 'png';
108
+ size = pngSize(fd);
109
+ } else if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) {
110
+ type = 'jpeg';
111
+ size = jpegSize(fd, bytes);
112
+ } else if (head.length >= 12 && head.toString('latin1', 0, 4) === 'RIFF' && head.toString('latin1', 8, 12) === 'WEBP') {
113
+ type = 'webp';
114
+ size = webpSize(fd);
115
+ }
116
+ if (!type || !size || !(size.width > 0) || !(size.height > 0)) return null;
117
+ return { type, bytes, width: size.width, height: size.height };
118
+ } finally {
119
+ fs.closeSync(fd);
120
+ }
121
+ }
122
+
123
+ export const AUDIO_MIME = Object.freeze({ wav: 'audio/wav', mp3: 'audio/mpeg' });
124
+
125
+ /** Length of a WAV file: the data chunk's bytes divided by the format chunk's byte rate. */
126
+ function wavSeconds(fd, fileBytes) {
127
+ let pos = 12;
128
+ let byteRate = null;
129
+ while (pos + 8 <= fileBytes) {
130
+ const head = readAt(fd, pos, 8);
131
+ if (head.length < 8) return null;
132
+ const id = head.toString('latin1', 0, 4);
133
+ const size = head.readUInt32LE(4);
134
+ if (id === 'fmt ') {
135
+ const fmt = readAt(fd, pos + 8, 12);
136
+ if (fmt.length < 12) return null;
137
+ byteRate = fmt.readUInt32LE(8);
138
+ } else if (id === 'data') {
139
+ if (!(byteRate > 0)) return null;
140
+ // A recorder that didn't go back to fill in the size leaves 0 or the maximum: use the rest of the file.
141
+ const rest = fileBytes - (pos + 8);
142
+ const dataBytes = size === 0 || size > rest ? rest : size;
143
+ return dataBytes / byteRate;
144
+ }
145
+ pos += 8 + size + (size % 2);
146
+ }
147
+ return null;
148
+ }
149
+
150
+ const MP3_BITRATES_V1 = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320];
151
+ const MP3_BITRATES_V2 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
152
+ const MP3_SAMPLE_RATES = { 3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000] };
153
+
154
+ /** The fields of an MPEG Layer III frame header, or null when the four bytes aren't one. */
155
+ function mp3Header(buf) {
156
+ if (buf.length < 4 || buf[0] !== 0xff || (buf[1] & 0xe0) !== 0xe0) return null;
157
+ const version = (buf[1] >> 3) & 3; // 3: MPEG-1, 2: MPEG-2, 0: MPEG-2.5
158
+ const layer = (buf[1] >> 1) & 3; // 1: Layer III
159
+ const bitrateIndex = buf[2] >> 4;
160
+ const rateIndex = (buf[2] >> 2) & 3;
161
+ if (version === 1 || layer !== 1 || bitrateIndex === 0 || bitrateIndex === 15 || rateIndex === 3) return null;
162
+ const mono = (buf[3] >> 6) === 3;
163
+ return {
164
+ sampleRate: MP3_SAMPLE_RATES[version][rateIndex],
165
+ kbps: (version === 3 ? MP3_BITRATES_V1 : MP3_BITRATES_V2)[bitrateIndex],
166
+ samplesPerFrame: version === 3 ? 1152 : 576,
167
+ sideInfoBytes: version === 3 ? (mono ? 17 : 32) : (mono ? 9 : 17),
168
+ hasCrc: (buf[1] & 1) === 0,
169
+ };
170
+ }
171
+
172
+ /**
173
+ * An MP3's first frame and its length. The length comes from the frame count in the first
174
+ * frame's Xing, Info or VBRI tag; a file without one has no stated length (`seconds: null`).
175
+ * Null when the file doesn't start with an MPEG Layer III frame (after an ID3v2 tag, if any).
176
+ */
177
+ function mp3Info(fd) {
178
+ let start = 0;
179
+ const tag = readAt(fd, 0, 10);
180
+ if (tag.length === 10 && tag.toString('latin1', 0, 3) === 'ID3') {
181
+ const size = ((tag[6] & 0x7f) << 21) | ((tag[7] & 0x7f) << 14) | ((tag[8] & 0x7f) << 7) | (tag[9] & 0x7f);
182
+ start = 10 + size + (tag[5] & 0x10 ? 10 : 0);
183
+ }
184
+ const frame = readAt(fd, start, 200);
185
+ const h = mp3Header(frame);
186
+ if (!h) return null;
187
+ let frames = null;
188
+ const xingAt = 4 + (h.hasCrc ? 2 : 0) + h.sideInfoBytes;
189
+ const xing = frame.toString('latin1', xingAt, xingAt + 4);
190
+ if ((xing === 'Xing' || xing === 'Info') && frame.length >= xingAt + 12 && (frame.readUInt32BE(xingAt + 4) & 1)) {
191
+ frames = frame.readUInt32BE(xingAt + 8);
192
+ } else if (frame.toString('latin1', 36, 40) === 'VBRI' && frame.length >= 54) {
193
+ frames = frame.readUInt32BE(50);
194
+ }
195
+ return { seconds: frames > 0 ? (frames * h.samplesPerFrame) / h.sampleRate : null };
196
+ }
197
+
198
+ /**
199
+ * @param {string} filePath
200
+ * @returns {{ type: 'wav'|'mp3', bytes: number, seconds: number|null } | null} `seconds` is null
201
+ * when the file doesn't state its length; null overall when it is neither WAV nor MP3
202
+ */
203
+ export function probeAudio(filePath) {
204
+ const fd = fs.openSync(filePath, 'r');
205
+ try {
206
+ const bytes = fs.fstatSync(fd).size;
207
+ const head = readAt(fd, 0, 12);
208
+ if (head.length >= 12 && head.toString('latin1', 0, 4) === 'RIFF' && head.toString('latin1', 8, 12) === 'WAVE') {
209
+ return { type: 'wav', bytes, seconds: wavSeconds(fd, bytes) };
210
+ }
211
+ const mp3 = mp3Info(fd);
212
+ return mp3 ? { type: 'mp3', bytes, seconds: mp3.seconds } : null;
213
+ } finally {
214
+ fs.closeSync(fd);
215
+ }
216
+ }
217
+
218
+ /** The ratio in `ratios` ("16:9", ...) closest to width ÷ height, compared on a log scale. */
219
+ export function nearestRatio(width, height, ratios) {
220
+ if (!(width > 0) || !(height > 0)) return null;
221
+ const target = Math.log(width / height);
222
+ let best = null;
223
+ let bestGap = Infinity;
224
+ for (const ratio of ratios) {
225
+ const [w, h] = String(ratio).split(':').map(Number);
226
+ if (!(w > 0) || !(h > 0)) continue;
227
+ const gap = Math.abs(Math.log(w / h) - target);
228
+ if (gap < bestGap - 1e-12) { best = ratio; bestGap = gap; }
229
+ }
230
+ return best;
231
+ }
@@ -27,11 +27,15 @@ function requestFor(catalog, e, cwd) {
27
27
  if (model.kind === 'video') {
28
28
  flags.res = first(e.when?.resolution) ?? (model.resolutions.includes(DEFAULTS.resolution) ? DEFAULTS.resolution : model.resolutions[0]);
29
29
  if (e.mode === 'image-to-video') flags.image = 'https://example.com/first-frame.png';
30
- } else if (e.when?.size) {
31
- flags.size = first(e.when.size);
30
+ } else {
31
+ if (e.when?.size) flags.size = first(e.when.size);
32
+ if (e.mode === 'image-edit') flags.image = ['https://example.com/input.png'];
32
33
  }
33
- if (!model.aspectRatios.includes(DEFAULTS.aspectRatio)) flags.aspect = model.aspectRatios[0];
34
- return buildCanonicalRequest(e.model, flags, catalog, { cwd, requirePrompt: false });
34
+ if (!model.aspectRatios.includes(DEFAULTS.aspectRatio) || e.mode === 'image-edit') {
35
+ flags.aspect = model.aspectRatios.includes(DEFAULTS.aspectRatio) ? DEFAULTS.aspectRatio : model.aspectRatios[0];
36
+ }
37
+ // Variant prices are checked whatever the user's setting is.
38
+ return buildCanonicalRequest(e.model, flags, catalog, { cwd, requirePrompt: false, allowVariants: true });
35
39
  }
36
40
 
37
41
  /**
@@ -100,12 +104,14 @@ async function checkOne(app, e, base, out, compare, falPrices) {
100
104
  const entry = app.catalog.models[e.model].providers[e.provider];
101
105
  if (!entry) return out('unchecked', { reason: `${e.provider} doesn't list ${e.model}` });
102
106
 
103
- if (e.provider === 'wavespeed') {
104
- const live = await ADAPTERS.wavespeed.livePrice(request, ctx, { entry });
105
- if (!live) return out('unavailable', { reason: 'WaveSpeed\'s price API didn\'t answer' });
107
+ // Both price one whole request: WaveSpeed's price API and Higgsfield's estimate endpoint.
108
+ if (e.provider === 'wavespeed' || e.provider === 'higgsfield') {
109
+ const adapter = ADAPTERS[e.provider];
110
+ const live = await adapter.livePrice(request, ctx, { entry });
111
+ if (!live) return out('unavailable', { reason: `${adapter.displayName}'s price API didn't answer` });
106
112
  if (e.pricing.type === 'perSecond') return compare(live.usd / request.duration);
107
113
  if (e.pricing.type === 'perImage') return compare(live.usd / request.count);
108
- return out('unchecked', { reason: `a ${e.pricing.type} price can't be compared with WaveSpeed's request price` });
114
+ return out('unchecked', { reason: `a ${e.pricing.type} price can't be compared with ${adapter.displayName}'s request price` });
109
115
  }
110
116
 
111
117
  if (e.provider === 'fal') {