@evolinkai/cli 0.14.1 → 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/README.md +18 -2
- package/package.json +2 -2
- package/skills/evolink-cli/SKILL.md +5 -1
- package/skills/evolink-cli/references/ad-rebuild.md +76 -0
- package/src/cli.mjs +35 -3
- package/src/help.mjs +14 -1
- package/src/platform/core/src/services/gpt-image-tokens.js +18 -16
- package/src/platform/core/src/services/omni-tokens.js +17 -15
- package/src/platform/core/src/services/pricing-quote-client.js +86 -22
- package/src/platform/core/src/services/pricing-rules-client.js +15 -3
- package/src/platform/core/src/services/pricing-rules-estimate.js +18 -5
- package/src/platform/core/src/services/qwen-tts-tokens.js +12 -10
- package/src/platform/core/src/tools/estimate-cost.js +3 -3
- package/src/platform/core/src/tools/generate.js +4 -4
- package/src/platform/core/src/tools/get-pricing-rules.js +5 -2
- package/src/platform/core/src/version.js +1 -1
- package/src/platform/source.json +23 -23
- package/src/state.mjs +18 -4
- package/src/workflow.mjs +138 -0
|
@@ -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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
157
|
+
fill(input.image_urls.length, 'caller');
|
|
98
158
|
else if (typeof input.image_url === 'string')
|
|
99
|
-
|
|
159
|
+
fill(1, 'caller');
|
|
100
160
|
else
|
|
101
|
-
|
|
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
|
-
|
|
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
|
-
|
|
183
|
+
fill(mediaSeconds, 'caller');
|
|
121
184
|
if (value === undefined && name === 'first_input_video_seconds' && mediaSeconds !== undefined)
|
|
122
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
215
|
+
fill(CONSERVATIVE_QUOTE_PARAMETERS[`${model.toLowerCase()} ${name}`]?.value, 'service');
|
|
153
216
|
if (value === undefined)
|
|
154
|
-
|
|
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
|
-
|
|
225
|
+
reject('must be a finite scalar.', 'scalar');
|
|
162
226
|
}
|
|
163
227
|
if (typeof value === 'string' && value.length > 128)
|
|
164
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
244
|
+
reject('is outside the published range.', 'range');
|
|
181
245
|
}
|
|
182
246
|
}
|
|
183
247
|
else if (p.type === 'boolean' && typeof value !== 'boolean') {
|
|
184
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
|
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
|
|
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,7 +2,7 @@
|
|
|
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';
|
|
@@ -219,6 +219,14 @@ const omniParameters = (rule, usage) => tokenParameters(rule, usage.tokens);
|
|
|
219
219
|
function reservation(rule, entry, input, countPromptTokens, mediaSeconds) {
|
|
220
220
|
if (!reservesTokens(rule, entry))
|
|
221
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) {
|
|
222
230
|
const id = entry.id.toLowerCase();
|
|
223
231
|
if (isOmniTokenModel(id)) {
|
|
224
232
|
const usage = omniReservation(id, input, mediaSeconds, { countPromptTokens });
|
|
@@ -417,8 +425,9 @@ export const ApprovedRulesEstimate = z.object({ source: z.literal('pricing_rules
|
|
|
417
425
|
fingerprint: z.string().regex(/^[a-f0-9]{64}$/), total_uc: z.string().max(32).regex(/^\d+$/),
|
|
418
426
|
expires_at: z.string().datetime({ offset: true }), batch_items: z.number().int().min(1).max(MAX_BATCH_ITEMS).optional() }).strict();
|
|
419
427
|
function economicRules(rule) {
|
|
420
|
-
//
|
|
421
|
-
|
|
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,
|
|
422
431
|
tiers: c.tiers.map(({ effective_at, official_rate, ...t }) => t) })) };
|
|
423
432
|
}
|
|
424
433
|
/** countPromptTokens replaces the approximate prompt token count, for comparing with the gateway's exact count. */
|
|
@@ -428,8 +437,12 @@ export function calculateRulesEstimate(body, entry, input, options = {}) {
|
|
|
428
437
|
fail('pricing_rules_unavailable', 'This model has no available published media pricing policy.');
|
|
429
438
|
}
|
|
430
439
|
const prepared = prepareSeedanceInput(entry, qwenTTSInput(entry.id, input));
|
|
431
|
-
if (prepared.errors.length)
|
|
432
|
-
|
|
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
|
+
}
|
|
433
446
|
const effectiveInput = prepared.input;
|
|
434
447
|
const declared = new Set((rule.parameters ?? []).map(p => p.name));
|
|
435
448
|
const id = entry.id.toLowerCase();
|
|
@@ -50,14 +50,16 @@ export function qwenCharacterClass(character) {
|
|
|
50
50
|
return 'punctuation';
|
|
51
51
|
return 'other';
|
|
52
52
|
}
|
|
53
|
-
function invalid(param, message
|
|
53
|
+
function invalid(param, message, check) {
|
|
54
|
+
throw new QuoteError('invalid_quote_parameter', message, param, 'caller', check, 'qwen_tts');
|
|
55
|
+
}
|
|
54
56
|
/** A string as the gateway decodes it from the request JSON: an unpaired surrogate becomes U+FFFD. */
|
|
55
57
|
const decoded = (text) => text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, '\uFFFD');
|
|
56
58
|
function textParam(input, param) {
|
|
57
59
|
const value = input[param];
|
|
58
60
|
if (value === undefined || value === null)
|
|
59
61
|
return '';
|
|
60
|
-
return typeof value === 'string' ? decoded(value) : invalid(param, `${param} must be a string
|
|
62
|
+
return typeof value === 'string' ? decoded(value) : invalid(param, `${param} must be a string.`, 'type');
|
|
61
63
|
}
|
|
62
64
|
const characters = (text) => [...text].length;
|
|
63
65
|
/** strings.TrimSpace(text) == "": only the characters unicode.IsSpace accepts. */
|
|
@@ -78,7 +80,7 @@ function byCodePoint(a, b) {
|
|
|
78
80
|
}
|
|
79
81
|
/** validateQwenAudioTTSHotFix: {pronunciation?, replace?}, each a non-empty list of {"word": "value"} objects. */
|
|
80
82
|
function checkHotFix(hotFix) {
|
|
81
|
-
const shape = () => invalid('hot_fix', 'hot_fix must be an object with pronunciation and/or replace arrays of {"word": "value"} objects.');
|
|
83
|
+
const shape = () => invalid('hot_fix', 'hot_fix must be an object with pronunciation and/or replace arrays of {"word": "value"} objects.', 'shape');
|
|
82
84
|
if (!isObject(hotFix) || !Object.keys(hotFix).length)
|
|
83
85
|
shape();
|
|
84
86
|
let entries = 0;
|
|
@@ -96,7 +98,7 @@ function checkHotFix(hotFix) {
|
|
|
96
98
|
}
|
|
97
99
|
}
|
|
98
100
|
if (entries > MAX_HOT_FIX_ENTRIES)
|
|
99
|
-
invalid('hot_fix', `hot_fix may contain at most ${MAX_HOT_FIX_ENTRIES} entries in total, got ${entries}
|
|
101
|
+
invalid('hot_fix', `hot_fix may contain at most ${MAX_HOT_FIX_ENTRIES} entries in total, got ${entries}.`, 'count');
|
|
100
102
|
}
|
|
101
103
|
/**
|
|
102
104
|
* QwenAudioTTSEffectiveText: the text after hot_fix.replace, item by item and each item's words in code point order,
|
|
@@ -147,7 +149,7 @@ export function goJSONCharacters(value) {
|
|
|
147
149
|
if (typeof value === 'boolean')
|
|
148
150
|
return value ? 4 : 5;
|
|
149
151
|
// checkHotFix leaves only objects, lists and strings; Go writes numbers differently from JavaScript.
|
|
150
|
-
return invalid('hot_fix', 'hot_fix holds only objects, lists and strings.');
|
|
152
|
+
return invalid('hot_fix', 'hot_fix holds only objects, lists and strings.', 'shape');
|
|
151
153
|
}
|
|
152
154
|
/**
|
|
153
155
|
* The tokens the gateway reserves at submission for this input. The text is prompt, or input when prompt is empty;
|
|
@@ -156,22 +158,22 @@ export function goJSONCharacters(value) {
|
|
|
156
158
|
export function qwenTTSReservation(input) {
|
|
157
159
|
const prompt = textParam(input, 'prompt'), alias = textParam(input, 'input');
|
|
158
160
|
if (prompt !== '' && alias !== '' && prompt !== alias)
|
|
159
|
-
invalid('input', 'prompt and input differ; send only one.');
|
|
161
|
+
invalid('input', 'prompt and input differ; send only one.', 'conflict');
|
|
160
162
|
const text = prompt !== '' ? prompt : alias;
|
|
161
163
|
if (blank(text))
|
|
162
|
-
invalid('prompt', 'prompt is required.');
|
|
164
|
+
invalid('prompt', 'prompt is required.', 'required');
|
|
163
165
|
if (characters(text) > QWEN_TTS_MAX_TEXT)
|
|
164
|
-
invalid('prompt', `prompt must be at most ${QWEN_TTS_MAX_TEXT} characters, got ${characters(text)}
|
|
166
|
+
invalid('prompt', `prompt must be at most ${QWEN_TTS_MAX_TEXT} characters, got ${characters(text)}.`, 'length');
|
|
165
167
|
const instruction = textParam(input, 'instruction');
|
|
166
168
|
const billed = billingCharacters(instruction);
|
|
167
169
|
if (billed > MAX_INSTRUCTION)
|
|
168
|
-
invalid('instruction', `instruction must be at most ${MAX_INSTRUCTION} billing characters (Han characters count as 2), got ${billed}
|
|
170
|
+
invalid('instruction', `instruction must be at most ${MAX_INSTRUCTION} billing characters (Han characters count as 2), got ${billed}.`, 'length');
|
|
169
171
|
const hotFix = input.hot_fix === null ? undefined : input.hot_fix;
|
|
170
172
|
if (hotFix !== undefined)
|
|
171
173
|
checkHotFix(hotFix);
|
|
172
174
|
const effective = qwenEffectiveText(text, hotFix);
|
|
173
175
|
if (!effective.ok)
|
|
174
|
-
invalid('hot_fix', `prompt must be at most ${QWEN_TTS_MAX_TEXT} characters after hot_fix.replace is applied, got ${effective.characters}
|
|
176
|
+
invalid('hot_fix', `prompt must be at most ${QWEN_TTS_MAX_TEXT} characters after hot_fix.replace is applied, got ${effective.characters}.`, 'length');
|
|
175
177
|
const hotFixCharacters = hotFix === undefined ? 0 : goJSONCharacters(hotFix);
|
|
176
178
|
const expressive = instruction !== '' || effective.text.includes('[');
|
|
177
179
|
const classes = { han: 0, caseless: 0, lower: 0, punctuation: 0, other: 0 };
|
|
@@ -7,7 +7,7 @@ import { resolveModel, suggestModels } from '../services/model-catalog.js';
|
|
|
7
7
|
import { formatIssues, validateInput } from '../services/param-validator.js';
|
|
8
8
|
import { formatEstimateRange } from '../services/pricing-client.js';
|
|
9
9
|
import { PricingRulesError, reusablePricingRules } from '../services/pricing-rules-client.js';
|
|
10
|
-
import { QuoteError, QuoteParameters } from '../services/pricing-quote-client.js';
|
|
10
|
+
import { QuoteError, QuoteParameters, quoteErrorAt, quoteErrorFields } from '../services/pricing-quote-client.js';
|
|
11
11
|
import { calculateRulesEstimate, createRulesEstimate, readPricingRulesFor, recentRulesNote } from '../services/pricing-rules-estimate.js';
|
|
12
12
|
import { qwenTTSInput } from '../services/qwen-tts-tokens.js';
|
|
13
13
|
import { prepareSeedanceInput } from '../services/seedance-input.js';
|
|
@@ -143,7 +143,7 @@ export function registerEstimateCost(server, config) {
|
|
|
143
143
|
});
|
|
144
144
|
if (error instanceof QuoteError)
|
|
145
145
|
return failure(`${error.message} Nothing was submitted or charged.`, {
|
|
146
|
-
error: { category: 'estimate_unavailable',
|
|
146
|
+
error: { category: 'estimate_unavailable', ...quoteErrorFields(error) },
|
|
147
147
|
pricing_source: pricingSource, submission_allowed: false, final_budget_enforced: false, charged: 'no', ...(inputs ? { batch: { items: inputs.length } } : {})
|
|
148
148
|
});
|
|
149
149
|
const failed = errorResult(error);
|
|
@@ -254,7 +254,7 @@ async function estimateBatch(config, entry, inputs, options) {
|
|
|
254
254
|
return calculateRulesEstimate(body, entry, item.input, { mediaSeconds: options.mediaSeconds, pricingParameters: options.pricingParameters });
|
|
255
255
|
}
|
|
256
256
|
catch (error) {
|
|
257
|
-
throw error instanceof QuoteError ?
|
|
257
|
+
throw error instanceof QuoteError ? quoteErrorAt(error, index) : error;
|
|
258
258
|
}
|
|
259
259
|
});
|
|
260
260
|
const total = batchTotal(entry.id, results), combined = total.estimate, status = total.status;
|
|
@@ -6,7 +6,7 @@ import { BATCH_REQUEST_ID_MAX, BATCH_SUBMIT_CONCURRENCY, MAX_BATCH_ITEMS, batchT
|
|
|
6
6
|
import { resolveModel, suggestModels } from '../services/model-catalog.js';
|
|
7
7
|
import { formatIssues, validateInput } from '../services/param-validator.js';
|
|
8
8
|
import { formatEstimateRange } from '../services/pricing-client.js';
|
|
9
|
-
import { ApprovedAccountQuote, QuoteParameters, QuoteError } from '../services/pricing-quote-client.js';
|
|
9
|
+
import { ApprovedAccountQuote, QuoteParameters, QuoteError, quoteErrorAt, quoteErrorFields } from '../services/pricing-quote-client.js';
|
|
10
10
|
import { ApprovedRulesEstimate, REFERENCE_BUDGET_FACTOR, amountsForUC, calculateRulesEstimate, createRulesEstimate, checkRulesApproval, readPricingRulesFor, referenceAllowance, referenceBudgetExceeded, rulesBudgetExceeded } from '../services/pricing-rules-estimate.js';
|
|
11
11
|
import { PricingRulesError } from '../services/pricing-rules-client.js';
|
|
12
12
|
import { isOmniTokenModel } from '../services/omni-tokens.js';
|
|
@@ -420,7 +420,7 @@ function registerGenerate(server, config, kind) {
|
|
|
420
420
|
charged: 'no', submission_state: 'not_submitted'
|
|
421
421
|
});
|
|
422
422
|
if (error instanceof QuoteError)
|
|
423
|
-
return failure(`${error.message} Nothing was submitted or charged.`, { error: { category: 'estimate_unavailable',
|
|
423
|
+
return failure(`${error.message} Nothing was submitted or charged.`, { error: { category: 'estimate_unavailable', ...quoteErrorFields(error) }, charged: 'no', submission_state: 'not_submitted' });
|
|
424
424
|
// clientRequestId is set right before the submit, so it also tells whether a request may have gone out.
|
|
425
425
|
return errorResult(error, { paid: clientRequestId !== undefined, clientRequestId, taskId: acceptedTaskId,
|
|
426
426
|
phase: acceptedTaskId ? 'accepted' : clientRequestId ? 'submit_started' : 'before_submit' });
|
|
@@ -527,7 +527,7 @@ async function generateBatch(config, kind, args, extra, startedMono) {
|
|
|
527
527
|
catch (error) {
|
|
528
528
|
itemSkipped[index] = skipEstimate ? unpriced(error) : undefined;
|
|
529
529
|
if (!itemSkipped[index])
|
|
530
|
-
throw error instanceof QuoteError ?
|
|
530
|
+
throw error instanceof QuoteError ? quoteErrorAt(error, index) : error;
|
|
531
531
|
return undefined;
|
|
532
532
|
}
|
|
533
533
|
}) : [];
|
|
@@ -707,7 +707,7 @@ async function generateBatch(config, kind, args, extra, startedMono) {
|
|
|
707
707
|
});
|
|
708
708
|
if (error instanceof QuoteError)
|
|
709
709
|
return failure(`${error.message} Nothing was submitted or charged.`, {
|
|
710
|
-
error: { category: 'estimate_unavailable',
|
|
710
|
+
error: { category: 'estimate_unavailable', ...quoteErrorFields(error) }, charged: 'no', submission_state: 'not_submitted', batch
|
|
711
711
|
});
|
|
712
712
|
// Each submission reports its own outcome, so an error here came before any item was submitted.
|
|
713
713
|
return errorResult(error, { paid: false, clientRequestId: batchId, phase: 'before_submit' });
|
|
@@ -8,7 +8,7 @@ import { failure, ok, READ_ONLY, retryText } from './shared.js';
|
|
|
8
8
|
export function registerPricingRules(server, config) {
|
|
9
9
|
server.registerTool('get_pricing_rules', {
|
|
10
10
|
title: 'Read public pricing rules',
|
|
11
|
-
description: 'Read schema-2 public default pricing rules, decimal-string rates including fractional UC, minimum charges, tiers and optional full expressions. Free and anonymous upstream. The returned price_selection, when present, identifies route-priority prices or legacy minimum configuration prices. Coverage follows the returned published policies and supported legacy text adapters, including media when available. These are public reference rates, not account prices, live availability, a task quote, a bill or a final spending cap. Do not substitute these rules for media estimate_cost or assume empty media results are free.',
|
|
11
|
+
description: 'Read schema-2 public default pricing rules, decimal-string rates including fractional UC, minimum charges, tiers and optional full expressions. Free and anonymous upstream. Model IDs and published aliases are case-insensitive; results keep the canonical model_id and published aliases. The returned price_selection, when present, identifies route-priority prices or legacy minimum configuration prices. Coverage follows the returned published policies and supported legacy text adapters, including media when available. These are public reference rates, not account prices, live availability, a task quote, a bill or a final spending cap. Do not substitute these rules for media estimate_cost or assume empty media results are free.',
|
|
12
12
|
inputSchema: PricingRulesQuery.shape,
|
|
13
13
|
annotations: { title: 'Read public pricing rules', ...READ_ONLY },
|
|
14
14
|
}, async (input) => {
|
|
@@ -37,12 +37,15 @@ export function registerPricingRules(server, config) {
|
|
|
37
37
|
warnings.push(`${rejected.length} model(s) were left out because their published rules could not be read: ${rejected.slice(0, 20).join(', ')}${rejected.length > 20 ? `, and ${rejected.length - 20} more` : ''}. Missing rules do not mean these models are free.`);
|
|
38
38
|
}
|
|
39
39
|
const lines = [`Public pricing rules (${body.meta.price_scope}; ${selection}; ${source}); ${models.length} model(s).`, ...warnings];
|
|
40
|
+
if (input.model && 'model' in body && input.model !== body.model.model_id) {
|
|
41
|
+
lines.push(`Requested model ${input.model} resolves to ${body.model.model_id} through a published alias.`);
|
|
42
|
+
}
|
|
40
43
|
for (const model of models) {
|
|
41
44
|
lines.push(`${model.model_id} (${model.modality}; ${model.pricing_status}; ${model.policy_source} v${model.policy_version})`);
|
|
42
45
|
for (const component of model.components)
|
|
43
46
|
lines.push(`- ${component.role}: ${component.rate.usd} USD (${component.rate.credits} credits) per ${component.billing_unit_size} ${component.unit === '1k_tokens' ? 'tokens' : component.unit}; minimum ${component.minimum_charge.usd} USD; ${component.tiers.length} tier(s); ${component.pricing_status}.`);
|
|
44
47
|
}
|
|
45
|
-
return ok(lines.join('\n'), { ...body, pricing_source: source,
|
|
48
|
+
return ok(lines.join('\n'), { ...body, ...(input.model ? { requested_model: input.model } : {}), pricing_source: source,
|
|
46
49
|
pricing_endpoint: '/v1/catalog/pricing-rules', quote_established: false, final_budget_enforced: false,
|
|
47
50
|
account_price: false, warnings });
|
|
48
51
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
|
|
2
2
|
// Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
|
|
3
3
|
/** Version reported in serverInfo and in the X-Evo-Client-Version header. */
|
|
4
|
-
export const MCP_VERSION = '1.12.
|
|
4
|
+
export const MCP_VERSION = '1.12.2';
|