@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.
@@ -0,0 +1,189 @@
1
+ // Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
2
+ // Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
3
+ import { QuoteError } from './pricing-quote-client.js';
4
+ // The tokens the gateway reserves for a Qwen Audio TTS speech task at submission. Ported from GroAPI
5
+ // (feat/task-microservice-split) service/qwen_audio_tts.go (QwenAudioTTSEffectiveText and
6
+ // EstimateQwenAudioTTSPreChargeUsage) and the speech checks in controller/unified_audio_qwen_tts.go that run before it.
7
+ // The gateway counts each character's worst case by its class, so a task usually settles below the reservation, at the
8
+ // tokens the upstream reports.
9
+ const MODELS = new Set(['qwen-audio-3.1-tts-flash']);
10
+ /** Qwen Audio TTS models, which the gateway reserves and bills by input and output token counts. */
11
+ export const isQwenTTSModel = (model) => MODELS.has(model.trim().toLowerCase());
12
+ /**
13
+ * The input as the gateway reads it: hot_fix null is no hot_fix there (it neither checks it nor sends it on), so it is
14
+ * left out before the documented parameters are checked, the input is priced and it is submitted.
15
+ */
16
+ export function qwenTTSInput(model, input) {
17
+ if (input.hot_fix !== null || !isQwenTTSModel(model))
18
+ return input;
19
+ const rest = { ...input };
20
+ delete rest.hot_fix;
21
+ return rest;
22
+ }
23
+ /** The longest text one task synthesizes, in characters, also after hot_fix.replace. */
24
+ export const QWEN_TTS_MAX_TEXT = 5000;
25
+ /** instruction holds at most this many billing characters, a Han character counting two. */
26
+ const MAX_INSTRUCTION = 100;
27
+ /** hot_fix holds at most this many word entries across its lists. */
28
+ const MAX_HOT_FIX_ENTRIES = 200;
29
+ const HOT_FIX_LISTS = new Set(['pronunciation', 'replace']);
30
+ /** Reserved for every task: what a one-character request uses at most. */
31
+ const BASE_INPUT_TOKENS = 2, BASE_OUTPUT_TOKENS = 10;
32
+ /** Spaces and common punctuation, read like the words around them. */
33
+ const PUNCTUATION = new Set(' .,!?;:\'"-()\n,。!?;:、“”‘’()…—');
34
+ /** Input tokens per character, by class. */
35
+ const INPUT_TOKENS = { han: 1, caseless: 1, lower: 1, punctuation: 1, other: 3 };
36
+ /** Output tokens per character in halves, as read and with an instruction or a [tag] in the text. */
37
+ const OUTPUT_HALVES = {
38
+ han: [16, 20], caseless: [8, 16], lower: [9, 18], punctuation: [6, 12], other: [30, 30]
39
+ };
40
+ const HAN = /^\p{Script=Han}$/u, LETTER = /^\p{L}$/u, UPPER = /^\p{Lu}$/u, LOWER = /^\p{Ll}$/u;
41
+ /** The class the gateway counts a character in, checked in its order: Han, a letter without case, lowercase, punctuation. */
42
+ export function qwenCharacterClass(character) {
43
+ if (HAN.test(character))
44
+ return 'han';
45
+ if (LETTER.test(character) && !UPPER.test(character) && !LOWER.test(character))
46
+ return 'caseless';
47
+ if (LOWER.test(character))
48
+ return 'lower';
49
+ if (PUNCTUATION.has(character))
50
+ return 'punctuation';
51
+ return 'other';
52
+ }
53
+ function invalid(param, message, check) {
54
+ throw new QuoteError('invalid_quote_parameter', message, param, 'caller', check, 'qwen_tts');
55
+ }
56
+ /** A string as the gateway decodes it from the request JSON: an unpaired surrogate becomes U+FFFD. */
57
+ const decoded = (text) => text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, '\uFFFD');
58
+ function textParam(input, param) {
59
+ const value = input[param];
60
+ if (value === undefined || value === null)
61
+ return '';
62
+ return typeof value === 'string' ? decoded(value) : invalid(param, `${param} must be a string.`, 'type');
63
+ }
64
+ const characters = (text) => [...text].length;
65
+ /** strings.TrimSpace(text) == "": only the characters unicode.IsSpace accepts. */
66
+ const blank = (text) => /^[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]*$/u.test(text);
67
+ /** CountBillingChars: a Han character counts two, any other one. */
68
+ const billingCharacters = (text) => { let count = 0; for (const character of text)
69
+ count += HAN.test(character) ? 2 : 1; return count; };
70
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
71
+ /** sort.Strings: by UTF-8 bytes, which is code point order. */
72
+ function byCodePoint(a, b) {
73
+ const x = [...a], y = [...b];
74
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
75
+ const difference = x[i].codePointAt(0) - y[i].codePointAt(0);
76
+ if (difference)
77
+ return difference;
78
+ }
79
+ return x.length - y.length;
80
+ }
81
+ /** validateQwenAudioTTSHotFix: {pronunciation?, replace?}, each a non-empty list of {"word": "value"} objects. */
82
+ function checkHotFix(hotFix) {
83
+ const shape = () => invalid('hot_fix', 'hot_fix must be an object with pronunciation and/or replace arrays of {"word": "value"} objects.', 'shape');
84
+ if (!isObject(hotFix) || !Object.keys(hotFix).length)
85
+ shape();
86
+ let entries = 0;
87
+ for (const [list, items] of Object.entries(hotFix)) {
88
+ if (!HOT_FIX_LISTS.has(list) || !Array.isArray(items) || !items.length)
89
+ shape();
90
+ for (const item of items) {
91
+ if (!isObject(item) || !Object.keys(item).length)
92
+ shape();
93
+ for (const [word, value] of Object.entries(item)) {
94
+ if (typeof value !== 'string' || word === '' || value === '')
95
+ shape();
96
+ entries++;
97
+ }
98
+ }
99
+ }
100
+ if (entries > MAX_HOT_FIX_ENTRIES)
101
+ invalid('hot_fix', `hot_fix may contain at most ${MAX_HOT_FIX_ENTRIES} entries in total, got ${entries}.`, 'count');
102
+ }
103
+ /**
104
+ * QwenAudioTTSEffectiveText: the text after hot_fix.replace, item by item and each item's words in code point order,
105
+ * and its length. A replacement that would make the text longer than max is not made (ok false, with that length).
106
+ */
107
+ export function qwenEffectiveText(text, hotFix, max = QWEN_TTS_MAX_TEXT) {
108
+ let length = characters(text);
109
+ if (!isObject(hotFix))
110
+ return { text, characters: length, ok: length <= max };
111
+ if (length > max)
112
+ return { text, characters: length, ok: false };
113
+ for (const item of Array.isArray(hotFix.replace) ? hotFix.replace : []) {
114
+ const pair = isObject(item) ? item : {};
115
+ for (const word of Object.keys(pair).sort((a, b) => byCodePoint(decoded(a), decoded(b)))) {
116
+ const target = pair[word];
117
+ if (typeof target !== 'string' || word === '')
118
+ continue;
119
+ const from = decoded(word), to = decoded(target);
120
+ const hits = text.split(from).length - 1;
121
+ if (!hits)
122
+ continue;
123
+ const projected = length + hits * (characters(to) - characters(from));
124
+ if (projected > max)
125
+ return { text, characters: projected, ok: false };
126
+ text = text.split(from).join(to);
127
+ length = projected;
128
+ }
129
+ }
130
+ return { text, characters: length, ok: true };
131
+ }
132
+ /** Characters of json.Marshal(value): Go escapes <, > and & (HTML), U+2028 and U+2029, and control characters. */
133
+ export function goJSONCharacters(value) {
134
+ if (typeof value === 'string') {
135
+ let count = 2;
136
+ for (const character of decoded(value)) {
137
+ const code = character.codePointAt(0);
138
+ count += character === '"' || character === '\\' || '\b\f\n\r\t'.includes(character) ? 2
139
+ : code < 0x20 || character === '<' || character === '>' || character === '&' || code === 0x2028 || code === 0x2029 ? 6 : 1;
140
+ }
141
+ return count;
142
+ }
143
+ if (Array.isArray(value))
144
+ return 2 + value.reduce((sum, item, i) => sum + (i ? 1 : 0) + goJSONCharacters(item), 0);
145
+ if (isObject(value))
146
+ return 2 + Object.entries(value).reduce((sum, [key, item], i) => sum + (i ? 1 : 0) + goJSONCharacters(key) + 1 + goJSONCharacters(item), 0);
147
+ if (value === null)
148
+ return 4;
149
+ if (typeof value === 'boolean')
150
+ return value ? 4 : 5;
151
+ // checkHotFix leaves only objects, lists and strings; Go writes numbers differently from JavaScript.
152
+ return invalid('hot_fix', 'hot_fix holds only objects, lists and strings.', 'shape');
153
+ }
154
+ /**
155
+ * The tokens the gateway reserves at submission for this input. The text is prompt, or input when prompt is empty;
156
+ * the checks are the gateway's own before it reserves, which the documented parameters do not all cover.
157
+ */
158
+ export function qwenTTSReservation(input) {
159
+ const prompt = textParam(input, 'prompt'), alias = textParam(input, 'input');
160
+ if (prompt !== '' && alias !== '' && prompt !== alias)
161
+ invalid('input', 'prompt and input differ; send only one.', 'conflict');
162
+ const text = prompt !== '' ? prompt : alias;
163
+ if (blank(text))
164
+ invalid('prompt', 'prompt is required.', 'required');
165
+ if (characters(text) > QWEN_TTS_MAX_TEXT)
166
+ invalid('prompt', `prompt must be at most ${QWEN_TTS_MAX_TEXT} characters, got ${characters(text)}.`, 'length');
167
+ const instruction = textParam(input, 'instruction');
168
+ const billed = billingCharacters(instruction);
169
+ if (billed > MAX_INSTRUCTION)
170
+ invalid('instruction', `instruction must be at most ${MAX_INSTRUCTION} billing characters (Han characters count as 2), got ${billed}.`, 'length');
171
+ const hotFix = input.hot_fix === null ? undefined : input.hot_fix;
172
+ if (hotFix !== undefined)
173
+ checkHotFix(hotFix);
174
+ const effective = qwenEffectiveText(text, hotFix);
175
+ if (!effective.ok)
176
+ invalid('hot_fix', `prompt must be at most ${QWEN_TTS_MAX_TEXT} characters after hot_fix.replace is applied, got ${effective.characters}.`, 'length');
177
+ const hotFixCharacters = hotFix === undefined ? 0 : goJSONCharacters(hotFix);
178
+ const expressive = instruction !== '' || effective.text.includes('[');
179
+ const classes = { han: 0, caseless: 0, lower: 0, punctuation: 0, other: 0 };
180
+ let inputTokens = BASE_INPUT_TOKENS + hotFixCharacters * 3, halves = BASE_OUTPUT_TOKENS * 2;
181
+ for (const character of effective.text) {
182
+ const kind = qwenCharacterClass(character);
183
+ classes[kind]++;
184
+ inputTokens += INPUT_TOKENS[kind];
185
+ halves += OUTPUT_HALVES[kind][expressive ? 1 : 0];
186
+ }
187
+ return { tokens: { input_tokens: inputTokens, output_tokens: Math.ceil(halves / 2) }, characters: effective.characters, classes,
188
+ hot_fix_characters: hotFixCharacters, expressive };
189
+ }
@@ -20,7 +20,7 @@ export const ESTIMATE_OPT_OUT_GUIDANCE = [
20
20
  'When the user opts out for the rest of the conversation, tell them once, clearly, that later generations in this conversation will be submitted without asking, and that they can start a new conversation or ask you to restore estimates to bring them back.',
21
21
  'If estimate_cost fails for a reason other than invalid input, generate with skip_estimate: true when the user has opted out; otherwise ask once, in one sentence, whether to generate anyway with the cost settled by actual usage, and on yes use skip_estimate: true.',
22
22
  'skip_estimate does not set aside an explicit user budget, does not approve enabling model web or image search, and does not change what is charged; after submitting, tell the user what was reserved or charged.',
23
- 'A pricing_quote that expired keeps its approval while the input and price are unchanged; a changed price needs a new estimate and approval.',
23
+ 'A pricing_quote holds for 24 hours from the estimate, at the approved price or lower: an expired one, a higher price or a changed input needs a new estimate (free) and approval.',
24
24
  ].join(' ');
