@evolinkai/cli 0.13.0 → 0.14.1

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.
Files changed (29) hide show
  1. package/README.md +22 -7
  2. package/package.json +1 -1
  3. package/skills/evolink-cli/SKILL.md +21 -7
  4. package/skills/evolink-cli/references/capabilities.md +1 -1
  5. package/skills/evolink-cli/references/media-workflows.md +1 -1
  6. package/skills/evolink-cli/references/usage-and-budget.md +5 -3
  7. package/src/cli.mjs +76 -21
  8. package/src/help.mjs +12 -5
  9. package/src/media.mjs +185 -36
  10. package/src/platform/core/src/data/model-constraints.js +8 -5
  11. package/src/platform/core/src/data/model-params.overrides.generated.js +1 -1
  12. package/src/platform/core/src/services/api-client.js +1 -1
  13. package/src/platform/core/src/services/batch-generation.js +117 -0
  14. package/src/platform/core/src/services/gpt-image-tokens.js +264 -0
  15. package/src/platform/core/src/services/omni-tokens.js +258 -0
  16. package/src/platform/core/src/services/param-validator.js +48 -1
  17. package/src/platform/core/src/services/pricing-call-limit.js +4 -4
  18. package/src/platform/core/src/services/pricing-derived.js +3 -3
  19. package/src/platform/core/src/services/pricing-rules-client.js +23 -5
  20. package/src/platform/core/src/services/pricing-rules-estimate.js +320 -70
  21. package/src/platform/core/src/services/qwen-tts-tokens.js +187 -0
  22. package/src/platform/core/src/tool-guidance.js +25 -2
  23. package/src/platform/core/src/tools/estimate-cost.js +203 -61
  24. package/src/platform/core/src/tools/generate.js +498 -75
  25. package/src/platform/core/src/tools/get-model.js +15 -3
  26. package/src/platform/core/src/tools/get-pricing-rules.js +4 -3
  27. package/src/platform/core/src/tools/shared.js +1 -1
  28. package/src/platform/core/src/version.js +1 -1
  29. package/src/platform/source.json +43 -35
