@evolinkai/cli 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/media.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { hash } from './state.mjs';
3
3
  import { CliError, requireThat, fileError } from './errors.mjs';
4
- import { APPROVAL_TTL_MS, REFERENCE_BUDGET_FACTOR, referenceBudgetExceeded, rulesBudgetExceeded } from './platform/core/src/services/pricing-rules-estimate.js';
4
+ import { APPROVAL_TTL_MS, REFERENCE_BUDGET_FACTOR, priceRose, referenceBudgetExceeded, rulesBudgetExceeded } from './platform/core/src/services/pricing-rules-estimate.js';
5
5
  import { compareDecimal } from './platform/core/src/services/pricing-quote-client.js';
6
6
  import { DASHBOARD_URL } from './platform/core/src/services/http-policy.js';
7
7
  import { dashboardCheck } from './platform/core/src/tools/shared.js';
@@ -26,12 +26,34 @@ const RECOVERABLE = ['submitting', 'outcome_unknown', 'partial'];
26
26
  /** A quote for several inputs of one model (estimate --inputs-file), submitted in one call. */
27
27
  const isBatch = quote => Array.isArray(quote.args?.inputs);
28
28
 
29
- /** A first submission of an expired quote whose input and price were unchanged says so in its result. */
30
- function withExpiry(view, quote) {
31
- if (!quote) return view;
32
- const at = new Date(quote.expires_at).toISOString();
33
- const line = `The quote expired at ${at}, but its input and price are unchanged, so it was submitted under the original approval.`;
34
- return { ...view, approval_expired: true, quote_expired_at: at, text: view.text ? `${view.text}\n${line}` : line };
29
+ /**
30
+ * A quote holds until its expires_at, 24 hours after the estimate at most. Past it a first submission needs a new
31
+ * estimate and approval; recovery cannot replay it either, so the user checks what already went through first.
32
+ */
33
+ function expiredQuote(quote, id, resume) {
34
+ const at = new Date(quote.expires_at).toISOString(), batch = isBatch(quote), ids = quote.task_ids ?? [];
35
+ const list = 'evolink tasks list --since 2d', collect = ids.length ? `evolink tasks batch --ids ${ids.join(',')}` : undefined;
36
+ const message = !resume ? `This quote expired at ${at}. Refresh it with evolink estimate --refresh-quote ${id} and obtain the user's approval again. Nothing was submitted.`
37
+ : batch ? `This quote expired at ${at}, so its batch cannot be finished with it. Check ${collect ? `${collect} and ${list}` : list} first to see which inputs went through; then estimate only the inputs that did not and, after the user approves, submit them as a new batch. Nothing was submitted.`
38
+ : `This quote expired at ${at}, so its submission cannot be recovered with it. Check ${list} first to see whether it went through; only if it did not, estimate it again and, after the user approves, submit it as a new generation. Nothing was submitted.`;
39
+ return new CliError('quote_expired', message, { quote_id: id, client_request_id: quote.client_request_id, expired_at: at, submission_allowed: false,
40
+ ...(ids.length ? { task_ids: ids } : {}), next_step: resume ? collect ?? list : `evolink estimate --refresh-quote ${id}`, ...(resume ? dashboardCheck() : {}) });
41
+ }
42
+
43
+ /**
44
+ * Whether a fresh estimate still matches the approved quote: the same input at the approved price or lower. With the
45
+ * core's approval record that is its request hash and total, whatever else changed in the rules. Without one on both
46
+ * sides (an older service, or rules that cannot be read now), any change to the estimate needs a new approval.
47
+ */
48
+ export function approvalHolds(fresh, quote) {
49
+ const approved = quote.args?.pricing_quote, now = fresh.pricing_quote;
50
+ if (approved && now) {
51
+ return { input: approved.request_hash === now.request_hash && approved.model_id === now.model_id && approved.batch_items === now.batch_items,
52
+ rose: priceRose(approved, now) };
53
+ }
54
+ const account = quote.account_quote, current = fresh.account_quote;
55
+ if (account && current) return { input: account.request_hash === current.request_hash, rose: compareDecimal(current.quote.amount, account.quote.amount) > 0 };
56
+ return { input: true, rose: priceFingerprint(fresh) !== quote.fingerprint, byFingerprint: true };
35
57
  }
36
58
 
37
59
  /** The shared core's batch result names its own tool calls; for the CLI these lines name the CLI commands instead. */
@@ -39,7 +61,9 @@ export function cliBatchText(text, id, taskIds) {
39
61
  return (text ?? '').split('\n').map(line => {
40
62
  if (line.startsWith('Collect the results with list_tasks')) return `Collect the results with evolink tasks batch --ids ${taskIds.join(',')}; it is free and read-only.`;
41
63
  if (line.startsWith('To finish the batch, call ')) {
42
- return line.replace(/^To finish the batch, call \S+ again with client_request_id "[^"]*" and exactly the same inputs/, `To finish the batch, run evolink tasks resume --quote ${id}`);
64
+ // tasks resume replays the request ID for 23 of the gateway's 24 hours (RECOVERY_WINDOW_MS).
65
+ return line.replace(/^To finish the batch, call \S+ again with client_request_id "[^"]*" and exactly the same inputs/, `To finish the batch, run evolink tasks resume --quote ${id}`)
66
+ .replace(' within 24 hours of its first submission', ' within 23 hours of its first submission');
43
67
  }
44
68
  if (line.startsWith('The outcome of ')) {
45
69
  return line.replace(/retry later with the same client_request_id and inputs, or check list_tasks\.$/, `run evolink tasks resume --quote ${id} later, or check evolink tasks list --since 30m.`);
@@ -49,6 +73,12 @@ export function cliBatchText(text, id, taskIds) {
49
73
  }).join('\n');
50
74
  }
51
75
 
76
+ /** The shared core's refusal of a replayed approval, before anything is sent: its price rose, or it expired. */
77
+ function replayRefusal(error) {
78
+ const code = error?.details?.error?.code;
79
+ return ['price_changed', 'quote_expired'].includes(code) && error.details.charged === 'no' ? code : undefined;
80
+ }
81
+
52
82
  function interrupted(taskId) {
53
83
  return new CliError('interrupted', 'Stopped waiting locally. The EvoLink task continues.', { task_id: taskId }, 130);
54
84
  }
@@ -277,17 +307,22 @@ export class Media {
277
307
  if (resume) requireThat(this.now() < (quote.approved_at ?? quote.created_at) + RECOVERY_WINDOW_MS, 'recovery_window_passed',
278
308
  'This request ID was first submitted more than 23 hours ago. EvoLink keeps a request ID for 24 hours, so replaying it now could create and charge a new task. Check recent tasks with evolink tasks list --since 2d instead.',
279
309
  { quote_id: id, client_request_id: quote.client_request_id, submission_allowed: false, ...dashboardCheck() });
280
- // An expired quote still holds for its unchanged input and price: the fresh estimate below refuses a changed one.
281
- const expired = !resume && !quote.skip_estimate && this.now() >= quote.expires_at;
310
+ if (!quote.skip_estimate && this.now() >= quote.expires_at) throw expiredQuote(quote, id, resume);
282
311
  const { max_cost_usd, account_quote, pricing_quote, skip_estimate, ...checkArgs } = quote.args;
283
312
  // skip_estimate: the user opted out of estimates; the shared core still refuses invalid input and an unpriceable budget.
284
313
  if (!quote.skip_estimate) {
285
314
  let fresh;
286
315
  try {
287
- // Preserve the original approved request during uncertain submission recovery.
288
- fresh = resume && (account_quote || pricing_quote) ? { model: quote.args.model, type: quote.type, input_valid: true, estimate: quote.estimate, account_quote, pricing_quote }
316
+ // Recovery sends the original approved request, which the shared core checks against the current price itself.
317
+ const replay = resume && (account_quote || pricing_quote);
318
+ fresh = replay ? { model: quote.args.model, type: quote.type, input_valid: true, estimate: quote.estimate, account_quote, pricing_quote }
289
319
  : await this.client.call('estimate_cost', checkArgs);
290
- requireThat(resume && (account_quote || pricing_quote) || priceFingerprint(fresh) === quote.fingerprint, 'price_changed', 'The quote changed. Estimate again and obtain approval for the new quote.', { estimate: fresh.estimate });
320
+ if (!replay) {
321
+ const held = approvalHolds(fresh, quote);
322
+ requireThat(held.input, 'quote_input_changed', 'The input as EvoLink reads it changed since the quote. Estimate again and obtain approval for the new quote.', { estimate: fresh.estimate });
323
+ requireThat(!held.rose, 'price_changed', held.byFingerprint ? 'The quote changed. Estimate again and obtain approval for the new quote.'
324
+ : 'The price rose since the quote was approved. Estimate again and obtain approval for the new quote.', { estimate: fresh.estimate });
325
+ }
291
326
  checkEstimate(fresh, max_cost_usd);
292
327
  } catch (error) { throw quoteError(error, max_cost_usd); }
293
328
  if (!resume && fresh.pricing_quote) {
@@ -311,7 +346,7 @@ export class Media {
311
346
  await this.state.write('quotes', id, quote);
312
347
  const { pricing_source, ...generationArgs } = quote.args;
313
348
  const request = { ...generationArgs, client_request_id: quote.client_request_id };
314
- if (batch) return this.submitBatch(kind, id, quote, request, { resume, previous, expired });
349
+ if (batch) return this.submitBatch(kind, id, quote, request, { resume, previous });
315
350
  let result;
316
351
  try {
317
352
  result = await this.client.call(`generate_${kind}`, request);
@@ -331,20 +366,25 @@ export class Media {
331
366
  }
332
367
  quote.state = !resume && e.details?.charged === 'no' && ['not_submitted', 'rejected'].includes(e.details?.submission_state) ? 'refused' : 'outcome_unknown';
333
368
  await this.state.write('quotes', id, quote);
369
+ // The shared core refused the replay before sending it: the approval no longer holds (price or age).
370
+ const approval = resume && replayRefusal(e);
371
+ if (approval) throw new CliError(approval, `${approval === 'price_changed' ? 'The price rose since the quote was approved' : 'The quote expired'}, so the replay was not sent, and the original submission remains unverified. Check evolink tasks list --since 2d first to see whether it went through; only if it did not, estimate it again and, after the user approves, submit it as a new generation.`,
372
+ { ...(e.details || {}), charged: 'unknown', submission_state: 'outcome_unknown', quote_id: id, client_request_id: quote.client_request_id, submission_allowed: false,
373
+ next_step: 'evolink tasks list --since 2d', ...dashboardCheck() }, e.exitCode);
334
374
  throw new CliError(resume ? 'outcome_unknown' : e.code || 'outcome_unknown', resume ? 'The original submission remains unverified. The replay could not proceed; check recent tasks with the original request ID before preparing any new generation.' : e.message, { ...(e.details || {}), ...(quote.state === 'outcome_unknown' ? { charged: 'unknown', submission_state: 'outcome_unknown' } : {}), quote_id: id, client_request_id: quote.client_request_id,
335
375
  recovery: `evolink tasks resume --quote ${id}` }, e.exitCode);
336
376
  }
337
377
  quote.state = 'submitted';
338
378
  quote.task_id = result.task_id;
339
379
  await this.state.write('quotes', id, quote);
340
- return withExpiry({ ...result, quote_id: id, client_request_id: quote.client_request_id }, expired && quote);
380
+ return { ...result, quote_id: id, client_request_id: quote.client_request_id };
341
381
  });
342
382
  }
343
383
  /**
344
384
  * Submits a batch quote's inputs in one shared-core call and records each input's outcome. The same request ID and
345
385
  * inputs (tasks resume) later return accepted inputs without a new charge and submit only those still to finish.
346
386
  */
347
- async submitBatch(kind, id, quote, request, { resume, previous, expired }) {
387
+ async submitBatch(kind, id, quote, request, { resume, previous }) {
348
388
  let result, failure;
349
389
  try { result = await this.client.call(`generate_${kind}`, request); } catch (error) { failure = error; }
350
390
  const outcome = result ?? failure?.details ?? {};
@@ -365,10 +405,14 @@ export class Media {
365
405
  const view = { ...outcome, quote_id: id, client_request_id: quote.client_request_id, task_ids: taskIds, text: cliBatchText(outcome.text, id, taskIds),
366
406
  ...(taskIds.length ? { collect: `evolink tasks batch --ids ${taskIds.join(',')}` } : {}),
367
407
  ...(RECOVERABLE.includes(quote.state) ? { recovery: `evolink tasks resume --quote ${id}` } : {}) };
368
- if (result) return withExpiry(view, expired && quote);
408
+ if (result) return view;
369
409
  if (items) throw new CliError(failure.code || 'batch_not_submitted', failure.message, view, failure.exitCode);
370
- throw new CliError(resume && !refusedBefore ? 'outcome_unknown' : failure.code || 'outcome_unknown', resume && !refusedBefore
371
- ? 'The batch submission remains unverified. The replay could not proceed; check recent tasks with the original request ID before preparing any new generation.' : failure.message, {
410
+ // The shared core refused the replay before sending anything because the approval no longer holds (price or age).
411
+ const approval = resume && refusedBefore && replayRefusal(failure);
412
+ const check = `${taskIds.length ? `evolink tasks batch --ids ${taskIds.join(',')} and ` : ''}evolink tasks list --since 2d`;
413
+ throw new CliError(approval || (resume && !refusedBefore ? 'outcome_unknown' : failure.code || 'outcome_unknown'), approval
414
+ ? `${approval === 'price_changed' ? 'The total price rose since the quote was approved' : 'The quote expired'}, so nothing was sent. Check ${check} first to see which inputs went through; then estimate only the inputs that did not and, after the user approves, submit them as a new batch.`
415
+ : resume && !refusedBefore ? 'The batch submission remains unverified. The replay could not proceed; check recent tasks with the original request ID before preparing any new generation.' : failure.message, {
372
416
  ...view, ...(quote.state === 'outcome_unknown' ? { charged: 'unknown', submission_state: 'outcome_unknown' } : {}),
373
417
  ...(refusedBefore && quote.state === 'partial' ? { items: quote.items, next_step: 'This call submitted nothing. Accepted inputs keep their tasks (task_ids). Resolve the error; then finish the rest with tasks resume, or estimate them again as a new batch if their price or input changed.' } : {}),
374
418
  }, failure.exitCode);
@@ -3,7 +3,7 @@
3
3
  import { ApiHttpError, submitTask } from './api-client.js';
4
4
  import { remainingMs } from './http-policy.js';
5
5
  import { QuoteError, quoteRequestHash } from './pricing-quote-client.js';
6
- import { APPROVAL_TTL_MS, MAX_BATCH_ITEMS, amountsForUC } from './pricing-rules-estimate.js';
6
+ import { APPROVAL_TTL_MS, MAX_BATCH_ITEMS, amountsForUC, approvalExpired, priceRose } from './pricing-rules-estimate.js';
7
7
  export { MAX_BATCH_ITEMS };
8
8
  /** Submissions of one batch in flight at once. */
9
9
  export const BATCH_SUBMIT_CONCURRENCY = 10;
@@ -53,21 +53,21 @@ export function batchTotal(model, items) {
53
53
  }
54
54
  function fail(code, message) { throw new QuoteError(code, message); }
55
55
  /**
56
- * A batch approval holds for the same inputs, in the same order, at the same total; past its expires_at it still holds
57
- * when neither changed. An approval of one input never approves a batch.
56
+ * A batch approval holds for the same inputs, in the same order, until its expires_at, at the approved total or lower:
57
+ * the total counts, not any one input's price. An approval of one input never approves a batch.
58
58
  */
59
59
  export function checkBatchApproval(approval, fresh) {
60
- const expired = Date.parse(approval.expires_at) <= Date.now();
61
60
  if (approval.batch_items === undefined) {
62
61
  fail('quote_input_changed', 'This pricing_quote approves one input; estimate these inputs together (inputs) and obtain approval.');
63
62
  }
64
63
  if (approval.batch_items !== fresh.batch_items || approval.request_hash !== fresh.request_hash || approval.model_id !== fresh.model_id) {
65
64
  fail('quote_input_changed', 'The inputs differ from the approved batch estimate (the same inputs, in the same order).');
66
65
  }
67
- if (approval.fingerprint !== fresh.fingerprint || approval.total_uc !== fresh.total_uc) {
68
- fail('price_changed', 'The pricing rules or estimated price changed. Estimate again and obtain approval.');
66
+ if (approvalExpired(approval)) {
67
+ fail('quote_expired', `The approved batch estimate expired at ${approval.expires_at}. Estimate these inputs again and obtain approval. If this call finishes a batch submitted earlier, check list_tasks first: within 24 hours of its first submission, finish it with the new pricing_quote, the same client_request_id and the same inputs; past that, submit only the inputs that did not go through, as a new batch with a new client_request_id.`);
69
68
  }
70
- return { expired };
69
+ if (priceRose(approval, fresh))
70
+ fail('price_changed', 'The estimated total of the batch rose after it was approved. Estimate again and obtain approval.');
71
71
  }
72
72
  /**
73
73
  * The gateway answered every attempt without running it: a rate limit (it releases the key, so the same key can be
@@ -29,8 +29,10 @@ const family25 = (model) => model.trim().toLowerCase().startsWith('gpt-image-2.5
29
29
  const family1 = (model) => model === 'gpt-image-1.5' || model === 'gpt-image-1';
30
30
  /** Models the gateway reserves and bills by token counts. */
31
31
  export const isTokenImageModel = (model) => model === 'gpt-image-2' || family1(model) || family25(model);
32
- function invalid(param, message) { throw new QuoteError('invalid_quote_parameter', message, param); }
33
- const text = (param, value) => value === undefined ? '' : typeof value === 'string' ? value : invalid(param, `${param} must be a string.`);
32
+ function invalid(param, message, check = 'range') {
33
+ throw new QuoteError('invalid_quote_parameter', message, param, undefined, check, 'gpt_image');
34
+ }
35
+ const text = (param, value) => value === undefined ? '' : typeof value === 'string' ? value : invalid(param, `${param} must be a string.`, 'type');
34
36
  const nestedParams = (input) => input.model_params && typeof input.model_params === 'object' && !Array.isArray(input.model_params)
35
37
  ? input.model_params : {};
36
38
  const lower = (value) => typeof value === 'string' ? value.trim().toLowerCase() : '';
@@ -81,8 +83,8 @@ function outputSize(size, resolution) {
81
83
  return pixels;
82
84
  }
83
85
  const ratio = ['', 'auto'].includes(trimmed.toLowerCase()) ? '1:1' : trimmed.toLowerCase();
84
- const aspect = RATIOS[ratio] ?? invalid('size', `size ${size} is not a supported ratio or WxH pixel size.`);
85
- const tier = resolution.trim().toUpperCase() || '1K', budget = BUDGETS[tier] ?? invalid('resolution', `resolution ${resolution} must be 1K, 2K or 4K.`);
86
+ const aspect = RATIOS[ratio] ?? invalid('size', `size ${size} is not a supported ratio or WxH pixel size.`, 'enum');
87
+ const tier = resolution.trim().toUpperCase() || '1K', budget = BUDGETS[tier] ?? invalid('resolution', `resolution ${resolution} must be 1K, 2K or 4K.`, 'enum');
86
88
  const [width, height] = fitBudget(roundToStep(Math.trunc(Math.sqrt(budget * aspect[0] / aspect[1]))), roundToStep(Math.trunc(Math.sqrt(budget * aspect[1] / aspect[0]))));
87
89
  checkPixels(width, height);
88
90
  return [width, height];
@@ -96,7 +98,7 @@ function family1Size(size) {
96
98
  return [1024, 1536];
97
99
  if (['1536x1024', '1536×1024', '3:2'].includes(value))
98
100
  return [1536, 1024];
99
- return invalid('size', `size ${size} must be 1024x1024, 1024x1536, 1536x1024, 1:1, 2:3 or 3:2.`);
101
+ return invalid('size', `size ${size} must be 1024x1024, 1024x1536, 1536x1024, 1:1, 2:3 or 3:2.`, 'enum');
100
102
  }
101
103
  function scaledTiles(base, longer, shorter) {
102
104
  // The calculator's own order of division: base * shorter / longer differs in the last bit for a few sizes.
@@ -152,7 +154,7 @@ function gifSheet(model, size, frames, quality) {
152
154
  if (!['', 'auto'].includes(trimmed.toLowerCase())) {
153
155
  const pixels = trimmed.includes(':') ? undefined : pixelSize(trimmed);
154
156
  if (!pixels)
155
- invalid('size', `With output_format gif, size is auto or the WIDTHxHEIGHT of each frame, not ${size}.`);
157
+ invalid('size', `With output_format gif, size is auto or the WIDTHxHEIGHT of each frame, not ${size}.`, 'shape');
156
158
  [frameWidth, frameHeight] = pixels;
157
159
  if (frameWidth % STEP || frameHeight % STEP || frameWidth > MAX_EDGE || frameHeight > MAX_EDGE) {
158
160
  invalid('size', `GIF frame edges must be multiples of ${STEP} and at most ${MAX_EDGE}px, got ${frameWidth}x${frameHeight}.`);
@@ -205,30 +207,30 @@ function gifOutput(model, input, images) {
205
207
  const params = nestedParams(input);
206
208
  const format = lower(input.output_format) || lower(params.output_format), background = lower(input.background) || lower(params.background);
207
209
  if (background === 'transparent' && (format === 'jpeg' || format === 'jpg'))
208
- invalid('background', `background transparent needs png or webp output; ${format} cannot keep transparency.`);
210
+ invalid('background', `background transparent needs png or webp output; ${format} cannot keep transparency.`, 'conflict');
209
211
  if (!family26(model))
210
212
  return false;
211
213
  // SVG output is paused on the gateway, and its author model would be priced on top, so it is never quoted.
212
214
  if (format === 'svg')
213
- invalid('output_format', `output_format svg is not available on ${model}; use png, jpeg, webp or gif.`);
215
+ invalid('output_format', `output_format svg is not available on ${model}; use png, jpeg, webp or gif.`, 'enum');
214
216
  if (['svg_model', 'svg_reasoning_effort'].some(key => Object.hasOwn(params, key)))
215
- invalid('model_params', 'model_params.svg_model and svg_reasoning_effort need output_format svg, which is not available.');
217
+ invalid('model_params', 'model_params.svg_model and svg_reasoning_effort need output_format svg, which is not available.', 'conflict');
216
218
  if (format !== 'gif' && ['frame_count', 'frame_duration_ms'].some(key => Object.hasOwn(params, key)))
217
- invalid('model_params', 'model_params.frame_count and frame_duration_ms need output_format gif.');
219
+ invalid('model_params', 'model_params.frame_count and frame_duration_ms need output_format gif.', 'conflict');
218
220
  const markup = [input.markup_url, params.markup_url].map(value => typeof value === 'string' ? value.trim() : '').find(Boolean);
219
221
  if (markup) {
220
222
  if (!(referenceCount(input.image_url) + referenceCount(input.image_urls) + referenceCount(params.image_url) + referenceCount(params.image_urls))) {
221
- invalid('markup_url', 'markup_url marks up the first reference image, so it needs image_urls.');
223
+ invalid('markup_url', 'markup_url marks up the first reference image, so it needs image_urls.', 'required');
222
224
  }
223
225
  if ([input.mask_url, params.mask_url].some(value => typeof value === 'string' && value.trim() !== ''))
224
- invalid('markup_url', 'markup_url cannot be combined with mask_url.');
226
+ invalid('markup_url', 'markup_url cannot be combined with mask_url.', 'conflict');
225
227
  }
226
228
  if (format !== 'gif')
227
229
  return false;
228
230
  if (images > 1)
229
- invalid('n', `output_format gif on ${model} needs n=1.`);
231
+ invalid('n', `output_format gif on ${model} needs n=1.`, 'conflict');
230
232
  if (background === 'transparent')
231
- invalid('background', 'background transparent needs png or webp output, not gif.');
233
+ invalid('background', 'background transparent needs png or webp output, not gif.', 'conflict');
232
234
  return true;
233
235
  }
234
236
  /**
@@ -238,11 +240,11 @@ function gifOutput(model, input, images) {
238
240
  * countPromptTokens replaces the approximation when the exact count is known.
239
241
  */
240
242
  export function tokenImageReservation(model, input, countPromptTokens = approximatePromptTokens) {
241
- const n = input.n === undefined ? 1 : Number.isInteger(input.n) ? Math.max(1, input.n) : invalid('n', 'n must be a whole number.');
243
+ const n = input.n === undefined ? 1 : Number.isInteger(input.n) ? Math.max(1, input.n) : invalid('n', 'n must be a whole number.', 'type');
242
244
  const given = text('quality', input.quality);
243
245
  const quality = given === '' ? family1(model) ? 'high' : 'medium' : given.trim().toLowerCase();
244
246
  if (!Object.hasOwn(family1(model) ? TILES_1 : family25(model) ? BASE_25 : BASE_2, quality))
245
- invalid('quality', `quality ${given} is not supported by ${model}.`);
247
+ invalid('quality', `quality ${given} is not supported by ${model}.`, 'enum');
246
248
  const size = text('size', input.size), resolution = text('resolution', input.resolution);
247
249
  const auto = !family1(model) && ['', 'auto'].includes(size.trim().toLowerCase());
248
250
  let output, outputTokens;
@@ -50,7 +50,9 @@ export function approximateOmniPromptTokens(prompt) {
50
50
  }
51
51
  return Math.ceil(hundredths / 100);
52
52
  }
53
- function invalid(param, message) { throw new QuoteError('invalid_quote_parameter', message, param); }
53
+ function invalid(param, message, check = 'count') {
54
+ throw new QuoteError('invalid_quote_parameter', message, param, undefined, check, 'omni');
55
+ }
54
56
  const textOf = (value) => typeof value === 'string' ? value : '';
55
57
  /** parseFlexibleStringArray: one string or a list; empty and non-string entries do not count. */
56
58
  const flexible = (value) => typeof value === 'string' ? value === '' ? [] : [value]
@@ -86,12 +88,12 @@ const upscaleMax = (target) => Math.max(0, ...Object.entries(UPSCALE).filter(([p
86
88
  const upscaleSource = (target) => TIERS.find(tier => UPSCALE[`${tier}>${target}`] === upscaleMax(target));
87
89
  function checkLength(mediaSeconds, max, what, model) {
88
90
  if (mediaSeconds > max)
89
- invalid('media_seconds', `${what} must be ${max} seconds or shorter for ${model}; media_seconds is ${mediaSeconds}.`);
91
+ invalid('media_seconds', `${what} must be ${max} seconds or shorter for ${model}; media_seconds is ${mediaSeconds}.`, 'range');
90
92
  }
91
93
  function requirePrompt(input, model) {
92
94
  const prompt = textOf(input.prompt);
93
95
  if (prompt.trim() === '')
94
- invalid('prompt', `prompt is required for ${model}.`);
96
+ invalid('prompt', `prompt is required for ${model}.`, 'required');
95
97
  return prompt;
96
98
  }
97
99
  /**
@@ -100,7 +102,7 @@ function requirePrompt(input, model) {
100
102
  * countPromptTokens replaces the approximate prompt count when the gateway's exact count is known.
101
103
  */
102
104
  export function omniReservation(model, input, mediaSeconds, options = {}) {
103
- const id = model.trim().toLowerCase(), found = omniModel(id) ?? invalid('model', `${model} is not a Gemini Omni Flash model.`);
105
+ const id = model.trim().toLowerCase(), found = omniModel(id) ?? invalid('model', `${model} is not a Gemini Omni Flash model.`, 'enum');
104
106
  const count = options.countPromptTokens ?? approximateOmniPromptTokens, route = found.route, g = found.generation;
105
107
  const tokensOf = (prompt) => prompt === '' ? 0 : count(prompt);
106
108
  if (!g)
@@ -110,9 +112,9 @@ export function omniReservation(model, input, mediaSeconds, options = {}) {
110
112
  const start = textOf(input.image_start).trim(), end = textOf(input.image_end).trim();
111
113
  if (start || end) {
112
114
  if (route !== 'image')
113
- invalid('image_start', `image_start and image_end are only for gemini-omni-${g.label}-flash-image-to-video.`);
115
+ invalid('image_start', `image_start and image_end are only for gemini-omni-${g.label}-flash-image-to-video.`, 'conflict');
114
116
  if (end && !start)
115
- invalid('image_end', 'image_end needs image_start: a last frame only is not supported.');
117
+ invalid('image_end', 'image_end needs image_start: a last frame only is not supported.', 'required');
116
118
  }
117
119
  const duration = durationOf(input.duration);
118
120
  if (route === 'text' && (images.length || videos.length))
@@ -123,7 +125,7 @@ export function omniReservation(model, input, mediaSeconds, options = {}) {
123
125
  if (videos.length)
124
126
  invalid('video_urls', `${id} takes no video input.`);
125
127
  if (images.length === 2 && duration > g.maxFrameOutput)
126
- invalid('duration', `first and last frame generation supports up to ${g.maxFrameOutput} seconds on ${id}, got ${duration}.`);
128
+ invalid('duration', `first and last frame generation supports up to ${g.maxFrameOutput} seconds on ${id}, got ${duration}.`, 'range');
127
129
  }
128
130
  if (route === 'reference') {
129
131
  if (images.length < 1)
@@ -138,16 +140,16 @@ export function omniReservation(model, input, mediaSeconds, options = {}) {
138
140
  if (videos.length !== 1)
139
141
  invalid('video_urls', `${id} takes exactly 1 video, got ${videos.length}.`);
140
142
  if (!isHTTP(videos[0]))
141
- invalid('video_urls', `${id} takes the video as an http(s) URL.`);
143
+ invalid('video_urls', `${id} takes the video as an http(s) URL.`, 'shape');
142
144
  }
143
145
  // An upscale takes no prompt; the gateway drops one.
144
146
  const prompt = route === 'upscale' ? '' : requirePrompt(input, id);
145
147
  const quality = textOf(input.quality).trim().toLowerCase();
146
148
  const follows = (route === 'edit' || route === 'extend') && (quality === '' || quality === 'auto');
147
149
  if (quality !== '' && !follows && !TIERS.includes(quality))
148
- invalid('quality', `quality ${input.quality} is not supported by ${id}.`);
150
+ invalid('quality', `quality ${input.quality} is not supported by ${id}.`, 'enum');
149
151
  if (route === 'upscale' && (quality === '' || quality === '360p'))
150
- invalid('quality', `quality on ${id} is the target resolution: 720p, 1080p or 4k.`);
152
+ invalid('quality', `quality on ${id} is the target resolution: 720p, 1080p or 4k.`, 'enum');
151
153
  const tier = (quality === '' || quality === 'auto' ? DEFAULT_TIER : quality);
152
154
  // Input and reference videos: the gateway reads their length at submission and refuses one that is too long.
153
155
  let input_videos;
@@ -169,7 +171,7 @@ export function omniReservation(model, input, mediaSeconds, options = {}) {
169
171
  const target = quality, source = options.inputTier ?? upscaleSource(target);
170
172
  const rate = UPSCALE[`${source}>${target}`];
171
173
  if (rate === undefined)
172
- invalid('quality', `${id} cannot upscale ${source} to ${target}; supported: 360p to 720p or 1080p, 720p to 1080p or 4k, 1080p to 4k.`);
174
+ invalid('quality', `${id} cannot upscale ${source} to ${target}; supported: 360p to 720p or 1080p, 720p to 1080p or 4k, 1080p to 4k.`, 'conflict');
173
175
  return { ...base, route, prompt_tokens: 0, output: { resolution: target, seconds: input_videos.seconds },
174
176
  upscale: { target, source, source_assumed: options.inputTier === undefined, tokens_per_second: rate },
175
177
  tokens: { input_tokens: 0, video_output_tokens: cap(rate * input_videos.seconds), other_output_tokens: 0 } };
@@ -195,11 +197,11 @@ function reservation10(id, route, input, mediaSeconds, tokensOf) {
195
197
  const images = media10(input, 'image_urls', 'image_url', 'image'), videos = media10(input, 'video_urls', 'video_url', 'video');
196
198
  // validateGeminiOmniFlashRequest: no resolution or frame fields, an edit takes no duration, and the media each route takes.
197
199
  if (textOf(input.quality) !== '')
198
- invalid('quality', `quality is not supported by ${id}.`);
200
+ invalid('quality', `quality is not supported by ${id}.`, 'conflict');
199
201
  if (textOf(input.image_start) !== '' || textOf(input.image_end) !== '')
200
- invalid('image_start', `image_start and image_end are not supported by ${id}; use image_urls.`);
202
+ invalid('image_start', `image_start and image_end are not supported by ${id}; use image_urls.`, 'conflict');
201
203
  if (route === 'edit' && (durationOf(input.duration) !== 0 || input.duration === 'auto'))
202
- invalid('duration', `duration is not supported by ${id}.`);
204
+ invalid('duration', `duration is not supported by ${id}.`, 'conflict');
203
205
  if (route === 'text' && (images.length || videos.length))
204
206
  invalid('image_urls', `${id} takes no image or video input.`);
205
207
  if (route === 'image' && images.length !== 1)
@@ -214,7 +216,7 @@ function reservation10(id, route, input, mediaSeconds, tokensOf) {
214
216
  if (videos.length !== 1)
215
217
  invalid('video_urls', `${id} takes exactly 1 video, got ${videos.length}.`);
216
218
  if (!isHTTP(videos[0]))
217
- invalid('video_urls', `${id} takes the video as an http(s) URL.`);
219
+ invalid('video_urls', `${id} takes the video as an http(s) URL.`, 'shape');
218
220
  }
219
221
  const prompt = requirePrompt(input, id), promptTokens = tokensOf(prompt);
220
222
  let input_videos, inputTokens = promptTokens;
@@ -234,6 +236,19 @@ function reservation10(id, route, input, mediaSeconds, tokensOf) {
234
236
  ...(input_videos ? { input_videos } : {}),
235
237
  tokens: { input_tokens: inputTokens, video_output_tokens: seconds * V10.output, other_output_tokens: OMNI_OTHER_OUTPUT_TOKENS } };
236
238
  }
239
+ /**
240
+ * The input resolutions a reference price is also given at, lowest first, when the gateway reads the input's own at
241
+ * submission: every tier for an input or reference video, or for an upscale each source it accepts for the target.
242
+ */
243
+ export function omniInputTiers(reservation) {
244
+ if (reservation.upscale) {
245
+ const target = reservation.upscale.target;
246
+ return reservation.upscale.source_assumed ? TIERS.filter(tier => UPSCALE[`${tier}>${target}`] !== undefined) : [];
247
+ }
248
+ return reservation.input_videos?.resolution_assumed ? [...TIERS] : [];
249
+ }
250
+ /** The resolution the reference price itself counts the input at: the highest, or the upscale source that costs most. */
251
+ export const omniQuotedTier = (reservation) => reservation.upscale?.source ?? reservation.input_videos?.resolution;
237
252
  /** The lower-resolution input a reference price can also be given for: 720p, or for an upscale the cheaper source. */
238
253
  export function omniLowerInputTier(reservation) {
239
254
  if (reservation.upscale) {