25
25
  /** How to submit several tasks: clients run paid tool calls one at a time, so one call per task and the wait for each result are what to avoid. */
26
26
  export const BATCH_GENERATION_GUIDANCE = [
@@ -28,9 +28,9 @@ export const BATCH_GENERATION_GUIDANCE = [
28
28
  'For tasks of different models, submit one task per item with wait_seconds: 0.',
29
29
  'Either way, collect the results with list_tasks (task_ids, up to 50 per call; free and read-only, so these calls can run in parallel), and tell the user the tasks generate at the same time.',
30
30
  'Do not rely on n for the count: some models, such as GPT Image, often return fewer images than n.',
31
- 'To finish a batch, call the generate tool again with the same client_request_id and exactly the same inputs within 24 hours: the items its result lists to finish (not submitted, or refused and since fixed) are then submitted, and accepted items return their original tasks without a new charge.',
31
+ 'To finish a batch, call the generate tool again with the same client_request_id and exactly the same inputs within 24 hours of its first submission: the items its result lists to finish (not submitted, or refused and since fixed) are then submitted, and accepted items return their original tasks without a new charge.',
32
32
  'For an item with an unknown outcome, retry later the same way or check list_tasks.',
33
- 'Never resubmit accepted, not-submitted or unknown-outcome items under a new client_request_id: that creates and charges new tasks.',
33
+ 'Within those 24 hours, never resubmit accepted, not-submitted or unknown-outcome items under a new client_request_id: that creates and charges new tasks. Past them the same client_request_id no longer prevents a second charge: check list_tasks first, then submit only the items that did not go through, as a new batch with a new client_request_id.',
34
34
  'An item refused because it differs from what that client_request_id submitted earlier is a new task: it needs a new estimate, approval and client_request_id.',
35
35
  ].join(' ');
36
36
  /** Shared confirmation wording; approval and spending rules above still apply. */
@@ -68,7 +68,7 @@ export const GENERATION_CONFIRMATION_GUIDANCE = [
68
68
  '- For a batch (inputs), use one confirmation for the whole batch: in Output give the number of items and what differs between them, and in Cost the total plus the price per item, or the range when items differ. One approval covers exactly that batch.',
69
69
  '- Keep model web and image search off unless the user explicitly requests or approves enabling it. Never enable search on your own or just because a copied example enables it. If you think search is needed, first explain its extra per-search rates and unknown total, end the reply, and wait for explicit user consent before enabling it. Approval of a task without search does not authorize adding search; changed search settings require a fresh estimate and approval.',
70
70
  '- When search_charges is returned, disclose each enabled search type and its per-search rate before generation approval, even when the user requested search. A zero-search subtotal excludes unknown search fees; one task may search multiple times or not at all. Expected counts are assumptions, not execution limits. Actual counts depend on the task and model strategy. Do not add a search-fee warning when search is off.',
71
- '- For a token_billed estimate, show the reference price in credits and approximate USD and say "参考价 {积分}(约 {美元}),按实际 token 用量结算,完成后多退少补,实际可能更低或略高" / "Reference price {credits} (about {USD}); billed by actual token usage and settled when the task finishes, so the final charge may be lower or slightly higher." When size is auto (except a GIF, whose frames have a fixed size), add that setting a size gives a closer reference price. For a Gemini Omni video with an input or reference video, pass its length as media_seconds; the reference counts that video at the highest resolution (4k), so also show the lower-resolution price the estimate gives. If an estimate still needs token usage, say "按实际 token 用量计费,生成前无法确定总价" / "Billed by actual token usage; the total is unknown before generation." and include the applicable published unit rates when returned. If no price is available, say so rather than assuming token billing.',
71
+ '- For a token_billed estimate, show the reference price in credits and approximate USD and say "参考价 {积分}(约 {美元}),按实际 token 用量结算,完成后多退少补,实际可能更低或略高" / "Reference price {credits} (about {USD}); billed by actual token usage and settled when the task finishes, so the final charge may be lower or slightly higher." When size is auto (except a GIF, whose frames have a fixed size), add that setting a size gives a closer reference price. For a Gemini Omni video with an input or reference video, pass its length as media_seconds; the reference counts that video at the highest resolution (4k), so also show the price the estimate lists for each input resolution. If an estimate still needs token usage, say "按实际 token 用量计费,生成前无法确定总价" / "Billed by actual token usage; the total is unknown before generation." and include the applicable published unit rates when returned. If no price is available, say so rather than assuming token billing.',
72
72
  '- If the user set a fixed cap that cannot be checked, explain that gap and replace the usual closing with an explicit question about proceeding without that cap. Do not treat a generic "Confirm generation" as consent to remove or raise a cap.',
73
73
  '- The suggested confirmation phrase is not a required command; any clear approval of the quoted task is valid. Existing task or batch approval still follows the spending approval rules; do not ask again when it already covers this request.',
74
74
  '- Keep routine explanations about the task and cost, for example "这次生成需要确认费用" / "Please confirm the cost for this generation." Do not add skill paths, filenames or quoted internal rules to routine confirmations unless the user asks or higher-priority host instructions require them.',
@@ -7,8 +7,9 @@ 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
+ import { qwenTTSInput } from '../services/qwen-tts-tokens.js';
12
13
  import { prepareSeedanceInput } from '../services/seedance-input.js';
13
14
  import { API_KEYS_URL, MCP_CONSOLE_URL, MCP_KEY_NAME, TOP_UP_URL } from '../services/http-policy.js';
14
15
  import { trackedLink } from '../services/utm.js';
@@ -49,7 +50,7 @@ export function registerEstimateCost(server, config) {
49
50
  }
50
51
  if (inputs !== undefined)
51
52
  return await estimateBatch(config, entry, inputs, { mediaSeconds, pricingParameters, pricingSource });
52
- const prepared = prepareSeedanceInput(entry, input ?? {});
53
+ const prepared = prepareSeedanceInput(entry, qwenTTSInput(entry.id, input ?? {}));
53
54
  const values = prepared.input;
54
55
  const validation = entry.spec ? validateInput(entry.spec, values) : undefined;
55
56
  validation?.errors.push(...prepared.errors);
@@ -142,7 +143,7 @@ export function registerEstimateCost(server, config) {
142
143
  });
143
144
  if (error instanceof QuoteError)
144
145
  return failure(`${error.message} Nothing was submitted or charged.`, {
145
- error: { category: 'estimate_unavailable', code: error.code, ...(error.param ? { param: error.param } : {}) },
146
+ error: { category: 'estimate_unavailable', ...quoteErrorFields(error) },
146
147
  pricing_source: pricingSource, submission_allowed: false, final_budget_enforced: false, charged: 'no', ...(inputs ? { batch: { items: inputs.length } } : {})
147
148
  });
148
149
  const failed = errorResult(error);
@@ -228,7 +229,7 @@ function itemPrice(estimate) {
228
229
  */
229
230
  async function estimateBatch(config, entry, inputs, options) {
230
231
  const batch = { items: inputs.length };
231
- const prepared = inputs.map(item => prepareSeedanceInput(entry, item));
232
+ const prepared = inputs.map(item => prepareSeedanceInput(entry, qwenTTSInput(entry.id, item)));
232
233
  const checks = prepared.map(item => {
233
234
  if (!entry.spec)
234
235
  return undefined;
@@ -253,7 +254,7 @@ async function estimateBatch(config, entry, inputs, options) {
253
254
  return calculateRulesEstimate(body, entry, item.input, { mediaSeconds: options.mediaSeconds, pricingParameters: options.pricingParameters });
254
255
  }
255
256
  catch (error) {
256
- throw error instanceof QuoteError ? new QuoteError(error.code, `inputs[${index}]: ${error.message}`, error.param) : error;
257
+ throw error instanceof QuoteError ? quoteErrorAt(error, index) : error;
257
258
  }
258
259
  });
259
260
  const total = batchTotal(entry.id, results), combined = total.estimate, status = total.status;
@@ -6,10 +6,11 @@ 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';
13
+ import { isQwenTTSModel, qwenTTSInput } from '../services/qwen-tts-tokens.js';
13
14
  import { CLIENT_REQUEST_ID_PATTERN, monotonicNow, newRunId, remainingMs } from '../services/http-policy.js';
14
15
  import { formatUsd } from '../services/error-handler.js';
15
16
  import { DASHBOARD_CHECK_GUIDANCE, MEDIA_SECONDS_DESCRIPTION, MEDIA_SECONDS_MAX, PAID, dashboardCheck, errorResult, failure, money, ok, progressReporter, retryText, usdOf } from './shared.js';
@@ -58,26 +59,29 @@ function inputSchema(kind) {
58
59
  .describe('Model parameters exactly as listed by get_model, e.g. {"prompt":"…","quality":"1080p"}. Do not put model or callback_url here.'),
59
60
  // The leading max() lets zod stop at an oversized array instead of checking every element.
60
61
  inputs: z.array(z.record(z.string(), z.unknown())).max(MAX_BATCH_ITEMS).min(1).optional()
61
- .describe(`Several tasks of this model at once (1–${MAX_BATCH_ITEMS}), each item like input. One pricing_quote from estimate_cost with the same inputs, in the same order, approves the whole batch; every item is submitted right away (up to ${BATCH_SUBMIT_CONCURRENCY} at a time) and the result lists each item's task_id or error. Collect the results with list_tasks (task_ids). To finish a batch, call again with the same client_request_id and exactly the same inputs within 24 hours: the items the result lists to finish (not submitted, or refused and since fixed) are then submitted, and accepted items return their original tasks without a new charge. Never resubmit accepted, not-submitted or unknown-outcome items under a new client_request_id: that creates and charges new tasks. media_seconds and pricing_parameters apply to every item. Pass input or inputs, not both.`),
62
+ .describe(`Several tasks of this model at once (1–${MAX_BATCH_ITEMS}), each item like input. One pricing_quote from estimate_cost with the same inputs, in the same order, approves the whole batch; every item is submitted right away (up to ${BATCH_SUBMIT_CONCURRENCY} at a time) and the result lists each item's task_id or error. Collect the results with list_tasks (task_ids). To finish a batch, call again with the same client_request_id and exactly the same inputs within 24 hours of its first submission: the items the result lists to finish (not submitted, or refused and since fixed) are then submitted, and accepted items return their original tasks without a new charge. Within those 24 hours, never resubmit accepted, not-submitted or unknown-outcome items under a new client_request_id: that creates and charges new tasks. Past them, check list_tasks and submit only the items that did not go through, as a new batch with a new client_request_id. media_seconds and pricing_parameters apply to every item. Pass input or inputs, not both.`),
62
63
  client_request_id: z.string().regex(CLIENT_REQUEST_ID_PATTERN).optional()
63
- .describe(`Optional idempotency key (16–96 characters: letters, digits, . _ -; with inputs at most ${BATCH_REQUEST_ID_MAX}, since each item adds .NN). Reuse the same value only to retry the same request after a network error or timeout, or to finish a batch with exactly the same inputs.`),
64
+ .describe(`Optional idempotency key (16–96 characters: letters, digits, . _ -; with inputs at most ${BATCH_REQUEST_ID_MAX}, since each item adds .NN). Reuse the same value only to retry the same request after a network error or timeout, or to finish a batch with exactly the same inputs, within 24 hours of the first submission.`),
64
65
  max_cost_usd: z.number().positive().max(10_000).optional()
65
66
  .describe(`Compatibility option for a budget explicitly specified by the user. Compare the submission estimate against that budget; never derive this value from the estimate. This does not limit the final charge. Refuses when the estimate is incomplete or exceeds the budget; a token-billed reference price must fit ${REFERENCE_BUDGET_FACTOR} times over. With inputs it applies to the batch total.`),
66
67
  account_quote: ApprovedAccountQuote.optional().describe('Legacy approval. Refresh with estimate_cost and obtain user approval before using the new pricing rules.'),
67
- pricing_quote: ApprovedRulesEstimate.optional().describe('Client approval record from estimate_cost, for exactly this input (or these inputs). Rechecked against fresh pricing rules before submission; past its expires_at it still applies while the input and price are unchanged. Does not bind final settlement.'),
68
+ pricing_quote: ApprovedRulesEstimate.optional().describe('Client approval record from estimate_cost, for exactly this input (or these inputs), valid until its expires_at (24 hours from the estimate). Rechecked against fresh pricing rules before submission: refused if the input changed, the price rose or it expired; an unchanged or lower price submits. Does not bind final settlement.'),
68
69
  pricing_parameters: QuoteParameters.optional().describe('The same explicit billing usage passed to estimate_cost.'),
69
70
  media_seconds: z.number().positive().max(MEDIA_SECONDS_MAX).optional().describe(MEDIA_SECONDS_DESCRIPTION),
70
71
  wait_seconds: z.number().int().min(0).max(MAX_WAIT_SECONDS).optional()
71
72
  .describe(`Seconds to wait for the result after submitting, 0–${MAX_WAIT_SECONDS} (default ${WAIT_MS[kind] / 1000}; with inputs only 0). 0 returns the task_id right after submission: use it when submitting several tasks, then collect them with list_tasks.`),
72
- skip_estimate: z.boolean().optional().describe('Only when the user has explicitly said not to estimate or not to confirm (for example "generate directly", "no need to estimate", "from now on just generate"); never on your own initiative. Submits without an approved estimate, also when the price cannot be computed or a pricing_quote changed, and says so in the result; the task is charged by actual usage. Invalid input and an explicit max_cost_usd are still checked.'),
73
+ skip_estimate: z.boolean().optional().describe('Only when the user has explicitly said not to estimate or not to confirm (for example "generate directly", "no need to estimate", "from now on just generate"); never on your own initiative. Submits without an approved estimate, also when the price cannot be computed or a pricing_quote changed or expired, and says so in the result; the task is charged by actual usage. Invalid input and an explicit max_cost_usd are still checked.'),
73
74
  };
74
75
  }
75
76
  const argsSchema = (kind) => z.object(inputSchema(kind));
76
- /** What lowers a reference price: GPT Image's output settings, or a Gemini Omni video's resolution, length and media. */
77
- const lowerReference = (model) => isOmniTokenModel(model) ? 'quality, duration, images or input videos' : 'size, quality, count or reference images';
77
+ /** What lowers a reference price: GPT Image's output settings, a Gemini Omni video's resolution, length and media, or a Qwen TTS text. */
78
+ const lowerReference = (model) => isOmniTokenModel(model) ? 'quality, duration, images or input videos'
79
+ : isQwenTTSModel(model) ? 'length of the text' : 'size, quality, count or reference images';
78
80
  function rangeText(estimate) {
79
81
  return formatEstimateRange(estimate) ?? 'unknown';
80
82
  }
83
+ /** A pricing_quote refused for its input, its price or its age: skip_estimate submits anyway and says why. */
84
+ const QUOTE_REFUSALS = new Set(['quote_input_changed', 'price_changed', 'quote_expired']);
81
85
  /**
82
86
  * Why the price could not be computed, when skip_estimate may set that aside: rules that are missing, unreadable or
83
87
  * limited, or usage known only once the task runs. Input problems and a cancelled call are never set aside.
@@ -105,7 +109,7 @@ function unpriced(error) {
105
109
  return undefined;
106
110
  }
107
111
  /**
108
- * A pricing_quote that no longer matches, set aside by skip_estimate: the result names the approved and the current
112
+ * A pricing_quote that no longer applies, set aside by skip_estimate: the result names the approved and the current
109
113
  * price (`now`, undefined when no total can be computed before the task runs).
110
114
  */
111
115
  function changedApproval(error, approval, now, batch = false) {
@@ -113,7 +117,12 @@ function changedApproval(error, approval, now, batch = false) {
113
117
  return { reason: 'quote_input_changed', why: batch ? `the pricing_quote was for different inputs${now ? `; the estimate of these inputs is ${now}` : ''}`
114
118
  : `the pricing_quote was for a different input${now ? `; this input's estimate is ${now}` : ''}` };
115
119
  }
116
- return { reason: 'price_changed', why: `the price changed after it was approved (approved ${money(Number(amountsForUC(approval.total_uc).credits))}, now ${now ?? 'not computable before the task runs'})`,
120
+ const approved = money(Number(amountsForUC(approval.total_uc).credits));
121
+ if (error.code === 'quote_expired') {
122
+ return { reason: 'quote_expired', why: `the pricing_quote expired at ${approval.expires_at} (approved ${approved}, now ${now ?? 'not computable before the task runs'})`,
123
+ approved: approval.total_uc };
124
+ }
125
+ return { reason: 'price_changed', why: `the price rose after it was approved (approved ${approved}, now ${now ?? 'not computable before the task runs'})`,
117
126
  approved: approval.total_uc };
118
127
  }
119
128
  /** Why max_cost_usd could not be checked, and what the assistant can do next. */
@@ -163,7 +172,7 @@ async function generationModel(config, kind, model) {
163
172
  }
164
173
  /** An input as generate_* submits it, with the problems that stop it and the warnings it carries. */
165
174
  function checkGenerationInput(entry, input) {
166
- const prepared = prepareSeedanceInput(entry, input);
175
+ const prepared = prepareSeedanceInput(entry, qwenTTSInput(entry.id, input));
167
176
  const errors = [], warnings = [];
168
177
  if (entry.spec) {
169
178
  const validation = validateInput(entry.spec, prepared.input);
@@ -245,10 +254,9 @@ function registerGenerate(server, config, kind) {
245
254
  if (!skipped)
246
255
  throw error;
247
256
  }
248
- let approvalExpired = false;
249
257
  if (args.pricing_quote && rulesEstimate) {
250
258
  try {
251
- approvalExpired = checkRulesApproval(args.pricing_quote, rulesEstimate).expired;
259
+ checkRulesApproval(args.pricing_quote, rulesEstimate);
252
260
  }
253
261
  catch (error) {
254
262
  if (!skip || !(error instanceof QuoteError))
@@ -349,15 +357,13 @@ function registerGenerate(server, config, kind) {
349
357
  if (estimateSkipped) {
350
358
  if (!skipped)
351
359
  lines.push('Submitted at the user\'s request without an approved estimate (skip_estimate).');
352
- else if (skipped.reason === 'price_changed' || skipped.reason === 'quote_input_changed')
360
+ else if (QUOTE_REFUSALS.has(skipped.reason))
353
361
  lines.push(`Submitted at the user's request (skip_estimate) although ${skipped.why}.`);
354
362
  else
355
363
  lines.push(`Price check skipped at the user's request (skip_estimate): ${skipped.why}. The task is charged by actual usage.`);
356
364
  if (!(typeof reserved === 'number' && reserved > 0) && task.status !== 'completed')
357
365
  lines.push('get_task shows the charge when the task finishes.');
358
366
  }
359
- if (approvalExpired)
360
- lines.push(`The approved estimate expired at ${args.pricing_quote.expires_at}, but the input and price are unchanged, so it was submitted under that approval.`);
361
367
  if (estimate?.status === 'estimated')
362
368
  lines.push(`Estimate before submitting: ${rangeText(estimate)}`);
363
369
  if (reference && estimate)
@@ -394,7 +400,6 @@ function registerGenerate(server, config, kind) {
394
400
  client_request_id: clientRequestId,
395
401
  submission_state: 'accepted',
396
402
  replayed: submitted.idempotency_replayed === true,
397
- ...(approvalExpired ? { approval_expired: true } : {}),
398
403
  ...(estimateSkipped ? { estimate_skipped: true, estimate_skip_reason: skipped?.reason ?? 'none' } : {}),
399
404
  ...(skipped?.approved ? { approved_amounts: amountsForUC(skipped.approved) } : {}),
400
405
  ...(typeof reserved === 'number' ? { reserved_credits: reserved, reserved_usd: usdOf(reserved) } : {}),
@@ -415,7 +420,7 @@ function registerGenerate(server, config, kind) {
415
420
  charged: 'no', submission_state: 'not_submitted'
416
421
  });
417
422
  if (error instanceof QuoteError)
418
- return failure(`${error.message} Nothing was submitted or charged.`, { error: { category: 'estimate_unavailable', code: error.code }, charged: 'no', submission_state: 'not_submitted' });
423
+ return failure(`${error.message} Nothing was submitted or charged.`, { error: { category: 'estimate_unavailable', ...quoteErrorFields(error) }, charged: 'no', submission_state: 'not_submitted' });
419
424
  // clientRequestId is set right before the submit, so it also tells whether a request may have gone out.
420
425
  return errorResult(error, { paid: clientRequestId !== undefined, clientRequestId, taskId: acceptedTaskId,
421
426
  phase: acceptedTaskId ? 'accepted' : clientRequestId ? 'submit_started' : 'before_submit' });
@@ -522,16 +527,15 @@ async function generateBatch(config, kind, args, extra, startedMono) {
522
527
  catch (error) {
523
528
  itemSkipped[index] = skipEstimate ? unpriced(error) : undefined;
524
529
  if (!itemSkipped[index])
525
- throw error instanceof QuoteError ? new QuoteError(error.code, `inputs[${index}]: ${error.message}`, error.param) : error;
530
+ throw error instanceof QuoteError ? quoteErrorAt(error, index) : error;
526
531
  return undefined;
527
532
  }
528
533
  }) : [];
529
534
  const estimates = rules && priced.every(item => item !== undefined) ? priced : undefined;
530
535
  const total = estimates ? batchTotal(entry.id, estimates) : undefined;
531
- let expiredApproval = false;
532
536
  if (args.pricing_quote && total) {
533
537
  try {
534
- expiredApproval = checkBatchApproval(args.pricing_quote, total.approval).expired;
538
+ checkBatchApproval(args.pricing_quote, total.approval);
535
539
  }
536
540
  catch (error) {
537
541
  if (!skipEstimate || !(error instanceof QuoteError))
@@ -615,7 +619,7 @@ async function generateBatch(config, kind, args, extra, startedMono) {
615
619
  if (skippedBatch) {
616
620
  if (!batchSkipped && !someItemsSkipped)
617
621
  lines.push('Submitted at the user\'s request without an approved estimate (skip_estimate).');
618
- else if (batchSkipped?.reason === 'price_changed' || batchSkipped?.reason === 'quote_input_changed')
622
+ else if (batchSkipped && QUOTE_REFUSALS.has(batchSkipped.reason))
619
623
  lines.push(`Submitted at the user's request (skip_estimate) although ${batchSkipped.why}.`);
620
624
  else if (batchSkipped)
621
625
  lines.push(`Price check skipped at the user's request (skip_estimate): ${batchSkipped.why}. The tasks are charged by actual usage.`);
@@ -625,8 +629,6 @@ async function generateBatch(config, kind, args, extra, startedMono) {
625
629
  if (accepted.some(report => !report.reserved))
626
630
  lines.push('list_tasks or get_task shows each charge when its task finishes.');
627
631
  }
628
- if (expiredApproval)
629
- lines.push(`The approved estimate expired at ${args.pricing_quote.expires_at}, but the inputs and price are unchanged, so the batch was submitted under that approval.`);
630
632
  if (total?.status === 'estimated')
631
633
  lines.push(`Estimate before submitting: ${rangeText(total.estimate)} for ${count} input${count === 1 ? '' : 's'}.`);
632
634
  if (tokenBilled && total)
@@ -649,7 +651,7 @@ async function generateBatch(config, kind, args, extra, startedMono) {
649
651
  lines.push(`Collect the results with list_tasks (task_ids: ${taskIds.join(', ')}); it is free and read-only.`);
650
652
  if (finishing.length) {
651
653
  const fixFirst = reports.some(report => report.finishable && report.state === 'rejected');
652
- lines.push(`To finish the batch, call ${name} again with client_request_id "${batchId}" and exactly the same inputs within 24 hours${fixFirst ? ', after fixing what the refused inputs need' : ''}: ${itemList(finishing)} will then be submitted, and accepted items return their original tasks without a new charge.`);
654
+ lines.push(`To finish the batch, call ${name} again with client_request_id "${batchId}" and exactly the same inputs within 24 hours of its first submission${fixFirst ? ', after fixing what the refused inputs need' : ''}: ${itemList(finishing)} will then be submitted, and accepted items return their original tasks without a new charge.`);
653
655
  }
654
656
  if (unknown.length)
655
657
  lines.push(`The outcome of ${itemList(unknown)} is unknown: retry later with the same client_request_id and inputs, or check list_tasks.`);
@@ -679,7 +681,6 @@ async function generateBatch(config, kind, args, extra, startedMono) {
679
681
  client_request_id: batchId,
680
682
  submission_state: accepted.length === count ? 'accepted' : accepted.length ? 'partial'
681
683
  : counts.outcome_unknown ? 'outcome_unknown' : counts.rejected ? 'rejected' : 'not_submitted',
682
- ...(expiredApproval ? { approval_expired: true } : {}),
683
684
  ...(skippedBatch ? { estimate_skipped: true, estimate_skip_reason: skipReasons } : {}),
684
685
  ...(batchSkipped?.approved ? { approved_amounts: amountsForUC(batchSkipped.approved) } : {}),
685
686
  ...(heldCredits > 0 ? { reserved_credits: heldCredits, reserved_usd: usdOf(heldCredits) } : {}),
@@ -706,7 +707,7 @@ async function generateBatch(config, kind, args, extra, startedMono) {
706
707
  });
707
708
  if (error instanceof QuoteError)
708
709
  return failure(`${error.message} Nothing was submitted or charged.`, {
709
- error: { category: 'estimate_unavailable', code: error.code }, charged: 'no', submission_state: 'not_submitted', batch
710
+ error: { category: 'estimate_unavailable', ...quoteErrorFields(error) }, charged: 'no', submission_state: 'not_submitted', batch
710
711
  });
711
712
  // Each submission reports its own outcome, so an error here came before any item was submitted.
712
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.0';
4
+ export const MCP_VERSION = '1.12.2';