@@ -0,0 +1,187 @@
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) { throw new QuoteError('invalid_quote_parameter', message, param); }
54
+ /** A string as the gateway decodes it from the request JSON: an unpaired surrogate becomes U+FFFD. */
55
+ const decoded = (text) => text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, '\uFFFD');
56
+ function textParam(input, param) {
57
+ const value = input[param];
58
+ if (value === undefined || value === null)
59
+ return '';
60
+ return typeof value === 'string' ? decoded(value) : invalid(param, `${param} must be a string.`);
61
+ }
62
+ const characters = (text) => [...text].length;
63
+ /** strings.TrimSpace(text) == "": only the characters unicode.IsSpace accepts. */
64
+ const blank = (text) => /^[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]*$/u.test(text);
65
+ /** CountBillingChars: a Han character counts two, any other one. */
66
+ const billingCharacters = (text) => { let count = 0; for (const character of text)
67
+ count += HAN.test(character) ? 2 : 1; return count; };
68
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
69
+ /** sort.Strings: by UTF-8 bytes, which is code point order. */
70
+ function byCodePoint(a, b) {
71
+ const x = [...a], y = [...b];
72
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
73
+ const difference = x[i].codePointAt(0) - y[i].codePointAt(0);
74
+ if (difference)
75
+ return difference;
76
+ }
77
+ return x.length - y.length;
78
+ }
79
+ /** validateQwenAudioTTSHotFix: {pronunciation?, replace?}, each a non-empty list of {"word": "value"} objects. */
80
+ 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.');
82
+ if (!isObject(hotFix) || !Object.keys(hotFix).length)
83
+ shape();
84
+ let entries = 0;
85
+ for (const [list, items] of Object.entries(hotFix)) {
86
+ if (!HOT_FIX_LISTS.has(list) || !Array.isArray(items) || !items.length)
87
+ shape();
88
+ for (const item of items) {
89
+ if (!isObject(item) || !Object.keys(item).length)
90
+ shape();
91
+ for (const [word, value] of Object.entries(item)) {
92
+ if (typeof value !== 'string' || word === '' || value === '')
93
+ shape();
94
+ entries++;
95
+ }
96
+ }
97
+ }
98
+ 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}.`);
100
+ }
101
+ /**
102
+ * QwenAudioTTSEffectiveText: the text after hot_fix.replace, item by item and each item's words in code point order,
103
+ * and its length. A replacement that would make the text longer than max is not made (ok false, with that length).
104
+ */
105
+ export function qwenEffectiveText(text, hotFix, max = QWEN_TTS_MAX_TEXT) {
106
+ let length = characters(text);
107
+ if (!isObject(hotFix))
108
+ return { text, characters: length, ok: length <= max };
109
+ if (length > max)
110
+ return { text, characters: length, ok: false };
111
+ for (const item of Array.isArray(hotFix.replace) ? hotFix.replace : []) {
112
+ const pair = isObject(item) ? item : {};
113
+ for (const word of Object.keys(pair).sort((a, b) => byCodePoint(decoded(a), decoded(b)))) {
114
+ const target = pair[word];
115
+ if (typeof target !== 'string' || word === '')
116
+ continue;
117
+ const from = decoded(word), to = decoded(target);
118
+ const hits = text.split(from).length - 1;
119
+ if (!hits)
120
+ continue;
121
+ const projected = length + hits * (characters(to) - characters(from));
122
+ if (projected > max)
123
+ return { text, characters: projected, ok: false };
124
+ text = text.split(from).join(to);
125
+ length = projected;
126
+ }
127
+ }
128
+ return { text, characters: length, ok: true };
129
+ }
130
+ /** Characters of json.Marshal(value): Go escapes <, > and & (HTML), U+2028 and U+2029, and control characters. */
131
+ export function goJSONCharacters(value) {
132
+ if (typeof value === 'string') {
133
+ let count = 2;
134
+ for (const character of decoded(value)) {
135
+ const code = character.codePointAt(0);
136
+ count += character === '"' || character === '\\' || '\b\f\n\r\t'.includes(character) ? 2
137
+ : code < 0x20 || character === '<' || character === '>' || character === '&' || code === 0x2028 || code === 0x2029 ? 6 : 1;
138
+ }
139
+ return count;
140
+ }
141
+ if (Array.isArray(value))
142
+ return 2 + value.reduce((sum, item, i) => sum + (i ? 1 : 0) + goJSONCharacters(item), 0);
143
+ if (isObject(value))
144
+ return 2 + Object.entries(value).reduce((sum, [key, item], i) => sum + (i ? 1 : 0) + goJSONCharacters(key) + 1 + goJSONCharacters(item), 0);
145
+ if (value === null)
146
+ return 4;
147
+ if (typeof value === 'boolean')
148
+ return value ? 4 : 5;
149
+ // 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.');
151
+ }
152
+ /**
153
+ * The tokens the gateway reserves at submission for this input. The text is prompt, or input when prompt is empty;
154
+ * the checks are the gateway's own before it reserves, which the documented parameters do not all cover.
155
+ */
156
+ export function qwenTTSReservation(input) {
157
+ const prompt = textParam(input, 'prompt'), alias = textParam(input, 'input');
158
+ if (prompt !== '' && alias !== '' && prompt !== alias)
159
+ invalid('input', 'prompt and input differ; send only one.');
160
+ const text = prompt !== '' ? prompt : alias;
161
+ if (blank(text))
162
+ invalid('prompt', 'prompt is required.');
163
+ if (characters(text) > QWEN_TTS_MAX_TEXT)
164
+ invalid('prompt', `prompt must be at most ${QWEN_TTS_MAX_TEXT} characters, got ${characters(text)}.`);
165
+ const instruction = textParam(input, 'instruction');
166
+ const billed = billingCharacters(instruction);
167
+ if (billed > MAX_INSTRUCTION)
168
+ invalid('instruction', `instruction must be at most ${MAX_INSTRUCTION} billing characters (Han characters count as 2), got ${billed}.`);
169
+ const hotFix = input.hot_fix === null ? undefined : input.hot_fix;
170
+ if (hotFix !== undefined)
171
+ checkHotFix(hotFix);
172
+ const effective = qwenEffectiveText(text, hotFix);
173
+ 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}.`);
175
+ const hotFixCharacters = hotFix === undefined ? 0 : goJSONCharacters(hotFix);
176
+ const expressive = instruction !== '' || effective.text.includes('[');
177
+ const classes = { han: 0, caseless: 0, lower: 0, punctuation: 0, other: 0 };
178
+ let inputTokens = BASE_INPUT_TOKENS + hotFixCharacters * 3, halves = BASE_OUTPUT_TOKENS * 2;
179
+ for (const character of effective.text) {
180
+ const kind = qwenCharacterClass(character);
181
+ classes[kind]++;
182
+ inputTokens += INPUT_TOKENS[kind];
183
+ halves += OUTPUT_HALVES[kind][expressive ? 1 : 0];
184
+ }
185
+ return { tokens: { input_tokens: inputTokens, output_tokens: Math.ceil(halves / 2) }, characters: effective.characters, classes,
186
+ hot_fix_characters: hotFixCharacters, expressive };
187
+ }
@@ -4,13 +4,35 @@
4
4
  export const PAID_GENERATION_GUIDANCE = [
5
5
  'Before each new paid generation, call estimate_cost with the exact model and input, then use the generation confirmation template in the server instructions.',
6
6
  'If the estimate is partial or unavailable, explain what is not covered or that the final cost is unknown.',
7
- 'End the reply and wait for the user to explicitly approve that quoted task before calling a generate tool.',
7
+ 'End the reply and wait for the user to explicitly approve that quoted task before calling a generate tool, unless the user opted out (skip_estimate).',
8
8
  'You may proceed under a prior explicit approval only when the user specified the task or batch scope and a spending budget that still covers this request; track the remaining budget.',
9
9
  'Your own suggested budget, a model recommendation, sufficient balance or a general request to generate is not spending approval.',
10
10
  'Show estimated cost and ask for approval. Do not derive max_cost_usd from a quote; compare only an explicit user budget, without promising a final charge.',
11
11
  'A new variation, regeneration or retry after a failed task is a new paid generation and needs approval unless that explicit batch approval covers it.',
12
12
  'Never remove or raise a user spending cap without their explicit approval.',
13
13
  ].join(' ');
