@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.
@@ -31,12 +31,60 @@ export const ApprovedAccountQuote = z.object({ quote: AccountQuoteSchema,
31
31
  export class QuoteError extends Error {
32
32
  code;
33
33
  param;
34
- constructor(code, message, param) {
34
+ origin;
35
+ check;
36
+ validator;
37
+ itemIndex;
38
+ constructor(code, message, param, origin, check, validator, itemIndex) {
35
39
  super(message);
36
40
  this.code = code;
37
41
  this.param = param;
42
+ this.origin = origin;
43
+ this.check = check;
44
+ this.validator = validator;
45
+ this.itemIndex = itemIndex;
38
46
  }
39
47
  }
48
+ /** The structured error both quoting tools return: the code, and for a rejected value its parameter, origin and check. */
49
+ export function quoteErrorFields(error) {
50
+ return { code: error.code, ...(error.param ? { param: error.param } : {}),
51
+ ...(error.origin ? { origin: error.origin } : {}), ...(error.check ? { check: error.check } : {}),
52
+ ...(error.validator ? { validator: error.validator } : {}),
53
+ ...(error.itemIndex !== undefined ? { item_index: error.itemIndex } : {}) };
54
+ }
55
+ /** Keep a batch item's diagnostics while adding its location; input values never become diagnostic fields. */
56
+ export function quoteErrorAt(error, index) {
57
+ return new QuoteError(error.code, `inputs[${index}]: ${error.message}`, error.param, error.origin, error.check, error.validator, index);
58
+ }
59
+ /** Attribute the token calculators' reviewed checks without guessing from an English error message. */
60
+ export function reservationErrorOrigin(error, entry, input) {
61
+ if (error.code !== 'invalid_quote_parameter' || error.origin || !error.check)
62
+ return error;
63
+ const parts = (error.param ?? '').split('.');
64
+ let value = input, spec;
65
+ for (let i = 0; i < parts.length; i++) {
66
+ value = value && typeof value === 'object' && !Array.isArray(value) ? value[parts[i]] : undefined;
67
+ spec = i === 0 ? entry.spec?.params[parts[i]] : spec?.properties?.[parts[i]];
68
+ }
69
+ // The gateway also reads some image settings from model_params.
70
+ if (value === undefined && parts.length === 1 && input.model_params && typeof input.model_params === 'object' && !Array.isArray(input.model_params)) {
71
+ value = input.model_params[parts[0]];
72
+ spec = entry.spec?.params.model_params?.properties?.[parts[0]] ?? spec;
73
+ }
74
+ if (value === undefined && error.param === 'video_urls')
75
+ value = input.video_url ?? input.video;
76
+ if (value === undefined && error.param === 'image_urls')
77
+ value = input.image_url ?? input.image_start ?? input.image_end ?? input.image;
78
+ const documented = error.check === 'enum' && spec?.enum?.some(option => option === value) === true;
79
+ const origin = error.param === 'model' ? 'service' : documented ? 'documented'
80
+ : value === undefined && ['enum', 'type', 'shape'].includes(error.check) ? 'service' : 'caller';
81
+ return new QuoteError(error.code, error.message, error.param, origin, error.check, error.validator, error.itemIndex);
82
+ }
83
+ /** The model's documentation pins this setting to listed values or bounds, which input validation enforces. */
84
+ function documentedLimits(spec) {
85
+ return !!spec && ((spec.enum?.length ?? 0) > 0 || spec.minimum !== undefined || spec.maximum !== undefined
86
+ || spec.exclusiveMinimum !== undefined || spec.exclusiveMaximum !== undefined);
87
+ }
40
88
  function canonical(value) {
41
89
  if (Array.isArray(value))
42
90
  return `[${value.map(canonical).join(',')}]`;
@@ -49,7 +97,9 @@ export function quoteRequestHash(model, input, mediaSeconds, pricingParameters =
49
97
  return createHash('sha256').update(canonical({ model: model.toLowerCase(), input, media_seconds: mediaSeconds,
50
98
  pricing_parameters: pricingParameters })).digest('hex');
51
99
  }
52
- function fail(code, message, param) { throw new QuoteError(code, message, param); }
100
+ function fail(code, message, param, origin, check) {
101
+ throw new QuoteError(code, message, param, origin, check);
102
+ }
53
103
  const aliases = { duration_seconds: ['duration'], output_seconds: ['duration'], image_count: ['n', 'count'],
54
104
  video_count: ['n', 'count'], resolution: ['quality'], quality: ['resolution'] };
55
105
  const measured = /(?:tokens|input_seconds|output_seconds|source_output_seconds|first_input_video_seconds|search_count)$/;
@@ -86,29 +136,42 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
86
136
  fail('conflicting_quote_parameter', `Conflicting generation values for ${name}.`, name);
87
137
  }
88
138
  let value = supplied[0];
139
+ // Whose value this is, so a rejection below can say so (never the value itself): see QuoteValueOrigin.
140
+ let origin;
141
+ if (value !== undefined) {
142
+ const key = generationNames.find(k => given(k) !== undefined);
143
+ origin = asRule(given(key)) !== given(key) ? 'service' : documentedLimits(documented(key)) ? 'documented' : 'caller';
144
+ }
145
+ const fill = (candidate, from) => {
146
+ if (value === undefined && candidate !== undefined)
147
+ [value, origin] = [candidate, from];
148
+ };
89
149
  // A promptless Midjourney V7 edit runs and bills as fast whatever speed was requested.
90
150
  if (value === undefined && name === 'prompt_present')
91
- value = typeof input.prompt === 'string' && effectiveMjV7EditPrompt(input.prompt) !== '';
151
+ fill(typeof input.prompt === 'string' && effectiveMjV7EditPrompt(input.prompt) !== '', 'service');
92
152
  // Some rule parameters come from differently named request fields, as the gateway pre-deducts them.
93
153
  if (value === undefined)
94
- value = derivedQuoteParameter(model, name, input, nestedInput);
154
+ fill(derivedQuoteParameter(model, name, input, nestedInput), 'service');
95
155
  if (value === undefined && name === 'input_images') {
96
156
  if (Array.isArray(input.image_urls))
97
- value = input.image_urls.length;
157
+ fill(input.image_urls.length, 'caller');
98
158
  else if (typeof input.image_url === 'string')
99
- value = 1;
159
+ fill(1, 'caller');
100
160
  else
101
- value = 0;
161
+ fill(0, 'caller');
102
162
  }
103
163
  // Expected usage cannot change settings or references the model will actually receive.
104
164
  if (value === undefined && pricingParameters[name] !== undefined && !usage(name)
105
165
  && generationNames.some(key => documented(key) !== undefined)) {
106
- value = asRule(generationNames.map(key => documented(key)?.default).find(v => v !== undefined) ?? p.default);
166
+ fill(asRule(generationNames.map(key => documented(key)?.default).find(v => v !== undefined) ?? p.default), 'service');
107
167
  }
108
168
  if (pricingParameters[name] !== undefined) {
109
169
  if (value !== undefined && String(value) !== String(pricingParameters[name])) {
110
170
  fail('conflicting_quote_parameter', `Pricing parameter ${name} differs from the generation input.`, name);
111
171
  }
172
+ // Repeating a generation value or default keeps where it came from; only a value nothing else gave is the caller's.
173
+ if (value === undefined)
174
+ origin = 'caller';
112
175
  value = pricingParameters[name];
113
176
  }
114
177
  if (name === 'input_seconds' && value !== undefined && mediaSeconds !== undefined
@@ -117,11 +180,11 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
117
180
  }
118
181
  // media_seconds describes measured input length, never an unknown generated output.
119
182
  if (value === undefined && name === 'input_seconds' && mediaSeconds !== undefined)
120
- value = mediaSeconds;
183
+ fill(mediaSeconds, 'caller');
121
184
  if (value === undefined && name === 'first_input_video_seconds' && mediaSeconds !== undefined)
122
- value = mediaSeconds;
185
+ fill(mediaSeconds, 'caller');
123
186
  if (value === undefined && ['output_seconds', 'duration_seconds'].includes(name) && mediaSeconds !== undefined && entry.spec && !entry.spec.params.duration && !declared.has('duration') && entry.spec?.constraints?.outputDuration !== 'unknown')
124
- value = mediaSeconds;
187
+ fill(mediaSeconds, 'caller');
125
188
  if (value === undefined && name === 'duration_seconds' && declared.has('duration') && String(input.duration ?? pricingParameters.duration ?? entry.spec?.params.duration?.default ?? declared.get('duration')?.default) === '-1') {
126
189
  if (allowMissingUsage)
127
190
  continue;
@@ -134,7 +197,7 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
134
197
  }
135
198
  if (value === undefined && !usage(name)) {
136
199
  const defaults = generationNames.map(key => documented(key)?.default).filter(v => v !== undefined).map(asRule);
137
- value = defaults[0];
200
+ fill(defaults[0], 'service');
138
201
  }
139
202
  const references = Array.isArray(input.video_urls) && input.video_urls.length > 0
140
203
  || typeof input.video_url === 'string' && input.video_url.trim().length > 0
@@ -142,26 +205,27 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
142
205
  // Zero is an illustration for enabled search, never measured usage or an execution limit.
143
206
  // The rules evaluator separately records the missing actual/expected search count.
144
207
  if (value === undefined && search?.enabled && allowMissingUsage)
145
- value = '0';
208
+ fill('0', 'service');
146
209
  if (value === undefined && usage(name) && (p.required || references || /tokens$/.test(name) || search?.enabled || (name === 'search_count' && input.web_search === true) || p.default === undefined)) {
147
210
  if (allowMissingUsage)
148
211
  continue;
149
212
  fail('quote_usage_required', `Provide measured or expected usage for ${name} in pricing_parameters.`, name);
150
213
  }
151
214
  if (value === undefined)
152
- value = CONSERVATIVE_QUOTE_PARAMETERS[`${model.toLowerCase()} ${name}`]?.value;
215
+ fill(CONSERVATIVE_QUOTE_PARAMETERS[`${model.toLowerCase()} ${name}`]?.value, 'service');
153
216
  if (value === undefined)
154
- value = p.default;
217
+ fill(p.default, 'service');
155
218
  if (value === undefined) {
156
219
  if (p.required)
157
220
  fail('quote_parameter_required', `Pricing parameter ${name} is required.`, name);
158
221
  continue;
159
222
  }
223
+ const reject = (problem, check) => fail('invalid_quote_parameter', `Pricing parameter ${name} ${problem}`, name, origin, check);
160
224
  if (!['string', 'number', 'boolean'].includes(typeof value) || (typeof value === 'number' && !Number.isFinite(value))) {
161
- fail('invalid_quote_parameter', `Pricing parameter ${name} must be a finite scalar.`, name);
225
+ reject('must be a finite scalar.', 'scalar');
162
226
  }
163
227
  if (typeof value === 'string' && value.length > 128)
164
- fail('invalid_quote_parameter', `Pricing parameter ${name} is too long.`, name);
228
+ reject('is too long.', 'length');
165
229
  if (p.type === 'integer' || p.type === 'decimal') {
166
230
  if (typeof value === 'number' && String(value).includes('e')) {
167
231
  const negative = value < 0, [mantissa, exponent] = String(Math.abs(value)).split('e');
@@ -169,25 +233,25 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
169
233
  value = (negative ? '-' : '') + (point <= 0 ? '0.' + '0'.repeat(-point) + digits
170
234
  : point >= digits.length ? digits + '0'.repeat(point - digits.length) : digits.slice(0, point) + '.' + digits.slice(point));
171
235
  if (String(value).length > 128)
172
- fail('invalid_quote_parameter', `Pricing parameter ${name} is too long.`, name);
236
+ reject('is too long.', 'length');
173
237
  }
174
238
  if (typeof value === 'boolean' || !/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(String(value))
175
239
  || (p.type === 'integer' && !/^-?(?:0|[1-9]\d*)$/.test(String(value)))) {
176
- fail('invalid_quote_parameter', `Pricing parameter ${name} must be ${p.type}.`, name);
240
+ reject(`must be ${p.type}.`, 'type');
177
241
  }
178
242
  if ((p.minimum !== undefined && compareDecimal(String(value), p.minimum) < 0)
179
243
  || (p.maximum !== undefined && compareDecimal(String(value), p.maximum) > 0)) {
180
- fail('invalid_quote_parameter', `Pricing parameter ${name} is outside the published range.`, name);
244
+ reject('is outside the published range.', 'range');
181
245
  }
182
246
  }
183
247
  else if (p.type === 'boolean' && typeof value !== 'boolean') {
184
- fail('invalid_quote_parameter', `Pricing parameter ${name} must be boolean.`, name);
248
+ reject('must be boolean.', 'boolean');
185
249
  }
186
250
  // Published enums may spell numbers as strings ("5") while the generation input carries a number (5);
187
251
  // lookup expressions compare by text, so the allowed-value check does the same.
188
252
  const allowed = p.values ?? p.enum;
189
253
  if (allowed && !allowed.some(candidate => String(candidate) === String(value)))
190
- fail('invalid_quote_parameter', `Pricing parameter ${name} is not an allowed value.`, name);
254
+ reject('is not an allowed value.', 'enum');
191
255
  if (search && !search.enabled
192
256
  && compareDecimal(String(value), '0') !== 0) {
193
257
  fail('conflicting_quote_parameter', `${name} must be zero when ${search.input_parameter} is not enabled.`, name);
@@ -13,9 +13,11 @@ const MAX_JSON_DEPTH = 64;
13
13
  const decimal = z.string().max(64).regex(/^(?:0|[1-9]\d*)(?:\.\d+)?$/);
14
14
  const signedDecimal = z.string().max(64).regex(/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/);
15
15
  const identifier = (max) => z.string().trim().max(max).regex(/^[a-z0-9][a-z0-9._:-]*$/);
16
+ const modelName = z.string().trim().toLowerCase().pipe(identifier(100));
17
+ const aliasName = z.string().trim().max(100).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/);
16
18
  const optionalFilter = (schema) => z.preprocess(value => typeof value === 'string' && value.trim() === '' ? undefined : value, schema.optional());
17
19
  export const PricingRulesQuery = z.object({
18
- model: optionalFilter(identifier(100)), product_id: optionalFilter(identifier(100)),
20
+ model: optionalFilter(modelName).describe('Model ID or a published alias; model names are case-insensitive.'), product_id: optionalFilter(identifier(100)),
19
21
  operation: optionalFilter(z.string().trim().toLowerCase().pipe(identifier(50))),
20
22
  modality: optionalFilter(z.string().trim().toLowerCase().pipe(z.enum(['text', 'image', 'video', 'audio']))),
21
23
  lifecycle: optionalFilter(z.string().trim().toLowerCase().pipe(z.enum(['active', 'preview', 'deprecated']))),
@@ -70,6 +72,7 @@ const Parameter = z.object({ name: z.string().min(1).max(100), type: z.string().
70
72
  });
71
73
  const Model = z.object({
72
74
  model_id: identifier(100), product_id: identifier(100), operation: identifier(50),
75
+ aliases: z.array(aliasName).max(100).optional(),
73
76
  modality: z.enum(['text', 'image', 'video', 'audio']), lifecycle: z.enum(['active', 'preview', 'deprecated']),
74
77
  pricing_status: z.enum(['available', 'unavailable']), settlement_basis: z.string().min(1).max(100),
75
78
  policy_version: z.number().int().nonnegative(), policy_checksum: z.string().regex(/^[a-f0-9]{64}$/),
@@ -213,13 +216,22 @@ export function cachedPricingRules(input) {
213
216
  return old && old.expires > Date.now() ? old.body : undefined;
214
217
  }
215
218
  const stillFresh = (entry) => Date.parse(entry.body.meta.fresh_until) > Date.now();
219
+ /** Only identities explicitly published by this rule match; never infer names from a prefix or resemblance. */
220
+ function matchesModel(rule, model) {
221
+ const name = model.trim().toLowerCase();
222
+ return rule.model_id === name || rule.aliases?.some(alias => alias.toLowerCase() === name) === true;
223
+ }
216
224
  /** One model's full rules from the cache: its own entry, else its row in the cached full list. */
217
225
  function cachedModel(model, usable) {
218
226
  const own = cache.get(rulesURL(PricingRulesQuery.parse({ model, view: 'full' })).href);
219
227
  if (own && usable(own))
220
228
  return own;
221
229
  const list = cache.get(rulesURL(PricingRulesQuery.parse({ view: 'full' })).href);
222
- const rule = list && usable(list) && 'models' in list.body ? list.body.models.find(item => item.model_id === model) : undefined;
230
+ const rows = list && usable(list) && 'models' in list.body ? list.body.models : [];
231
+ const exact = rows.find(item => item.model_id === model.toLowerCase());
232
+ const aliases = exact ? [] : rows.filter(item => matchesModel(item, model));
233
+ // An ambiguous alias in a list is resolved by the single-model endpoint, not by list order.
234
+ const rule = exact ?? (aliases.length === 1 ? aliases[0] : undefined);
223
235
  return list && rule ? { body: { meta: list.body.meta, model: rule }, fetchedAt: list.fetchedAt } : undefined;
224
236
  }
225
237
  /** One model's full rules read at most maxAgeMs ago, even past their fresh_until: an estimate's fallback while the platform limits requests. */
@@ -289,7 +301,7 @@ export async function getPricingRules(input, options = {}) {
289
301
  }
290
302
  let body = validatePricingRules(await readBody(response), Boolean(query.model));
291
303
  const models = 'model' in body ? [body.model] : body.models;
292
- if (models.some(model => (query.model && model.model_id !== query.model)
304
+ if (models.some(model => (query.model && !matchesModel(model, query.model))
293
305
  || (query.product_id && model.product_id !== query.product_id) || (query.operation && model.operation !== query.operation)
294
306
  || (query.modality && model.modality !== query.modality) || (query.lifecycle && model.lifecycle !== query.lifecycle))) {
295
307
  throw new PricingRulesError('mismatched_pricing_rules');
@@ -2,18 +2,20 @@
2
2
  // Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
3
3
  import { z } from 'zod';
4
4
  import { PricingRulesError, getPricingRules, recentModelRules } from './pricing-rules-client.js';
5
- import { QuoteError, compareDecimal, isUsageParameter, prepareQuoteParameters, quoteRequestHash } from './pricing-quote-client.js';
5
+ import { QuoteError, compareDecimal, isUsageParameter, prepareQuoteParameters, quoteRequestHash, reservationErrorOrigin } from './pricing-quote-client.js';
6
6
  import { prepareSeedanceInput } from './seedance-input.js';
7
7
  import { searchUsage } from './search-usage.js';
8
8
  import { CONSERVATIVE_QUOTE_PARAMETERS } from './pricing-derived.js';
9
9
  import { INPUT_IMAGE_TOKENS, isTokenImageModel, tokenImageReservation } from './gpt-image-tokens.js';
10
- import { OMNI_IMAGE_TOKENS, OMNI_UNREAD_TIER, isOmniTokenModel, omniLowerInputTier, omniReservation } from './omni-tokens.js';
10
+ import { OMNI_IMAGE_TOKENS, OMNI_UNREAD_TIER, isOmniTokenModel, omniInputTiers, omniLowerInputTier, omniQuotedTier, omniReservation } from './omni-tokens.js';
11
+ import { isQwenTTSModel, qwenTTSInput, qwenTTSReservation } from './qwen-tts-tokens.js';
11
12
  /**
12
- * How long an approval from estimate_cost is shown as current. The rules' own `fresh_until`
13
+ * How long an approval from estimate_cost holds: 24 hours from the estimate. The rules' own `fresh_until`
13
14
  * is a short refresh window (minutes); people confirming a price in a chat may come back much
14
- * later. generate_* re-evaluates the current rules and refuses with `price_changed` when the
15
- * price moved, so an approval never submits at a stale price; one past this time still holds
16
- * for the same input and price (checkRulesApproval).
15
+ * later. generate_* re-evaluates the current rules every time: it refuses an approval past this
16
+ * time (`quote_expired`) or one whose price rose (`price_changed`), and submits at an unchanged or
17
+ * lower price (checkRulesApproval). The gateway keeps a request ID for 24 hours, so a retry under
18
+ * one approval is still within that window of the first submission.
17
19
  */
18
20
  export const APPROVAL_TTL_MS = 24 * 60 * 60_000;
19
21
  function fail(code, message) { throw new QuoteError(code, message); }
@@ -170,10 +172,12 @@ export function billingUsageHelp(rule, entry) {
170
172
  const declared = new Set((rule.parameters ?? []).map(p => p.name));
171
173
  return helpLines([...declared].filter(name => isUsageParameter(entry.id, name)).sort(), entry, rule, declared);
172
174
  }
173
- // GPT Image and Gemini Omni token models: the reference price counts the tokens the gateway reserves at submission for the input.
175
+ // GPT Image, Gemini Omni and Qwen TTS token models: the reference price counts the tokens the gateway reserves at
176
+ // submission for the input.
174
177
  const RESERVED_TOKENS = new Set(['image_input_tokens', 'image_cached_input_tokens', 'image_output_tokens',
175
178
  'text_input_tokens', 'text_cached_input_tokens', 'text_output_tokens']);
176
179
  const OMNI_TOKENS = new Set(['input_tokens', 'video_output_tokens', 'other_output_tokens']);
180
+ const QWEN_TOKENS = new Set(['input_tokens', 'output_tokens']);
177
181
  /** GPT Image 2.6 rules also bill an SVG's author model. SVG output is not quoted, so a reference price uses none. */
178
182
  const NO_SVG_AUTHOR = { svg_model: 'none', svg_input_tokens: 0, svg_output_tokens: 0 };
179
183
  const svgAuthor = (name) => Object.hasOwn(NO_SVG_AUTHOR, name);
@@ -186,6 +190,10 @@ function reservesTokens(rule, entry) {
186
190
  return (rule.parameters ?? []).every(p => OMNI_TOKENS.has(p.name))
187
191
  && rule.components.some(c => c.role === 'video_output' && c.pricing_status === 'available' && componentReads(c).has('video_output_tokens'));
188
192
  }
193
+ if (isQwenTTSModel(id)) {
194
+ return (rule.parameters ?? []).every(p => QWEN_TOKENS.has(p.name))
195
+ && rule.components.some(c => c.role === 'output' && c.pricing_status === 'available' && componentReads(c).has('output_tokens'));
196
+ }
189
197
  return isTokenImageModel(id)
190
198
  && (rule.parameters ?? []).every(p => RESERVED_TOKENS.has(p.name)
191
199
  || svgAuthor(p.name) && (p.name !== 'svg_model' || (p.values ?? p.enum ?? []).includes(NO_SVG_AUTHOR.svg_model)))
@@ -198,20 +206,36 @@ export function tokenReferenceHelp(rule, entry) {
198
206
  const rates = rule.components.filter(c => ![...componentReads(c)].some(svgAuthor))
199
207
  .map(c => `${c.id} $${c.rate.usd} per ${c.unit === '1k_tokens' ? '1K tokens' : c.unit.replace(/_/g, ' ')}`);
200
208
  if (isOmniTokenModel(entry.id.toLowerCase())) {
201
- return `Billed by actual token usage. estimate_cost gives a reference price for the exact input: the tokens EvoLink reserves at submission for its resolution, duration, prompt, images and input videos, at the published rates (public default rates: ${rates.join('; ')}). Give an input or reference video's length as media_seconds; its resolution is read at submission, so the reference counts the highest (${OMNI_UNREAD_TIER}). The task settles at the tokens it actually uses.`;
209
+ return `Billed by actual token usage. estimate_cost gives a reference price for the exact input: the tokens EvoLink reserves at submission for its resolution, duration, prompt, images and input videos, at the published rates (public default rates: ${rates.join('; ')}). Give an input or reference video's length as media_seconds; its resolution is read at submission, so the reference counts the highest (${OMNI_UNREAD_TIER}) and the estimate also lists the price at each input resolution. The task settles at the tokens it actually uses.`;
210
+ }
211
+ if (isQwenTTSModel(entry.id)) {
212
+ return `Billed by actual token usage. estimate_cost gives a reference price for the exact input: the tokens EvoLink reserves at submission for the text (after hot_fix.replace), an instruction or [tags] and hot_fix, at the published rates (public default rates: ${rates.join('; ')}). It counts each character's worst case, so the task usually settles below it, at the tokens it actually uses.`;
202
213
  }
203
214
  return `Billed by actual token usage. estimate_cost gives a reference price for the exact input: the tokens EvoLink reserves at submission for its size, quality, n, prompt and reference images, at the published rates (public default rates: ${rates.join('; ')}). The task settles at the tokens it actually uses.`;
204
215
  }
205
- /** An Omni reservation's tokens as the rule's parameters. */
206
- const omniParameters = (rule, usage) => Object.fromEntries((rule.parameters ?? []).map(p => [p.name, usage.tokens[p.name] ?? 0]));
216
+ /** An Omni or Qwen TTS reservation's tokens as the rule's parameters. */
217
+ const tokenParameters = (rule, tokens) => Object.fromEntries((rule.parameters ?? []).map(p => [p.name, tokens[p.name] ?? 0]));
218
+ const omniParameters = (rule, usage) => tokenParameters(rule, usage.tokens);
207
219
  function reservation(rule, entry, input, countPromptTokens, mediaSeconds) {
208
220
  if (!reservesTokens(rule, entry))
209
221
  return undefined;
222
+ try {
223
+ return tokenReservation(rule, entry, input, countPromptTokens, mediaSeconds);
224
+ }
225
+ catch (error) {
226
+ throw error instanceof QuoteError ? reservationErrorOrigin(error, entry, input) : error;
227
+ }
228
+ }
229
+ function tokenReservation(rule, entry, input, countPromptTokens, mediaSeconds) {
210
230
  const id = entry.id.toLowerCase();
211
231
  if (isOmniTokenModel(id)) {
212
232
  const usage = omniReservation(id, input, mediaSeconds, { countPromptTokens });
213
233
  return 'needs' in usage ? usage : { omni: usage, parameters: omniParameters(rule, usage) };
214
234
  }
235
+ if (isQwenTTSModel(id)) {
236
+ const usage = qwenTTSReservation(input);
237
+ return { qwen: usage, parameters: tokenParameters(rule, usage.tokens) };
238
+ }
215
239
  const usage = tokenImageReservation(id, input, countPromptTokens);
216
240
  const parameters = {};
217
241
  for (const p of rule.parameters ?? []) {
@@ -250,14 +274,18 @@ function omniBasis(usage) {
250
274
  parts.push(`${tokenText(t.other_output_tokens)} other output tokens`);
251
275
  return `Reference price: published token rates applied to what EvoLink reserves at submission for this input: ${parts.join(', ')}, each part rounded up.`;
252
276
  }
253
- function omniNotes(usage, ignored, lower) {
277
+ const tierList = (prices) => prices.map(price => `${price.resolution}${price.quoted ? ' (quoted)' : ''}: ${price.amounts.credits} credits (about $${price.amounts.usd})`).join('; ');
278
+ function omniNotes(usage, ignored, prices) {
254
279
  const notes = [CONFIRM_REFERENCE];
255
280
  const videos = usage.input_videos;
256
281
  if (videos?.resolution_assumed) {
257
- notes.push(`EvoLink reads the input video's resolution at submission; the request does not give it, so the reference counts the highest, ${videos.resolution}, as EvoLink reserves when it cannot read it.${lower ? ` A ${lower.tier} input video reserves ${lower.amounts.credits} credits (about $${lower.amounts.usd}) instead.` : ''}`);
282
+ notes.push(`EvoLink reads the input video's resolution at submission; the request does not give it, so the reference counts the highest, ${videos.resolution}, as EvoLink reserves when it cannot read it.${prices.length ? ` If the ${videos.count > 1 ? 'reference videos are' : 'input video is'} ${tierList(prices)}.` : ''}`);
283
+ const output = usage.output.resolution;
284
+ if (!usage.output.follows_input && output !== '360p')
285
+ notes.push(`An input video at or below the output resolution, ${output}, reserves the same as one at ${output}.`);
258
286
  }
259
287
  if (usage.upscale?.source_assumed) {
260
- notes.push(`EvoLink reads the source video's resolution at submission; the reference counts the source that costs most for ${usage.upscale.target}, ${usage.upscale.source}.${lower ? ` A ${lower.tier} source reserves ${lower.amounts.credits} credits (about $${lower.amounts.usd}) instead.` : ''}`);
288
+ notes.push(`EvoLink reads the source video's resolution at submission; the reference counts the source that costs most for ${usage.upscale.target}, ${usage.upscale.source}.${prices.length ? ` If the source video is ${tierList(prices)}.` : ''}`);
261
289
  }
262
290
  if (videos && usage.route !== 'upscale')
263
291
  notes.push(`media_seconds counts ${videos.count > 1 ? 'each reference video' : 'the input video'} at ${videos.seconds} s (rounded up); EvoLink measures ${videos.count > 1 ? 'each' : 'it'} at submission.`);
@@ -271,6 +299,19 @@ function omniNotes(usage, ignored, lower) {
271
299
  notes.push(ignoredNote(ignored));
272
300
  return notes;
273
301
  }
302
+ function qwenBasis(usage) {
303
+ return `Reference price: published token rates applied to what EvoLink reserves at submission for this input: ${tokenText(usage.tokens.input_tokens)} input tokens and ${tokenText(usage.tokens.output_tokens)} output tokens for ${tokenText(usage.characters)} characters of text${usage.hot_fix_characters ? ' and hot_fix' : ''}, each part rounded up.`;
304
+ }
305
+ function qwenNotes(usage, ignored) {
306
+ const notes = [CONFIRM_REFERENCE, 'EvoLink reserves the most each kind of character uses (Han characters, letters without case, lowercase letters, spaces and punctuation, other characters), so the task usually settles below the reference price.'];
307
+ if (usage.expressive)
308
+ notes.push('An instruction or a [tag] in the text raises the reserved output tokens.');
309
+ if (usage.hot_fix_characters)
310
+ notes.push('The text is counted after hot_fix.replace, as it is synthesized; hot_fix itself also counts toward the input tokens.');
311
+ if (ignored.length > 0)
312
+ notes.push(ignoredNote(ignored));
313
+ return notes;
314
+ }
274
315
  function evaluate(node, params) {
275
316
  const nodes = node.args ?? [], at = (i) => evaluate(nodes[i], params), number = (i) => numeric(at(i));
276
317
  switch (node.op) {
@@ -384,8 +425,9 @@ export const ApprovedRulesEstimate = z.object({ source: z.literal('pricing_rules
384
425
  fingerprint: z.string().regex(/^[a-f0-9]{64}$/), total_uc: z.string().max(32).regex(/^\d+$/),
385
426
  expires_at: z.string().datetime({ offset: true }), batch_items: z.number().int().min(1).max(MAX_BATCH_ITEMS).optional() }).strict();
386
427
  function economicRules(rule) {
387
- // Freshness and configuration timestamps do not change the approved price.
388
- return { ...rule, components: rule.components.map(({ effective_at, official_rate, ...c }) => ({ ...c,
428
+ // Identity aliases, freshness and configuration timestamps do not change the approved price.
429
+ const { aliases: _aliases, ...economic } = rule;
430
+ return { ...economic, components: rule.components.map(({ effective_at, official_rate, ...c }) => ({ ...c,
389
431
  tiers: c.tiers.map(({ effective_at, official_rate, ...t }) => t) })) };
390
432
  }
391
433
  /** countPromptTokens replaces the approximate prompt token count, for comparing with the gateway's exact count. */
@@ -394,15 +436,19 @@ export function calculateRulesEstimate(body, entry, input, options = {}) {
394
436
  if (!rule || rule.model_id !== entry.id.toLowerCase() || rule.modality !== entry.kind || rule.policy_source !== 'published' || rule.pricing_status !== 'available') {
395
437
  fail('pricing_rules_unavailable', 'This model has no available published media pricing policy.');
396
438
  }
397
- const prepared = prepareSeedanceInput(entry, input);
398
- if (prepared.errors.length)
399
- throw new QuoteError('invalid_quote_parameter', `${prepared.errors[0].param} ${prepared.errors[0].problem}`, prepared.errors[0].param);
439
+ const prepared = prepareSeedanceInput(entry, qwenTTSInput(entry.id, input));
440
+ if (prepared.errors.length) {
441
+ const issue = prepared.errors[0];
442
+ const check = issue.param === 'duration' ? 'range' : issue.param === 'quality' ? 'conflict'
443
+ : issue.param === 'model_params.web_search' ? 'type' : 'shape';
444
+ throw new QuoteError('invalid_quote_parameter', `${issue.param} ${issue.problem}`, issue.param, 'caller', check, 'seedance');
445
+ }
400
446
  const effectiveInput = prepared.input;
401
447
  const declared = new Set((rule.parameters ?? []).map(p => p.name));
402
448
  const id = entry.id.toLowerCase();
403
- // GPT Image and Gemini Omni token models never use token counts from pricing_parameters: the reference counts what
404
- // the gateway reserves for this input. Leaving them out of the request hash lets a generation pass them or not.
405
- const ignored = isTokenImageModel(id) || isOmniTokenModel(id)
449
+ // GPT Image, Gemini Omni and Qwen TTS token models never use token counts from pricing_parameters: the reference counts
450
+ // what the gateway reserves for this input. Leaving them out of the request hash lets a generation pass them or not.
451
+ const ignored = isTokenImageModel(id) || isOmniTokenModel(id) || isQwenTTSModel(id)
406
452
  ? Object.keys(options.pricingParameters ?? {}).filter(name => declared.has(name) && (/tokens$/.test(name) || svgAuthor(name))).sort() : [];
407
453
  const pricingParameters = ignored.length
408
454
  ? Object.fromEntries(Object.entries(options.pricingParameters).filter(([name]) => !ignored.includes(name))) : options.pricingParameters;
@@ -447,20 +493,27 @@ export function calculateRulesEstimate(body, entry, input, options = {}) {
447
493
  request_hash: requestHash, total_uc: amounts.uc, expires_at: new Date(Date.now() + APPROVAL_TTL_MS).toISOString(),
448
494
  fingerprint: quoteRequestHash(entry.id, { rules: economicRules(rule), parameters: params,
449
495
  exchange_rate_version: body.meta.exchange_rate_version, components, missing: [...missing].sort(), total_uc: amounts.uc,
450
- ...(reserved?.gpt || reserved?.omni ? { reservation: reserved.gpt ?? reserved.omni } : {}) }) };
496
+ ...(reserved?.gpt || reserved?.omni || reserved?.qwen ? { reservation: reserved.gpt ?? reserved.omni ?? reserved.qwen } : {}) }) };
451
497
  const status = missing.size ? components.length ? 'partial' : 'needs_input'
452
- : reserved?.gpt || reserved?.omni ? 'token_billed' : 'estimated';
498
+ : reserved?.gpt || reserved?.omni || reserved?.qwen ? 'token_billed' : 'estimated';
453
499
  const missingUsage = [...missing].sort(), usageHelp = helpLines(missingUsage, entry, rule, declared);
454
- const usage = reserved?.gpt, omni = reserved?.omni;
455
- // An Omni input video of unknown resolution counts the highest; the same input at a lower one, for the notes.
456
- const lowerTier = omni && status === 'token_billed' ? omniLowerInputTier(omni) : undefined;
457
- let lower;
458
- if (omni && lowerTier) {
459
- const alternative = omniReservation(id, effectiveInput, options.mediaSeconds, { countPromptTokens: options.countPromptTokens, inputTier: lowerTier });
460
- const cost = 'needs' in alternative ? undefined : chargeComponents(rule, declared, { ...params, ...omniParameters(rule, alternative) }, 1n, new Set()).total;
461
- if (cost !== undefined && cost < total)
462
- lower = { tier: lowerTier, amounts: amountsForUC(String(cost)) };
500
+ const usage = reserved?.gpt, omni = reserved?.omni, qwen = reserved?.qwen;
501
+ // An Omni input video of unknown resolution counts the highest; the same input at each resolution EvoLink can read
502
+ // it at, for the notes. lower_input keeps the one lower price 1.12.0 gave (720p; an upscale: the cheaper source).
503
+ const tierPrices = [];
504
+ if (omni && status === 'token_billed') {
505
+ const quoted = omniQuotedTier(omni);
506
+ for (const tier of omniInputTiers(omni)) {
507
+ const alternative = omniReservation(id, effectiveInput, options.mediaSeconds, { countPromptTokens: options.countPromptTokens, inputTier: tier });
508
+ if ('needs' in alternative)
509
+ continue;
510
+ const cost = chargeComponents(rule, declared, { ...params, ...omniParameters(rule, alternative) }, 1n, new Set()).total;
511
+ tierPrices.push({ resolution: tier, amounts: amountsForUC(String(cost)), ...(tier === quoted ? { quoted: true } : {}) });
512
+ }
463
513
  }
514
+ const lowerTier = omni && status === 'token_billed' ? omniLowerInputTier(omni) : undefined;
515
+ const lowerPrice = tierPrices.find(price => price.resolution === lowerTier);
516
+ const lower = lowerPrice && BigInt(lowerPrice.amounts.uc) < total ? { tier: lowerPrice.resolution, amounts: lowerPrice.amounts } : undefined;
464
517
  const estimate = { status,
465
518
  // Nothing could be priced: a zero amount would read as free.
466
519
  ...(status === 'needs_input' ? {} : { min_usd: Number(amounts.usd), max_usd: Number(amounts.usd),
@@ -469,16 +522,20 @@ export function calculateRulesEstimate(body, entry, input, options = {}) {
469
522
  basis: [status === 'token_billed' && usage
470
523
  ? `Reference price: published token rates applied to what EvoLink reserves at submission for this input. Per image: ${usage.per_image.image_output_tokens.toLocaleString('en-US')} output tokens (${usage.output.width}×${usage.output.height}${usage.output.gif ? `, ${usage.output.gif.frames} GIF frames` : ''}, quality ${usage.output.quality}), about ${usage.per_image.text_input_tokens.toLocaleString('en-US')} prompt tokens and ${usage.per_image.image_input_tokens.toLocaleString('en-US')} reference-image tokens, each part rounded up; ${usage.images} image${usage.images > 1 ? 's' : ''}.`
471
524
  : status === 'token_billed' && omni ? omniBasis(omni)
472
- : 'Published full pricing rules evaluated for the supplied generation parameters; exact UC rounding and component minimums.'],
525
+ : status === 'token_billed' && qwen ? qwenBasis(qwen)
526
+ : 'Published full pricing rules evaluated for the supplied generation parameters; exact UC rounding and component minimums.'],
473
527
  ...(missing.size ? { uncheckable_reason: 'usage', missing_usage: missingUsage, usage_help: usageHelp } : {}),
474
528
  ...(status === 'token_billed' && usage ? { reference_usage: usage } : {}),
475
- ...(status === 'token_billed' && omni ? { reference_usage: { ...omni, ...(lower ? { lower_input: { resolution: lower.tier, amounts: lower.amounts } } : {}) } } : {}),
529
+ ...(status === 'token_billed' && omni ? { reference_usage: { ...omni, ...(lower ? { lower_input: { resolution: lower.tier, amounts: lower.amounts } } : {}),
530
+ ...(tierPrices.length ? { input_resolution_prices: tierPrices } : {}) } } : {}),
531
+ ...(status === 'token_billed' && qwen ? { reference_usage: qwen } : {}),
476
532
  possible_extras: status === 'partial' ? usageHelp.map(line => `Additional charge depends on ${line}`) : [],
477
533
  notes: ['Public default prices; account discounts are not included.', ...status === 'needs_input'
478
534
  ? ['No total is quoted until the missing usage is known, and generate_* will not submit before then.']
479
535
  : status === 'token_billed' && usage ? reservationNotes(usage, ignored)
480
- : status === 'token_billed' && omni ? omniNotes(omni, ignored, lower)
481
- : ['Confirm the estimated cost before generation. Actual billed usage and final charges may differ.']] };
536
+ : status === 'token_billed' && omni ? omniNotes(omni, ignored, tierPrices)
537
+ : status === 'token_billed' && qwen ? qwenNotes(qwen, ignored)
538
+ : ['Confirm the estimated cost before generation. Actual billed usage and final charges may differ.']] };
482
539
  if (zeroUsage.length)
483
540
  estimate.notes.push(`pricing_parameters ${zeroUsage.join(', ')} given as 0 would price this generation at 0. No media generation is free, so ${zeroUsage.length > 1 ? 'they count' : 'it counts'} as missing.`);
484
541
  if (ignored.length && status !== 'token_billed')
@@ -554,9 +611,9 @@ export async function readPricingRulesFor(entry, options = {}) {
554
611
  }
555
612
  /** Said with an estimate made from rules read earlier, while the platform limits pricing requests. */
556
613
  export function recentRulesNote(readAt) {
557
- return `The platform is limiting pricing requests right now, so this estimate uses the published rules read at ${readAt}. generate_* reads the current rules again before submitting and asks for a new approval if the price changed.`;
614
+ return `The platform is limiting pricing requests right now, so this estimate uses the published rules read at ${readAt}. generate_* reads the current rules again before submitting and asks for a new approval if the price rose.`;
558
615
  }
559
- /** An approval from cached or recent rules can never submit at a changed price: checkRulesApproval refuses it. */
616
+ /** An approval from cached or recent rules can never submit at a higher price: checkRulesApproval refuses it. */
560
617
  export async function createRulesEstimate(entry, input, options = {}) {
561
618
  const { body, readAt } = await readPricingRulesFor(entry, options);
562
619
  const result = calculateRulesEstimate(body, entry, input, options);
@@ -565,20 +622,27 @@ export async function createRulesEstimate(entry, input, options = {}) {
565
622
  result.estimate.notes.push(recentRulesNote(readAt));
566
623
  return { ...result, rules_read_at: readAt };
567
624
  }
625
+ /** An approval holds until its expires_at, not at it. */
626
+ export const approvalExpired = (approval, now = Date.now()) => Date.parse(approval.expires_at) <= now;
568
627
  /**
569
- * An approval holds for the same input at the same price. Past its expires_at it still holds when neither changed
570
- * (`expired: true`, for the result to say so); a changed input or price needs a new estimate and approval.
628
+ * Only a higher total needs a new approval: an unchanged or lower one submits, whatever else changed in the rules. A
629
+ * partial estimate's total is the part it prices.
630
+ */
631
+ export const priceRose = (approval, fresh) => BigInt(fresh.total_uc) > BigInt(approval.total_uc);
632
+ /**
633
+ * An approval holds for the same input until its expires_at, at the approved price or lower. A changed input
634
+ * (quote_input_changed), an expired approval (quote_expired) or a higher price (price_changed) needs a new estimate and
635
+ * approval.
571
636
  */
572
637
  export function checkRulesApproval(approval, fresh) {
573
- const expired = Date.parse(approval.expires_at) <= Date.now();
574
638
  if (approval.batch_items !== undefined) {
575
639
  fail('quote_input_changed', 'This pricing_quote approves a batch (inputs); pass the same inputs, or estimate this input and obtain approval.');
576
640
  }
577
641
  if (approval.request_hash !== fresh.approval.request_hash || approval.model_id !== fresh.approval.model_id) {
578
642
  fail('quote_input_changed', 'The generation input differs from the approved estimate.');
579
643
  }
580
- if (approval.fingerprint !== fresh.approval.fingerprint || approval.total_uc !== fresh.approval.total_uc) {
581
- fail('price_changed', 'The pricing rules or estimated price changed. Estimate again and obtain approval.');
582
- }
583
- return { expired };
644
+ if (approvalExpired(approval))
645
+ fail('quote_expired', `The approved estimate expired at ${approval.expires_at}. Estimate again and obtain approval.`);
646
+ if (priceRose(approval, fresh.approval))
647
+ fail('price_changed', 'The estimated price rose after it was approved. Estimate again and obtain approval.');
584
648
  }