14
+ /**
15
+ * When the user opts out of estimates. The server instructions carry it in full; a generate tool's description only
16
+ * points to skip_estimate, since each description must stay short.
17
+ */
18
+ export const ESTIMATE_OPT_OUT_GUIDANCE = [
19
+ 'Exception: when the user explicitly says not to estimate or not to confirm (for example "generate directly", "no need to estimate", "stop asking", "from now on just generate"), skip estimate_cost and the confirmation and pass skip_estimate: true, within the scope the user gave: this task, this batch, or every later generation in this conversation; if the scope is unclear, only this task. Never infer it from silence, the balance or your own suggestion.',
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
+ '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
+ '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 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
+ ].join(' ');
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
+ export const BATCH_GENERATION_GUIDANCE = [
27
+ 'For several images or tasks of one model, pass inputs (up to 50 items, each like input) to estimate_cost and then, with its pricing_quote, to the generate tool: one estimate, one approval for the batch total, and one call that submits every item at once and returns each task_id right away.',
28
+ 'For tasks of different models, submit one task per item with wait_seconds: 0.',
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
+ '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 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
+ 'For an item with an unknown outcome, retry later the same way or check list_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
+ '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
+ ].join(' ');
14
36
  /** Shared confirmation wording; approval and spending rules above still apply. */
15
37
  export const GENERATION_CONFIRMATION_GUIDANCE = [
16
38
  'When spending approval is needed, use the following layout in English by default unless the user explicitly requests another language. Fill it from the exact model and input checked by `estimate_cost`; summarize the content in one sentence. Render normal text and bullets; the code blocks below only illustrate the layout.',
@@ -43,9 +65,10 @@ export const GENERATION_CONFIRMATION_GUIDANCE = [
43
65
  '- For a complete estimate, show the returned amount or range in credits and approximate USD. Label it as an estimate, not a guaranteed final charge.',
44
66
  '- Do not add a separate estimated cap or max_cost_usd to the default confirmation. If the user specified a budget, state whether the estimate fits it; pause if it exceeds the budget. A budget comparison does not limit the final settlement.',
45
67
  '- For a partial estimate, label it "部分估价" / "Partial estimate", state what is excluded, and say it is neither the total nor an upper bound.',
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.',
46
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.',
47
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.',
48
- '- For token billing, say "按实际 token 用量计费,生成前无法确定总价" / "Billed by actual token usage; the total is unknown before generation." 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.',
49
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.',
50
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.',
51
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.',
@@ -2,12 +2,14 @@
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 { getCredits } from '../services/api-client.js';
5
+ import { MAX_BATCH_ITEMS, batchTotal } from '../services/batch-generation.js';
5
6
  import { resolveModel, suggestModels } from '../services/model-catalog.js';
6
7
  import { formatIssues, validateInput } from '../services/param-validator.js';
7
8
  import { formatEstimateRange } from '../services/pricing-client.js';
8
- import { PricingRulesError } from '../services/pricing-rules-client.js';
9
+ import { PricingRulesError, reusablePricingRules } from '../services/pricing-rules-client.js';
9
10
  import { QuoteError, QuoteParameters } from '../services/pricing-quote-client.js';
10
- import { createRulesEstimate } from '../services/pricing-rules-estimate.js';
11
+ import { calculateRulesEstimate, createRulesEstimate, readPricingRulesFor, recentRulesNote } from '../services/pricing-rules-estimate.js';
12
+ import { qwenTTSInput } from '../services/qwen-tts-tokens.js';
11
13
  import { prepareSeedanceInput } from '../services/seedance-input.js';
12
14
  import { API_KEYS_URL, MCP_CONSOLE_URL, MCP_KEY_NAME, TOP_UP_URL } from '../services/http-policy.js';
13
15
  import { trackedLink } from '../services/utm.js';
@@ -21,36 +23,43 @@ export function registerEstimateCost(server, config) {
21
23
  'Check a generation input and estimate what it will cost, without submitting anything. Free.',
22
24
  'Returns whether the input is valid, the expected price range in USD and credits, what it is based on, and whether the account balance and any spending limit (the EvoLink MCP limit, or this API key\'s) cover it.',
23
25
  'Call it before a paid generate_* call, then use the generation confirmation template in the server instructions.',
26
+ `For several tasks of one model, pass inputs (up to ${MAX_BATCH_ITEMS}): one total and one pricing_quote approve the whole batch.`,
24
27
  ].join(' '),
25
28
  inputSchema: {
26
29
  model: z.string().min(1).max(128).describe('Model ID, e.g. "seedance-2.0-text-to-video".'),
27
30
  input: z.record(z.string(), z.unknown()).optional()
28
31
  .describe('The input you plan to pass to the generate tool, e.g. {"prompt":"…","duration":5,"quality":"1080p"}.'),
32
+ // The leading max() lets zod stop at an oversized array instead of checking every element.
33
+ inputs: z.array(z.record(z.string(), z.unknown())).max(MAX_BATCH_ITEMS).min(1).optional()
34
+ .describe(`Several inputs for this model (1–${MAX_BATCH_ITEMS}), each as you will pass it in the generate tool's inputs, in the same order. Returns each input's estimate, the total and one pricing_quote that approves the whole batch. media_seconds and pricing_parameters apply to every input. Pass input or inputs, not both.`),
29
35
  pricing_source: z.enum(['pricing_rules', 'account', 'public_reference']).default('pricing_rules').describe('Use published full pricing rules for public default estimates. The old account/public_reference values are compatibility aliases; neither requests a backend account quote.'),
30
- pricing_parameters: QuoteParameters.optional().describe('Measured or explicitly expected usage declared by the pricing policy, such as input_seconds or search_count. Missing enabled-search counts produce a zero-search partial subtotal and per-search rates. Do not invent counts, include user_group/prices/prompts, or treat expected counts as execution limits.'),
36
+ pricing_parameters: QuoteParameters.optional().describe('Measured or explicitly expected usage declared by the pricing policy, such as input_seconds or search_count. Missing enabled-search counts produce a zero-search partial subtotal and per-search rates. GPT Image token models do not use token counts here: their reference price comes from the input. Do not invent counts, include user_group/prices/prompts, or treat expected counts as execution limits.'),
31
37
  media_seconds: z.number().positive().max(MEDIA_SECONDS_MAX).optional().describe(MEDIA_SECONDS_DESCRIPTION),
32
38
  },
33
39
  annotations: { title: 'Estimate cost', ...READ_ONLY },
34
- }, async ({ model, input, media_seconds: mediaSeconds, pricing_source: pricingSource, pricing_parameters: pricingParameters }) => {
35
- const over = pricingCallLimitReached('estimate_cost');
36
- if (over)
37
- return failure(`This account already made ${over.limit} estimate_cost calls in the last minute, the most allowed. Wait ${retryText(over.retryAfterSeconds)}, then estimate again. Nothing was submitted or charged.`, {
38
- error: { category: 'rate_limited', code: 'pricing_calls_per_minute', retry_after_seconds: over.retryAfterSeconds },
39
- pricing_source: pricingSource, submission_allowed: false, final_budget_enforced: false, charged: 'no'
40
- });
40
+ }, async ({ model, input, inputs, media_seconds: mediaSeconds, pricing_source: pricingSource, pricing_parameters: pricingParameters }) => {
41
41
  try {
42
+ if (inputs !== undefined && input !== undefined)
43
+ return failure('Pass input for one generation or inputs for a batch, not both. No estimate was created.', {
44
+ error: { category: 'invalid_request', param: 'inputs' }, charged: 'no', batch: { items: inputs.length }
45
+ });
42
46
  const { catalog, entry } = await resolveModel(model, config, { fresh: true, allowStale: false, skipPricing: true });
43
47
  if (!entry) {
44
48
  const suggestions = suggestModels(catalog, model);
45
49
  return failure(`Unknown model "${model}".${suggestions.length ? ` Did you mean: ${suggestions.join(', ')}?` : ''} Use search_models to find model IDs.`, { error: { category: 'not_found', param: 'model' }, suggestions });
46
50
  }
47
- const prepared = prepareSeedanceInput(entry, input ?? {});
51
+ if (inputs !== undefined)
52
+ return await estimateBatch(config, entry, inputs, { mediaSeconds, pricingParameters, pricingSource });
53
+ const prepared = prepareSeedanceInput(entry, qwenTTSInput(entry.id, input ?? {}));
48
54
  const values = prepared.input;
49
55
  const validation = entry.spec ? validateInput(entry.spec, values) : undefined;
50
56
  validation?.errors.push(...prepared.errors);
51
57
  validation?.warnings.push(...prepared.warnings);
52
58
  if (validation?.errors.length)
53
59
  return failure('The generation input is invalid; no estimate was created.', { input_valid: false, problems: validation.errors, error: { category: 'invalid_request' }, charged: 'no' });
60
+ const over = estimateLimitReached(config, entry);
61
+ if (over)
62
+ return limitFailure(over, pricingSource);
54
63
  const rulesEstimate = await createRulesEstimate(entry, values, { mediaSeconds, pricingParameters, reuseRules: config.reusePricingRules === true });
55
64
  const estimate = rulesEstimate.estimate;
56
65
  const lines = [`Estimate for ${entry.id} (${entry.kind}); nothing was submitted or charged.`];
@@ -72,6 +81,8 @@ export function registerEstimateCost(server, config) {
72
81
  lines.push(`Estimated cost: ${range}`);
73
82
  else if (estimate.status === 'partial' && range)
74
83
  lines.push(`Partial estimate at published rates: ${range} (not a total or an upper bound).`);
84
+ else if (estimate.status === 'token_billed' && range)
85
+ lines.push(`Reference price: ${range}. Billed by actual token usage and settled when the task finishes, so the final charge may be lower or slightly higher.`);
75
86
  else if (estimate.status === 'token_billed')
76
87
  lines.push('Cost: billed by tokens used; it is only known after the task runs.');
77
88
  else if (estimate.status === 'needs_input')
@@ -113,55 +124,11 @@ export function registerEstimateCost(server, config) {
113
124
  ...(prepared.applies ? { effective_input: values, defaults_applied: prepared.defaults,
114
125
  amount_scope: estimate.status === 'partial' ? 'known_components_subtotal' : estimate.status === 'estimated' ? 'expected_usage_estimate' : 'not_established' } : {}),
115
126
  };
116
- try {
117
- const credits = await getCredits(config, 'estimate_cost');
118
- const balance = Math.max(0, credits.user.remaining_credits);
119
- lines.push(`Account balance: ${money(balance)}`);
120
- structured.balance_credits = balance;
121
- if (estimate.status === 'estimated' && estimate.max_credits !== undefined) {
122
- const enough = balance >= estimate.max_credits;
123
- structured.enough_balance = enough;
124
- if (!enough)
125
- lines.push(`The account balance may not cover this; top up at ${trackedLink(TOP_UP_URL, 'top_up')}.`);
126
- }
127
- // The key's own limit is checked before the balance: warn now instead of failing on submit.
128
- if (!credits.token.unlimited_credits) {
129
- const signedIn = currentCredentialMode() === 'signed_in';
130
- const left = Math.max(0, credits.token.remaining_credits);
131
- lines.push(signedIn
132
- ? `EvoLink MCP limit left: ${money(left)} (shared by all connected assistants).`
133
- : `This API key's limit left: ${money(left)}.`);
134
- structured.limit_scope = signedIn ? 'mcp' : 'api_key';
135
- structured.limit_remaining_credits = left;
136
- if (estimate.status === 'estimated' && estimate.max_credits !== undefined) {
137
- const enoughLimit = left >= estimate.max_credits;
138
- structured.enough_limit = enoughLimit;
139
- if (!enoughLimit) {
140
- lines.push(signedIn
141
- ? `The EvoLink MCP limit may not cover this. It is a limit the user set, not the account balance; they can raise it at ${trackedLink(MCP_CONSOLE_URL, 'api_keys')} (the key named "${MCP_KEY_NAME}").`
142
- : `This API key's limit may not cover this; raise it at ${trackedLink(API_KEYS_URL, 'api_keys')} or use another key.`);
143
- }
144
- }
145
- }
146
- const daily = dailyLimitOf(credits.token);
147
- if (daily && estimate.status === 'estimated' && estimate.max_credits !== undefined) {
148
- const signedIn = currentCredentialMode() === 'signed_in';
149
- const enoughToday = daily.left >= estimate.max_credits;
150
- structured.daily_left_credits = daily.left;
151
- structured.enough_daily_limit = enoughToday;
152
- if (!enoughToday) {
153
- const resets = `it resets at midnight${daily.zone ? ` (${daily.zone})` : ''}`;
154
- lines.push(signedIn
155
- ? `Today's EvoLink MCP limit may not cover this (${money(daily.left)} left today; ${resets}). It is a limit the user set, not the account balance.`
156
- : `Today's limit of this API key may not cover this (${money(daily.left)} left today; ${resets}).`);
157
- }
158
- }
159
- }
160
- catch {
161
- lines.push('Balance: could not be read right now.');
162
- }
127
+ await addBalance(config, estimate, lines, structured);
163
128
  if (priced)
164
- lines.push(`Estimate valid until ${rulesEstimate.approval.expires_at}.`, 'Public default estimate; account discounts are not included. Confirm this estimated cost before generation. Final charges depend on actual usage.');
129
+ lines.push(`Estimate valid until ${rulesEstimate.approval.expires_at}.`, estimate.status === 'token_billed'
130
+ ? 'Public default reference price; account discounts are not included. Confirm it before generation. The final charge follows actual token usage.'
131
+ : 'Public default estimate; account discounts are not included. Confirm this estimated cost before generation. Final charges depend on actual usage.');
165
132
  else
166
133
  lines.push('No total or approval record was issued. Estimate again with the missing usage before asking the user to approve a generation.');
167
134
  return ok(lines.join('\n'), structured);
@@ -172,12 +139,12 @@ export function registerEstimateCost(server, config) {
172
139
  ? `The platform is limiting pricing requests right now, so no estimate was created. Try again in ${retryText(error.retryAfter)}. Nothing was submitted or charged.`
173
140
  : 'The model pricing rules could not be verified. No estimate or generation was created.', {
174
141
  error: { category: 'estimate_unavailable', code: error.code, status: error.status, ...(error.retryAfter !== undefined ? { retry_after_seconds: error.retryAfter } : {}) }, pricing_source: pricingSource,
175
- submission_allowed: false, final_budget_enforced: false, charged: 'no'
142
+ submission_allowed: false, final_budget_enforced: false, charged: 'no', ...(inputs ? { batch: { items: inputs.length } } : {})
176
143
  });
177
144
  if (error instanceof QuoteError)
178
145
  return failure(`${error.message} Nothing was submitted or charged.`, {
179
146
  error: { category: 'estimate_unavailable', code: error.code, ...(error.param ? { param: error.param } : {}) },
180
- pricing_source: pricingSource, submission_allowed: false, final_budget_enforced: false, charged: 'no'
147
+ pricing_source: pricingSource, submission_allowed: false, final_budget_enforced: false, charged: 'no', ...(inputs ? { batch: { items: inputs.length } } : {})
181
148
  });
182
149
  const failed = errorResult(error);
183
150
  return { ...failed, structuredContent: { ...failed.structuredContent, pricing_source: pricingSource,
@@ -185,3 +152,178 @@ export function registerEstimateCost(server, config) {
185
152
  }
186
153
  });
187
154
  }
155
+ /** Only an estimate that reads the platform's rules counts; one answered from rules read moments ago does not. */
156
+ function estimateLimitReached(config, entry) {
157
+ const reused = config.reusePricingRules === true && reusablePricingRules({ model: entry.id.toLowerCase(), view: 'full' });
158
+ const over = reused ? undefined : pricingCallLimitReached('estimate_cost');
159
+ return over;
160
+ }
161
+ function limitFailure(over, pricingSource) {
162
+ return failure(`This account already made ${over.limit} estimate_cost calls that read the pricing rules in the last minute, the most allowed. Wait ${retryText(over.retryAfterSeconds)}, then estimate again. Nothing was submitted or charged.`, {
163
+ error: { category: 'rate_limited', code: 'pricing_calls_per_minute', retry_after_seconds: over.retryAfterSeconds },
164
+ pricing_source: pricingSource, submission_allowed: false, final_budget_enforced: false, charged: 'no'
165
+ });
166
+ }
167
+ /** Whether the balance and the spending limits cover the estimate; a reference price is what the gateway reserves at submission. */
168
+ async function addBalance(config, estimate, lines, structured) {
169
+ const checkable = (estimate.status === 'estimated' || estimate.status === 'token_billed') && estimate.max_credits !== undefined;
170
+ try {
171
+ const credits = await getCredits(config, 'estimate_cost');
172
+ const balance = Math.max(0, credits.user.remaining_credits);
173
+ lines.push(`Account balance: ${money(balance)}`);
174
+ structured.balance_credits = balance;
175
+ if (checkable && estimate.max_credits !== undefined) {
176
+ const enough = balance >= estimate.max_credits;
177
+ structured.enough_balance = enough;
178
+ if (!enough)
179
+ lines.push(`The account balance may not cover this; top up at ${trackedLink(TOP_UP_URL, 'top_up')}.`);
180
+ }
181
+ // The key's own limit is checked before the balance: warn now instead of failing on submit.
182
+ if (!credits.token.unlimited_credits) {
183
+ const signedIn = currentCredentialMode() === 'signed_in';
184
+ const left = Math.max(0, credits.token.remaining_credits);
185
+ lines.push(signedIn
186
+ ? `EvoLink MCP limit left: ${money(left)} (shared by all connected assistants).`
187
+ : `This API key's limit left: ${money(left)}.`);
188
+ structured.limit_scope = signedIn ? 'mcp' : 'api_key';
189
+ structured.limit_remaining_credits = left;
190
+ if (checkable && estimate.max_credits !== undefined) {
191
+ const enoughLimit = left >= estimate.max_credits;
192
+ structured.enough_limit = enoughLimit;
193
+ if (!enoughLimit) {
194
+ lines.push(signedIn
195
+ ? `The EvoLink MCP limit may not cover this. It is a limit the user set, not the account balance; they can raise it at ${trackedLink(MCP_CONSOLE_URL, 'api_keys')} (the key named "${MCP_KEY_NAME}").`
196
+ : `This API key's limit may not cover this; raise it at ${trackedLink(API_KEYS_URL, 'api_keys')} or use another key.`);
197
+ }
198
+ }
199
+ }
200
+ const daily = dailyLimitOf(credits.token);
201
+ if (daily && checkable && estimate.max_credits !== undefined) {
202
+ const signedIn = currentCredentialMode() === 'signed_in';
203
+ const enoughToday = daily.left >= estimate.max_credits;
204
+ structured.daily_left_credits = daily.left;
205
+ structured.enough_daily_limit = enoughToday;
206
+ if (!enoughToday) {
207
+ const resets = `it resets at midnight${daily.zone ? ` (${daily.zone})` : ''}`;
208
+ lines.push(signedIn
209
+ ? `Today's EvoLink MCP limit may not cover this (${money(daily.left)} left today; ${resets}). It is a limit the user set, not the account balance.`
210
+ : `Today's limit of this API key may not cover this (${money(daily.left)} left today; ${resets}).`);
211
+ }
212
+ }
213
+ }
214
+ catch {
215
+ lines.push('Balance: could not be read right now.');
216
+ }
217
+ }
218
+ const itemsText = (indexes) => indexes.map(index => `inputs[${index}]`).join(', ');
219
+ /** One input's price, for the per-input list of a batch. */
220
+ function itemPrice(estimate) {
221
+ const range = formatEstimateRange(estimate);
222
+ if (estimate.status === 'needs_input' || !range)
223
+ return `no total yet (depends on ${(estimate.missing_usage ?? []).join(', ') || 'usage measured when it runs'})`;
224
+ return estimate.status === 'partial' ? `${range} partial` : estimate.status === 'token_billed' ? `${range} reference price` : range;
225
+ }
226
+ /**
227
+ * Several inputs for one model, estimated from one read of its rules and counted once against the account: each
228
+ * input's price, the total, and one approval record for the whole batch, in input order.
229
+ */
230
+ async function estimateBatch(config, entry, inputs, options) {
231
+ const batch = { items: inputs.length };
232
+ const prepared = inputs.map(item => prepareSeedanceInput(entry, qwenTTSInput(entry.id, item)));
233
+ const checks = prepared.map(item => {
234
+ if (!entry.spec)
235
+ return undefined;
236
+ const check = validateInput(entry.spec, item.input);
237
+ check.errors.push(...item.errors);
238
+ check.warnings.push(...item.warnings);
239
+ return check;
240
+ });
241
+ const located = (index, issues) => issues.map(issue => ({ ...issue, param: `inputs[${index}].${issue.param}` }));
242
+ const problems = checks.flatMap((check, index) => located(index, check?.errors ?? []));
243
+ if (problems.length)
244
+ return failure(['Some inputs are invalid; no estimate was created:', ...formatIssues(problems)].join('\n'), {
245
+ input_valid: false, problems, error: { category: 'invalid_request' }, charged: 'no', batch
246
+ });
247
+ const over = estimateLimitReached(config, entry);
248
+ if (over)
249
+ return limitFailure(over, options.pricingSource);
250
+ const reuse = config.reusePricingRules === true;
251
+ const { body, readAt } = await readPricingRulesFor(entry, { reuseRules: reuse });
252
+ const results = prepared.map((item, index) => {
253
+ try {
254
+ return calculateRulesEstimate(body, entry, item.input, { mediaSeconds: options.mediaSeconds, pricingParameters: options.pricingParameters });
255
+ }
256
+ catch (error) {
257
+ throw error instanceof QuoteError ? new QuoteError(error.code, `inputs[${index}]: ${error.message}`, error.param) : error;
258
+ }
259
+ });
260
+ const total = batchTotal(entry.id, results), combined = total.estimate, status = total.status;
261
+ if (readAt)
262
+ combined.notes.push(recentRulesNote(readAt));
263
+ const count = inputs.length;
264
+ const lines = [`Estimate for ${count} input${count === 1 ? '' : 's'} of ${entry.id} (${entry.kind}); nothing was submitted or charged.`];
265
+ lines.push(entry.spec ? 'Inputs look valid.' : 'Inputs not checked: this model\'s parameters are not documented here.');
266
+ const warnings = checks.flatMap((check, index) => located(index, check?.warnings ?? []));
267
+ if (warnings.length)
268
+ lines.push('Warnings:', ...formatIssues(warnings));
269
+ prepared.forEach((item, index) => {
270
+ for (const applied of item.defaults)
271
+ lines.push(`Applied default: inputs[${index}].${applied.param}=${applied.value} (${applied.reason}); this effective value is used for pricing and submission.`);
272
+ });
273
+ const prices = results.map(result => itemPrice(result.estimate));
274
+ const same = prices.every(price => price === prices[0]);
275
+ const each = same && count > 1 ? `; ${prices[0]} each` : '';
276
+ const range = formatEstimateRange(combined);
277
+ if (status === 'estimated' && range)
278
+ lines.push(`Estimated cost: ${range} in total for ${count} input${count === 1 ? '' : 's'}${each}.`);
279
+ else if (status === 'partial' && range)
280
+ lines.push(`Partial estimate at published rates: ${range} in total (not a total or an upper bound; partial for ${itemsText(total.partial)}).`);
281
+ else if (status === 'token_billed' && range)
282
+ lines.push(`Reference price: ${range} in total for ${count} input${count === 1 ? '' : 's'}${each}. Billed by actual token usage and settled when each task finishes, so the final charge may be lower or slightly higher.`);
283
+ else if (status === 'needs_input')
284
+ lines.push(`Cost: cannot estimate yet. ${itemsText(total.needsInput)} depend${total.needsInput.length === 1 ? 's' : ''} on usage this request does not give:`, ...(combined.usage_help ?? []).map(line => `- ${line}`));
285
+ if (!same)
286
+ lines.push('Per input:', ...prices.map((price, index) => `- inputs[${index}]: ${price}`));
287
+ if (combined.basis.length)
288
+ lines.push('Based on:', ...combined.basis.map(line => `- ${line}`));
289
+ if (combined.possible_extras.length)
290
+ lines.push('May also charge:', ...combined.possible_extras.map(line => `- ${line}`));
291
+ for (const note of combined.notes)
292
+ lines.push(`Note: ${note}`);
293
+ // Without a total for every input there is nothing to approve: no amounts and no approval record.
294
+ const quoted = status !== 'needs_input';
295
+ const rule = results[0].rule;
296
+ const structured = {
297
+ model: entry.id,
298
+ type: entry.kind,
299
+ batch,
300
+ pricing_scope: 'public_default',
301
+ pricing_source: 'pricing_rules',
302
+ ...(quoted ? { pricing_quote: total.approval, amounts: total.amounts } : { submission_allowed: false }),
303
+ total_known: status === 'estimated',
304
+ ...(combined.missing_usage ? { missing_usage: combined.missing_usage } : {}),
305
+ items: results.map((result, index) => ({ index, status: result.estimate.status, total_known: result.estimate.total_known === true,
306
+ ...(result.estimate.status === 'needs_input' ? {} : { amounts: result.amounts }),
307
+ ...(result.estimate.missing_usage ? { missing_usage: result.estimate.missing_usage } : {}),
308
+ ...(result.estimate.search_charges?.length ? { search_charges: result.estimate.search_charges } : {}),
309
+ ...(prepared[index].applies ? { effective_input: prepared[index].input, defaults_applied: prepared[index].defaults } : {}) })),
310
+ policy_version: rule.policy_version,
311
+ policy_checksum: rule.policy_checksum,
312
+ settlement_basis: rule.settlement_basis,
313
+ ...(quoted ? { expires_at: total.approval.expires_at } : {}),
314
+ ...(readAt ? { rules_read_at: readAt } : {}),
315
+ final_budget_enforced: false,
316
+ input_valid: entry.spec ? true : null,
317
+ problems: [],
318
+ warnings,
319
+ estimate: combined,
320
+ };
321
+ await addBalance(config, combined, lines, structured);
322
+ if (quoted)
323
+ lines.push(`Estimate valid until ${total.approval.expires_at}.`, status === 'token_billed'
324
+ ? `Public default reference price; account discounts are not included. Confirm it for the whole batch before generation. The final charge follows actual token usage.`
325
+ : `Public default estimate; account discounts are not included. Confirm this estimated cost for the whole batch before generation. Final charges depend on actual usage.`, `One approval covers all ${count} input${count === 1 ? '' : 's'}: pass this pricing_quote with the same inputs, in the same order, to generate_${entry.kind}.`);
326
+ else
327
+ lines.push('No total or approval record was issued. Estimate again with the missing usage before asking the user to approve a generation.');
328
+ return ok(lines.join('\n'), structured);
329
+ }