@evolinkai/cli 0.8.0 → 0.9.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.
Files changed (33) hide show
  1. package/README.md +57 -5
  2. package/package.json +1 -1
  3. package/skills/evolink-cli/SKILL.md +15 -3
  4. package/skills/evolink-cli/references/usage-and-budget.md +11 -1
  5. package/src/api.mjs +19 -2
  6. package/src/cli.mjs +32 -6
  7. package/src/errors.mjs +21 -13
  8. package/src/files.mjs +14 -2
  9. package/src/help.mjs +8 -2
  10. package/src/media.mjs +54 -15
  11. package/src/oauth.mjs +11 -3
  12. package/src/platform/core/src/config.js +7 -4
  13. package/src/platform/core/src/platform-client.js +9 -3
  14. package/src/platform/core/src/platform-operations.js +2 -0
  15. package/src/platform/core/src/services/api-client.js +61 -29
  16. package/src/platform/core/src/services/error-handler.js +89 -34
  17. package/src/platform/core/src/services/file-client.js +32 -0
  18. package/src/platform/core/src/services/http-policy.js +62 -12
  19. package/src/platform/core/src/services/model-catalog.js +13 -7
  20. package/src/platform/core/src/services/pricing-quote-client.js +239 -0
  21. package/src/platform/core/src/services/pricing-rules-client.js +222 -0
  22. package/src/platform/core/src/services/pricing-rules-estimate.js +231 -0
  23. package/src/platform/core/src/services/public-error.js +63 -0
  24. package/src/platform/core/src/tool-guidance.js +2 -0
  25. package/src/platform/core/src/tools/estimate-cost.js +36 -11
  26. package/src/platform/core/src/tools/generate.js +31 -7
  27. package/src/platform/core/src/tools/get-model.js +3 -1
  28. package/src/platform/core/src/tools/get-pricing-rules.js +54 -0
  29. package/src/platform/core/src/tools/shared.js +39 -19
  30. package/src/platform/core/src/tools/task-billing.js +31 -0
  31. package/src/platform/core/src/tools/task-format.js +31 -12
  32. package/src/platform/core/src/version.js +1 -1
  33. package/src/platform/source.json +47 -35
@@ -0,0 +1,231 @@
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 { z } from 'zod';
4
+ import { getPricingRules } from './pricing-rules-client.js';
5
+ import { QuoteError, prepareQuoteParameters, quoteRequestHash } from './pricing-quote-client.js';
6
+ function fail(code, message) { throw new QuoteError(code, message); }
7
+ function gcd(a, b) { while (b)
8
+ [a, b] = [b, a % b]; return a < 0n ? -a : a; }
9
+ function rat(n, d = 1n) {
10
+ if (!d)
11
+ fail('invalid_pricing_expression', 'The pricing rule divides by zero.');
12
+ if (n.toString().length > 4096 || d.toString().length > 4096)
13
+ fail('invalid_pricing_expression', 'The pricing calculation exceeds its size limit.');
14
+ if (d < 0n) {
15
+ n = -n;
16
+ d = -d;
17
+ }
18
+ const g = gcd(n, d);
19
+ return { n: n / g, d: d / g };
20
+ }
21
+ function decimal(value) {
22
+ const text = String(value);
23
+ if (text.length > 128 || !/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(text))
24
+ fail('invalid_pricing_expression', 'The pricing rule requires a finite decimal.');
25
+ const [whole, part = ''] = text.split('.');
26
+ return rat(BigInt(whole + part), 10n ** BigInt(part.length));
27
+ }
28
+ function numeric(value) {
29
+ if (typeof value === 'object')
30
+ return value;
31
+ if (typeof value === 'string')
32
+ return decimal(value);
33
+ return fail('invalid_pricing_expression', 'The pricing rule requires a number.');
34
+ }
35
+ function boolean(value) {
36
+ if (typeof value !== 'boolean')
37
+ fail('invalid_pricing_expression', 'The pricing rule requires a boolean condition.');
38
+ return value;
39
+ }
40
+ const cmp = (a, b) => a.n * b.d < b.n * a.d ? -1 : a.n * b.d > b.n * a.d ? 1 : 0;
41
+ const mul = (a, b) => rat(a.n * b.n, a.d * b.d);
42
+ const div = (a, b) => rat(a.n * b.d, a.d * b.n);
43
+ const add = (a, b) => rat(a.n * b.d + b.n * a.d, a.d * b.d);
44
+ function rounded(a, mode) {
45
+ const trunc = a.n / a.d, remainder = a.n % a.d;
46
+ if (mode === 'floor')
47
+ return rat(trunc - (remainder < 0n ? 1n : 0n));
48
+ if (mode === 'ceil')
49
+ return rat(trunc + (remainder > 0n ? 1n : 0n));
50
+ if (mode === 'half_up')
51
+ return rat(trunc + ((remainder < 0n ? -remainder : remainder) * 2n >= a.d ? (a.n < 0n ? -1n : 1n) : 0n));
52
+ return fail('invalid_pricing_expression', 'The pricing rule uses an unsupported rounding mode.');
53
+ }
54
+ function exact(a) { return a.d === 1n ? String(a.n) : `${a.n}/${a.d}`; }
55
+ function display(a, places) {
56
+ const scale = 10n ** BigInt(places), n = rounded(mul(a, rat(scale)), 'half_up').n;
57
+ const text = n.toString().padStart(places + 1, '0');
58
+ return places ? `${text.slice(0, -places)}.${text.slice(-places)}`.replace(/\.?0+$/, '') : text;
59
+ }
60
+ export function amountsForUC(uc) {
61
+ const a = decimal(uc);
62
+ return { uc, credits: display(div(a, rat(10000n)), 4), cny: display(div(a, rat(100000n)), 5), usd: display(div(a, rat(680000n)), 8) };
63
+ }
64
+ export function rulesBudgetExceeded(uc, budget) {
65
+ // String(number) may use scientific notation for a small, explicit budget.
66
+ const [mantissa, exp = '0'] = String(budget).split('e');
67
+ const power = Number(exp), b = decimal(mantissa);
68
+ const value = power < 0 ? div(b, rat(10n ** BigInt(-power))) : mul(b, rat(10n ** BigInt(power)));
69
+ return cmp(decimal(uc), mul(value, rat(680000n))) > 0;
70
+ }
71
+ const arity = { constant: [0, 0], variable: [0, 0], lookup: [0, 0],
72
+ add: [2, 32], multiply: [2, 32], subtract: [2, 2], divide: [2, 2], min: [2, 32], max: [2, 32], clamp: [3, 3],
73
+ ceil: [1, 1], floor: [1, 1], if: [3, 3], eq: [2, 2], neq: [2, 2], lt: [2, 2], lte: [2, 2], gt: [2, 2], gte: [2, 2],
74
+ and: [2, 32], or: [2, 32], not: [1, 1] };
75
+ function checkExpression(node, declared, depth = 0, budget = { nodes: 0 }) {
76
+ const bounds = arity[node.op], size = node.args?.length ?? 0;
77
+ if (depth > 32 || ++budget.nodes > 10_000 || !bounds || size < bounds[0] || size > bounds[1]) {
78
+ fail('invalid_pricing_expression', 'The pricing rule has an unsupported or malformed expression.');
79
+ }
80
+ if (node.op === 'constant' && node.value === undefined || node.op === 'variable' && (!node.name || !declared.has(node.name))) {
81
+ fail('invalid_pricing_expression', 'The pricing rule references an undeclared value.');
82
+ }
83
+ if (node.op === 'lookup') {
84
+ if (!node.key || !node.values)
85
+ fail('invalid_pricing_expression', 'The pricing lookup is incomplete.');
86
+ checkExpression(node.key, declared, depth + 1, budget);
87
+ }
88
+ for (const child of node.args ?? [])
89
+ checkExpression(child, declared, depth + 1, budget);
90
+ }
91
+ function evaluate(node, params) {
92
+ const nodes = node.args ?? [], at = (i) => evaluate(nodes[i], params), number = (i) => numeric(at(i));
93
+ switch (node.op) {
94
+ case 'constant': return node.value === 'true' ? true : node.value === 'false' ? false : node.value;
95
+ case 'variable': {
96
+ if (!Object.hasOwn(params, node.name))
97
+ throw new QuoteError('quote_usage_required', `Provide measured or expected usage for ${node.name} in pricing_parameters.`, node.name);
98
+ return typeof params[node.name] === 'number' ? decimal(params[node.name]) : params[node.name];
99
+ }
100
+ case 'lookup': {
101
+ const key = evaluate(node.key, params), text = typeof key === 'object' ? exact(key) : String(key);
102
+ if (!Object.hasOwn(node.values, text))
103
+ fail('invalid_pricing_expression', 'No published pricing rule matches the selected parameter.');
104
+ return decimal(node.values[text]);
105
+ }
106
+ case 'if': return boolean(at(0)) ? at(1) : at(2);
107
+ case 'and': return nodes.every((_n, i) => boolean(at(i)));
108
+ case 'or': return nodes.some((_n, i) => boolean(at(i)));
109
+ case 'not': return !boolean(at(0));
110
+ case 'eq':
111
+ case 'neq': {
112
+ const a = at(0), b = at(1);
113
+ const equal = typeof a === 'boolean' || typeof b === 'boolean' ? a === b
114
+ : typeof a === 'object' || typeof b === 'object' || /^-?\d+(?:\.\d+)?$/.test(String(a)) && /^-?\d+(?:\.\d+)?$/.test(String(b))
115
+ ? cmp(numeric(a), numeric(b)) === 0 : a === b;
116
+ return node.op === 'eq' ? equal : !equal;
117
+ }
118
+ case 'lt': return cmp(number(0), number(1)) < 0;
119
+ case 'lte': return cmp(number(0), number(1)) <= 0;
120
+ case 'gt': return cmp(number(0), number(1)) > 0;
121
+ case 'gte': return cmp(number(0), number(1)) >= 0;
122
+ case 'add': return nodes.reduce((sum, _n, i) => add(sum, number(i)), rat(0n));
123
+ case 'multiply': return nodes.reduce((product, _n, i) => mul(product, number(i)), rat(1n));
124
+ case 'subtract': {
125
+ const b = number(1);
126
+ return add(number(0), rat(-b.n, b.d));
127
+ }
128
+ case 'divide': return div(number(0), number(1));
129
+ case 'ceil':
130
+ case 'floor': return rounded(number(0), node.op);
131
+ case 'min':
132
+ case 'max': return nodes.map((_n, i) => number(i)).reduce((a, b) => (cmp(a, b) < 0) === (node.op === 'min') ? a : b);
133
+ case 'clamp': {
134
+ const a = number(0), low = number(1), high = number(2);
135
+ if (cmp(low, high) > 0)
136
+ fail('invalid_pricing_expression', 'The pricing rule has invalid clamp bounds.');
137
+ return cmp(a, low) < 0 ? low : cmp(a, high) > 0 ? high : a;
138
+ }
139
+ default: return fail('invalid_pricing_expression', 'The pricing rule uses an unsupported operation.');
140
+ }
141
+ }
142
+ export const ApprovedRulesEstimate = z.object({ source: z.literal('pricing_rules'), price_scope: z.literal('public_default'),
143
+ model_id: z.string().min(1).max(100), request_hash: z.string().regex(/^[a-f0-9]{64}$/),
144
+ fingerprint: z.string().regex(/^[a-f0-9]{64}$/), total_uc: z.string().max(32).regex(/^\d+$/),
145
+ expires_at: z.string().datetime({ offset: true }) }).strict();
146
+ function economicRules(rule) {
147
+ // Freshness and configuration timestamps do not change the approved price.
148
+ return { ...rule, components: rule.components.map(({ effective_at, official_rate, ...c }) => ({ ...c,
149
+ tiers: c.tiers.map(({ effective_at, official_rate, ...t }) => t) })) };
150
+ }
151
+ export function calculateRulesEstimate(body, entry, input, options = {}) {
152
+ const rule = 'model' in body ? body.model : body.models.find(model => model.model_id === entry.id);
153
+ if (!rule || rule.model_id !== entry.id.toLowerCase() || rule.modality !== entry.kind || rule.policy_source !== 'published' || rule.pricing_status !== 'available') {
154
+ fail('pricing_rules_unavailable', 'This model has no available published media pricing policy.');
155
+ }
156
+ const params = prepareQuoteParameters(rule, entry, input, options.pricingParameters, options.mediaSeconds, true);
157
+ const declared = new Set((rule.parameters ?? []).map(p => p.name)), ids = new Set();
158
+ const components = [];
159
+ let total = 0n;
160
+ const missing = new Set();
161
+ for (const c of rule.components) {
162
+ if (ids.has(c.id) || !c.quantity_rule || !c.rounding)
163
+ fail('invalid_pricing_expression', 'The pricing rule is incomplete or has duplicate components.');
164
+ ids.add(c.id);
165
+ for (const expr of [c.condition, c.quantity_rule, ...c.tiers.map(t => t.when)])
166
+ if (expr)
167
+ checkExpression(expr, declared);
168
+ if (!['per_quantity', 'per_tier', 'per_component_subtotal'].includes(c.rounding.point)
169
+ || !['half_up', 'ceil', 'floor'].includes(c.rounding.mode))
170
+ fail('invalid_pricing_expression', 'The pricing rule has unsupported rounding.');
171
+ try {
172
+ if (c.condition && !boolean(evaluate(c.condition, params)))
173
+ continue;
174
+ const matches = c.tiers.filter(t => t.when && boolean(evaluate(t.when, params)));
175
+ if (matches.length > 1)
176
+ fail('invalid_pricing_expression', 'Multiple pricing tiers match the request.');
177
+ const selected = matches[0] ?? c;
178
+ if (selected.pricing_status !== 'available')
179
+ fail('pricing_rules_unavailable', 'A required pricing component is unavailable.');
180
+ const q = numeric(evaluate(c.quantity_rule, params)), m = decimal(matches[0]?.multiplier ?? '1'), rate = decimal(selected.rate.uc);
181
+ if (q.n < 0n)
182
+ fail('invalid_pricing_expression', 'The pricing rule produces a negative quantity.');
183
+ // Catalog tier.rate already includes its multiplier. Applying it twice overcharges.
184
+ const billed = mul(q, m);
185
+ const subtotal = c.rounding.point === 'per_quantity' ? mul(rounded(billed, c.rounding.mode), div(rate, m))
186
+ : c.rounding.point === 'per_tier' ? mul(q, rounded(rate, c.rounding.mode))
187
+ : rounded(mul(q, rate), c.rounding.mode);
188
+ const minimum = decimal(selected.minimum_charge.uc);
189
+ const charge = cmp(subtotal, minimum) < 0 ? minimum : subtotal;
190
+ if (charge.d !== 1n || charge.n < 0n || charge.n > BigInt(Number.MAX_SAFE_INTEGER))
191
+ fail('invalid_pricing_expression', 'The pricing rule does not produce a supported integer UC charge.');
192
+ total += charge.n;
193
+ components.push({ id: c.id, sku_id: selected.sku_id, quantity: exact(q), billed_quantity: exact(billed),
194
+ subtotal_uc: String(charge.n), minimum_charge_applied: cmp(subtotal, minimum) < 0 });
195
+ }
196
+ catch (error) {
197
+ if (error instanceof QuoteError && error.code === 'quote_usage_required' && error.param)
198
+ missing.add(error.param);
199
+ else
200
+ throw error;
201
+ }
202
+ }
203
+ if (total > BigInt(Number.MAX_SAFE_INTEGER))
204
+ fail('invalid_pricing_expression', 'The estimated charge exceeds its supported range.');
205
+ const amounts = amountsForUC(String(total)), requestHash = quoteRequestHash(entry.id, input, options.mediaSeconds, options.pricingParameters);
206
+ const approval = { source: 'pricing_rules', price_scope: 'public_default', model_id: entry.id,
207
+ request_hash: requestHash, total_uc: amounts.uc, expires_at: body.meta.fresh_until,
208
+ fingerprint: quoteRequestHash(entry.id, { rules: economicRules(rule), parameters: params,
209
+ exchange_rate_version: body.meta.exchange_rate_version, components, missing: [...missing].sort(), total_uc: amounts.uc }) };
210
+ const estimate = { status: missing.size ? components.length ? 'partial' : 'needs_input' : 'estimated', min_usd: Number(amounts.usd), max_usd: Number(amounts.usd),
211
+ min_credits: Number(amounts.credits), max_credits: Number(amounts.credits),
212
+ basis: ['Published full pricing rules evaluated for the supplied generation parameters; exact UC rounding and component minimums.'],
213
+ ...(missing.size ? { uncheckable_reason: 'usage' } : {}),
214
+ possible_extras: [...missing].map(name => `Additional charge depends on ${name}; supply expected or measured usage in pricing_parameters.`), notes: ['Public default prices; account discounts are not included.',
215
+ 'Confirm the estimated cost before generation. Actual billed usage and final charges may differ.'] };
216
+ return { approval, estimate, amounts, components, parameters: params, rule };
217
+ }
218
+ export async function createRulesEstimate(entry, input, options = {}) {
219
+ const { body } = await getPricingRules({ model: entry.id.toLowerCase(), view: 'full' }, { fresh: true });
220
+ return calculateRulesEstimate(body, entry, input, options);
221
+ }
222
+ export function checkRulesApproval(approval, fresh) {
223
+ if (Date.parse(approval.expires_at) <= Date.now())
224
+ fail('quote_expired', 'The approved estimate expired. Estimate again and obtain approval.');
225
+ if (approval.request_hash !== fresh.approval.request_hash || approval.model_id !== fresh.approval.model_id) {
226
+ fail('quote_input_changed', 'The generation input differs from the approved estimate.');
227
+ }
228
+ if (approval.fingerprint !== fresh.approval.fingerprint || approval.total_uc !== fresh.approval.total_uc) {
229
+ fail('price_changed', 'The pricing rules or estimated price changed. Estimate again and obtain approval.');
230
+ }
231
+ }
@@ -0,0 +1,63 @@
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
+ /** Only bounded public primitives may cross an error boundary. Result URLs use a separate delivery contract. */
4
+ export function publicIdentifier(value) {
5
+ return typeof value === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(value)
6
+ && !/^(sk-|evup_|eyJ)/i.test(value) ? value : undefined;
7
+ }
8
+ export function publicText(value) {
9
+ const ids = [];
10
+ const protectedText = value.slice(0, 2000).replace(/client_request_id "([A-Za-z0-9._-]{16,96})"/g, (match, id) => {
11
+ if (!publicIdentifier(id))
12
+ return match;
13
+ ids.push(id);
14
+ return `client_request_id "PUBLICCORRELATION${ids.length - 1}"`;
15
+ });
16
+ return protectedText
17
+ .replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')
18
+ .replace(/\b(?:sk-|evup_)[a-zA-Z0-9_-]+/g, '[redacted]')
19
+ .replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '[redacted]')
20
+ .replace(/https?:\/\/[^\s"'<>]+|\b(?:[a-z0-9-]+\.)+[a-z]{2,}(?::\d+)?(?:\/[^\s]*)?(?![A-Za-z0-9_.-])/gi, value => {
21
+ if (/^(input|params|parameters|task|usage|billing|quote|estimate)\.[A-Za-z_][A-Za-z0-9_.]*$/.test(value))
22
+ return value;
23
+ const suffix = /[.,;:!?)]+$/.exec(value)?.[0] ?? '';
24
+ const candidate = suffix ? value.slice(0, -suffix.length) : value;
25
+ try {
26
+ const url = new URL(candidate);
27
+ if (url.origin === 'https://evolink.ai' && !url.username && !url.password && !url.hash
28
+ && ['/dashboard/credits', '/dashboard/keys', '/dashboard/mcp'].includes(url.pathname)
29
+ && [...url.searchParams].every(([key, v]) => key.startsWith('utm_') && /^[a-z0-9_-]{1,80}$/i.test(v) || key === 'tab' && v === 'mcp'))
30
+ return value;
31
+ }
32
+ catch { }
33
+ return '[service address]';
34
+ })
35
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ' ')
36
+ .replace(/PUBLICCORRELATION(\d+)/g, (match, n) => ids[Number(n)] ?? match);
37
+ }
38
+ export function publicNumber(value) {
39
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1e12 ? value : undefined;
40
+ }
41
+ /** Reject prose in identifiers/names rather than letting remote text become an instruction. */
42
+ export function publicLabel(value) {
43
+ if (typeof value !== 'string' || !/^[\p{L}\p{N} _()/-]{1,80}$/u.test(value))
44
+ return undefined;
45
+ return publicText(value) === value ? value : undefined;
46
+ }
47
+ export function publicErrorDetails(value, depth = 0, seen = new WeakSet(), key = '') {
48
+ if (depth > 8)
49
+ return '[truncated]';
50
+ if (typeof value === 'string')
51
+ return ['client_request_id', 'task_id', 'quote_id', 'request_id'].includes(key) ? publicIdentifier(value) : publicText(value);
52
+ if (value && typeof value === 'object') {
53
+ if (seen.has(value))
54
+ return '[truncated]';
55
+ seen.add(value);
56
+ if (Array.isArray(value))
57
+ return value.slice(0, 100).map(v => publicErrorDetails(v, depth + 1, seen, key));
58
+ return Object.fromEntries(Object.entries(value).slice(0, 100)
59
+ .filter(([key]) => !/^(authorization|access_token|refresh_token|api_key|secret|password|client_secret)$/i.test(key))
60
+ .map(([key, nested]) => [publicText(key), publicErrorDetails(nested, depth + 1, seen, key)]));
61
+ }
62
+ return typeof value === 'number' && !Number.isFinite(value) ? undefined : value;
63
+ }
@@ -7,6 +7,7 @@ export const PAID_GENERATION_GUIDANCE = [
7
7
  'End the reply and wait for the user to explicitly approve that quoted task before calling a generate tool.',
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
+ '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.',
10
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.',
11
12
  'Never remove or raise a user spending cap without their explicit approval.',
12
13
  ].join(' ');
@@ -40,6 +41,7 @@ export const GENERATION_CONFIRMATION_GUIDANCE = [
40
41
  '',
41
42
  '- Include only applicable output settings supported by the selected model. Use the chosen reference inputs; do not invent settings, prices or totals.',
42
43
  '- 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
+ '- 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.',
43
45
  '- For a partial estimate, label it "部分估价" / "Partial estimate", state what is excluded, and say it is neither the total nor an upper bound.',
44
46
  '- 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.',
45
47
  '- 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.',
@@ -4,7 +4,10 @@ import { z } from 'zod';
4
4
  import { getCredits } from '../services/api-client.js';
5
5
  import { resolveModel, suggestModels } from '../services/model-catalog.js';
6
6
  import { formatIssues, validateInput } from '../services/param-validator.js';
7
- import { estimateCost, formatEstimateRange } from '../services/pricing-client.js';
7
+ import { formatEstimateRange } from '../services/pricing-client.js';
8
+ import { PricingRulesError } from '../services/pricing-rules-client.js';
9
+ import { QuoteError, QuoteParameters } from '../services/pricing-quote-client.js';
10
+ import { createRulesEstimate } from '../services/pricing-rules-estimate.js';
8
11
  import { API_KEYS_URL, MCP_CONSOLE_URL, MCP_KEY_NAME, TOP_UP_URL } from '../services/http-policy.js';
9
12
  import { trackedLink } from '../services/utm.js';
10
13
  import { currentCredentialMode } from '../request-context.js';
@@ -21,19 +24,24 @@ export function registerEstimateCost(server, config) {
21
24
  model: z.string().min(1).max(128).describe('Model ID, e.g. "seedance-2.0-text-to-video".'),
22
25
  input: z.record(z.unknown()).optional()
23
26
  .describe('The input you plan to pass to the generate tool, e.g. {"prompt":"…","duration":5,"quality":"1080p"}.'),
27
+ 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.'),
28
+ pricing_parameters: QuoteParameters.optional().describe('Measured or expected billing usage declared by the pricing policy, such as input_seconds. Do not include user_group, prices or generation prompts.'),
24
29
  media_seconds: z.number().positive().max(MEDIA_SECONDS_MAX).optional().describe(MEDIA_SECONDS_DESCRIPTION),
25
30
  },
26
31
  annotations: { title: 'Estimate cost', ...READ_ONLY },
27
- }, async ({ model, input, media_seconds: mediaSeconds }) => {
32
+ }, async ({ model, input, media_seconds: mediaSeconds, pricing_source: pricingSource, pricing_parameters: pricingParameters }) => {
28
33
  try {
29
- const { catalog, entry } = await resolveModel(model, config, { fresh: true, allowStale: false });
34
+ const { catalog, entry } = await resolveModel(model, config, { fresh: true, allowStale: false, skipPricing: true });
30
35
  if (!entry) {
31
36
  const suggestions = suggestModels(catalog, model);
32
37
  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 });
33
38
  }
34
39
  const values = input ?? {};
35
40
  const validation = entry.spec ? validateInput(entry.spec, values) : undefined;
36
- const estimate = estimateCost(entry.priced, entry.kind, values, entry.spec, { mediaSeconds });
41
+ if (validation?.errors.length)
42
+ return failure('The generation input is invalid; no estimate was created.', { input_valid: false, problems: validation.errors, error: { category: 'invalid_request' }, charged: 'no' });
43
+ const rulesEstimate = await createRulesEstimate(entry, values, { mediaSeconds, pricingParameters });
44
+ const estimate = rulesEstimate.estimate;
37
45
  const lines = [`Estimate for ${entry.id} (${entry.kind}); nothing was submitted or charged.`];
38
46
  if (!validation) {
39
47
  lines.push('Input not checked: this model\'s parameters are not documented here.');
@@ -68,7 +76,16 @@ export function registerEstimateCost(server, config) {
68
76
  const structured = {
69
77
  model: entry.id,
70
78
  type: entry.kind,
71
- pricing_scope: 'public_default_group',
79
+ pricing_scope: 'public_default',
80
+ pricing_source: 'pricing_rules',
81
+ pricing_quote: rulesEstimate.approval,
82
+ amounts: rulesEstimate.amounts,
83
+ components: rulesEstimate.components,
84
+ pricing_parameters: rulesEstimate.parameters,
85
+ policy_version: rulesEstimate.rule.policy_version,
86
+ policy_checksum: rulesEstimate.rule.policy_checksum,
87
+ settlement_basis: rulesEstimate.rule.settlement_basis,
88
+ expires_at: rulesEstimate.approval.expires_at,
72
89
  final_budget_enforced: false,
73
90
  input_valid: validation ? validation.errors.length === 0 : null,
74
91
  problems: validation?.errors ?? [],
@@ -122,15 +139,23 @@ export function registerEstimateCost(server, config) {
122
139
  catch {
123
140
  lines.push('Balance: could not be read right now.');
124
141
  }
125
- if (catalog.pricingWarning) {
126
- lines.push(`Note: ${catalog.pricingWarning}`);
127
- structured.pricing_warning = catalog.pricingWarning;
128
- }
129
- lines.push('This is an estimate from published prices. The amount actually reserved is shown when the task is submitted, and the final charge when it finishes.');
142
+ 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.');
130
143
  return ok(lines.join('\n'), structured);
131
144
  }
132
145
  catch (error) {
133
- return errorResult(error);
146
+ if (error instanceof PricingRulesError)
147
+ return failure('The model pricing rules could not be verified. No estimate or generation was created.', {
148
+ error: { category: 'estimate_unavailable', code: error.code, status: error.status }, pricing_source: pricingSource,
149
+ submission_allowed: false, final_budget_enforced: false, charged: 'no'
150
+ });
151
+ if (error instanceof QuoteError)
152
+ return failure(`${error.message} Nothing was submitted or charged.`, {
153
+ error: { category: 'estimate_unavailable', code: error.code, ...(error.param ? { param: error.param } : {}) },
154
+ pricing_source: pricingSource, submission_allowed: false, final_budget_enforced: false, charged: 'no'
155
+ });
156
+ const failed = errorResult(error);
157
+ return { ...failed, structuredContent: { ...failed.structuredContent, pricing_source: pricingSource,
158
+ submission_allowed: false, final_budget_enforced: false, charged: 'no' } };
134
159
  }
135
160
  });
136
161
  }
@@ -4,7 +4,10 @@ import { z } from 'zod';
4
4
  import { submitTask } from '../services/api-client.js';
5
5
  import { resolveModel, suggestModels } from '../services/model-catalog.js';
6
6
  import { formatIssues, validateInput } from '../services/param-validator.js';
7
- import { estimateCost, formatEstimateRange } from '../services/pricing-client.js';
7
+ import { formatEstimateRange } from '../services/pricing-client.js';
8
+ import { ApprovedAccountQuote, QuoteParameters, QuoteError } from '../services/pricing-quote-client.js';
9
+ import { ApprovedRulesEstimate, createRulesEstimate, checkRulesApproval, rulesBudgetExceeded } from '../services/pricing-rules-estimate.js';
10
+ import { PricingRulesError } from '../services/pricing-rules-client.js';
8
11
  import { CLIENT_REQUEST_ID_PATTERN, newRunId } from '../services/http-policy.js';
9
12
  import { formatUsd } from '../services/error-handler.js';
10
13
  import { MEDIA_SECONDS_DESCRIPTION, MEDIA_SECONDS_MAX, PAID, errorResult, failure, money, ok, progressReporter, usdOf } from './shared.js';
@@ -46,6 +49,8 @@ function rangeText(estimate) {
46
49
  }
47
50
  /** Why max_cost_usd could not be checked, and what the assistant can do next. */
48
51
  function uncheckedCap(estimate, pricingWarning) {
52
+ if (estimate.uncheckable_reason === 'usage')
53
+ return ['published pricing rules need additional billing usage to calculate a complete estimate', `Provide the missing expected or measured usage in pricing_parameters. ${estimate.possible_extras.join(' ')}`];
49
54
  if (estimate.uncheckable_reason === 'output_duration') {
50
55
  return ['the generated output duration is not fixed, so the declared seconds cannot establish an upper bound', 'Use an explicit duration if the model accepts it; otherwise ask the user whether to proceed without a cap.'];
51
56
  }
@@ -90,7 +95,10 @@ function registerGenerate(server, config, kind) {
90
95
  client_request_id: z.string().regex(CLIENT_REQUEST_ID_PATTERN).optional()
91
96
  .describe('Optional idempotency key (16–96 characters: letters, digits, . _ -). Reuse the same value only to retry the same request after a network error or timeout.'),
92
97
  max_cost_usd: z.number().positive().max(10_000).optional()
93
- .describe('Optional estimate-based submission cap, not a final settlement guarantee: refuses to submit when fresh public prices are unavailable, the estimate is higher or published rules cannot cover the full request. Per-second video requests with video_urls, video_url or source_task_id cannot use this cap, even with media_seconds.'),
98
+ .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.'),
99
+ account_quote: ApprovedAccountQuote.optional().describe('Legacy approval. Refresh with estimate_cost and obtain user approval before using the new pricing rules.'),
100
+ pricing_quote: ApprovedRulesEstimate.optional().describe('Client approval record from estimate_cost, for exactly this input. Rechecked against fresh pricing rules before submission; does not bind final settlement.'),
101
+ pricing_parameters: QuoteParameters.optional().describe('The same explicit billing usage passed to estimate_cost.'),
94
102
  media_seconds: z.number().positive().max(MEDIA_SECONDS_MAX).optional().describe(MEDIA_SECONDS_DESCRIPTION),
95
103
  },
96
104
  annotations: { title, ...PAID },
@@ -119,8 +127,9 @@ function registerGenerate(server, config, kind) {
119
127
  input.prompt = args.prompt;
120
128
  }
121
129
  let clientRequestId;
130
+ let acceptedTaskId;
122
131
  try {
123
- const { catalog, entry } = await resolveModel(args.model, config, { fresh: true, allowStale: false });
132
+ const { catalog, entry } = await resolveModel(args.model, config, { fresh: true, allowStale: false, skipPricing: true });
124
133
  if (!entry) {
125
134
  const suggestions = suggestModels(catalog, args.model, kind);
126
135
  return failure(`Unknown ${kind} model "${args.model}".${suggestions.length ? ` Did you mean: ${suggestions.join(', ')}?` : ''} Use search_models to find model IDs. Nothing was submitted or charged.`, { error: { category: 'not_found', param: 'model' }, suggestions, charged: 'no' });
@@ -148,7 +157,12 @@ function registerGenerate(server, config, kind) {
148
157
  warnings.push('This model\'s parameters are not documented here, so the input was not checked before sending.');
149
158
  }
150
159
  // media_seconds only prices the request; the body below is built from input alone.
151
- const estimate = estimateCost(entry.priced, kind, input, entry.spec, { mediaSeconds: args.media_seconds });
160
+ if (args.account_quote)
161
+ throw new QuoteError('quote_refresh_required', 'Refresh the legacy account estimate with estimate_cost and obtain user approval.');
162
+ const rulesEstimate = await createRulesEstimate(entry, input, { mediaSeconds: args.media_seconds, pricingParameters: args.pricing_parameters });
163
+ if (args.pricing_quote)
164
+ checkRulesApproval(args.pricing_quote, rulesEstimate);
165
+ const estimate = rulesEstimate.estimate;
152
166
  if (args.max_cost_usd !== undefined) {
153
167
  if (estimate.uncheckable_reason !== undefined || estimate.status !== 'estimated' || estimate.max_usd === undefined) {
154
168
  const [reason, next] = uncheckedCap(estimate, catalog.pricingWarning);
@@ -158,7 +172,7 @@ function registerGenerate(server, config, kind) {
158
172
  charged: 'no',
159
173
  });
160
174
  }
161
- if (estimate.max_usd > args.max_cost_usd) {
175
+ if (rulesBudgetExceeded(rulesEstimate.amounts.uc, args.max_cost_usd)) {
162
176
  return failure(`The estimated cost ${rangeText(estimate)} is above max_cost_usd $${formatUsd(args.max_cost_usd)}. Nothing was submitted or charged. Lower the duration, count or quality, or ask the user to raise the cap.`, {
163
177
  error: { category: 'invalid_request', param: 'max_cost_usd' },
164
178
  estimate,
@@ -166,6 +180,8 @@ function registerGenerate(server, config, kind) {
166
180
  });
167
181
  }
168
182
  }
183
+ if (estimate.status === 'needs_input')
184
+ throw new QuoteError('quote_usage_required', 'No charge can be estimated yet; supply the missing pricing usage before submission.');
169
185
  clientRequestId = args.client_request_id ?? newRunId();
170
186
  const body = { ...input, model: entry.id };
171
187
  const submitted = await submitTask(config, {
@@ -174,6 +190,7 @@ function registerGenerate(server, config, kind) {
174
190
  tool: name,
175
191
  idempotencyKey: clientRequestId,
176
192
  });
193
+ acceptedTaskId = submitted.id;
177
194
  let task = submitted;
178
195
  const waitUntil = started + WAIT_MS[kind];
179
196
  if (!TERMINAL_STATUSES.has(task.status) && WAIT_MS[kind] > 0 && Date.now() + 3_000 < waitUntil) {
@@ -216,7 +233,9 @@ function registerGenerate(server, config, kind) {
216
233
  return ok(lines.join('\n'), {
217
234
  ...view.structured,
218
235
  submitted: { model: entry.id, input },
219
- pricing_scope: 'public_default_group',
236
+ pricing_scope: 'public_default',
237
+ pricing_source: 'pricing_rules',
238
+ amounts: rulesEstimate.amounts,
220
239
  final_budget_enforced: false,
221
240
  client_request_id: clientRequestId,
222
241
  replayed: submitted.idempotency_replayed === true,
@@ -227,8 +246,13 @@ function registerGenerate(server, config, kind) {
227
246
  }, view.resources);
228
247
  }
229
248
  catch (error) {
249
+ if (error instanceof PricingRulesError)
250
+ return failure('The pricing rules could not be verified. Nothing was submitted or charged.', { error: { category: 'estimate_unavailable', code: error.code }, charged: 'no', submission_state: 'not_submitted' });
251
+ if (error instanceof QuoteError)
252
+ return failure(`${error.message} Nothing was submitted or charged.`, { error: { category: 'estimate_unavailable', code: error.code }, charged: 'no', submission_state: 'not_submitted' });
230
253
  // clientRequestId is set right before the submit, so it also tells whether a request may have gone out.
231
- return errorResult(error, { paid: clientRequestId !== undefined, clientRequestId });
254
+ return errorResult(error, { paid: clientRequestId !== undefined, clientRequestId, taskId: acceptedTaskId,
255
+ phase: acceptedTaskId ? 'accepted' : clientRequestId ? 'submit_started' : 'before_submit' });
232
256
  }
233
257
  });
234
258
  }
@@ -110,7 +110,9 @@ export function registerGetModel(server, config) {
110
110
  else {
111
111
  lines.push('', 'Parameters for this model are not documented here; the gateway checks the input when you submit.');
112
112
  }
113
- lines.push('', 'Pricing (USD; 68 credits ≈ $1):');
113
+ lines.push('', 'Public default component base prices (USD; 68 credits ≈ $1). Tiers, quantities and minimum charges affect totals; use estimate_cost with the actual input.');
114
+ structured.pricing_source = 'pricing_rules';
115
+ structured.pricing_scope = 'public_default';
114
116
  if (priced && priced.prices.length > 0) {
115
117
  const groups = [['output', 'Main charge'], ['add_on', 'Extra charges'], ['token', 'Usage-based']];
116
118
  for (const [role, label] of groups) {
@@ -0,0 +1,54 @@
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 { currentRequestCredentials } from '../request-context.js';
4
+ import { RequestTimeoutError } from '../services/http-policy.js';
5
+ import { getPricingRules, PricingRulesError, PricingRulesQuery } from '../services/pricing-rules-client.js';
6
+ import { failure, ok, READ_ONLY } from './shared.js';
7
+ export function registerPricingRules(server) {
8
+ server.registerTool('get_pricing_rules', {
9
+ title: 'Read public pricing rules',
10
+ 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
+ inputSchema: PricingRulesQuery.shape,
12
+ annotations: { title: 'Read public pricing rules', ...READ_ONLY },
13
+ }, async (input) => {
14
+ try {
15
+ const { body, source } = await getPricingRules(input);
16
+ const models = 'model' in body ? [body.model] : body.models;
17
+ const selection = body.meta.price_selection ?? 'configured_minimum';
18
+ const warnings = [
19
+ selection === 'route_priority'
20
+ ? 'Public reference rates use enabled routes by priority, with the existing web-price fallback when every route is unavailable. Failover can change the actual routed price.'
21
+ : 'Legacy public rates use the lowest configured price, which can include an unavailable route and differ from the web-price reference.',
22
+ 'Public default configuration prices may differ from routed settlement, account-group prices, discounts and promotions.',
23
+ 'No task quote or final spending cap was established. Do not multiply unit rates into a bill; minimum charges, tiers and rounding apply.',
24
+ 'Coverage follows the models returned for this query. Empty results mean no matching public rules were returned, not zero cost.',
25
+ ];
26
+ const lines = [`Public pricing rules (${body.meta.price_scope}; ${selection}; ${source}); ${models.length} model(s).`, ...warnings];
27
+ for (const model of models) {
28
+ lines.push(`${model.model_id} (${model.modality}; ${model.pricing_status}; ${model.policy_source} v${model.policy_version})`);
29
+ for (const component of model.components)
30
+ 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}.`);
31
+ }
32
+ return ok(lines.join('\n'), { ...body, pricing_source: source,
33
+ pricing_endpoint: '/v1/catalog/pricing-rules', quote_established: false, final_budget_enforced: false,
34
+ account_price: false, warnings });
35
+ }
36
+ catch (error) {
37
+ // This operation never reads account credentials. A transport failure or
38
+ // cancellation must not ask the user to sign in or expose exception text.
39
+ const safeError = error instanceof PricingRulesError ? error : new PricingRulesError(currentRequestCredentials()?.http?.signal?.aborted ? 'interrupted'
40
+ : error instanceof RequestTimeoutError ? 'pricing_rules_timeout'
41
+ : error instanceof TypeError ? 'pricing_rules_network_error' : 'pricing_rules_unavailable');
42
+ return failure(safeError.status === 404
43
+ ? 'No public pricing rules are published for this model and filters. This does not mean the model is free or unavailable.'
44
+ : safeError.code === 'interrupted' ? 'Public pricing rules lookup was interrupted. No quote or spending limit was established.'
45
+ : safeError.message, { error: { category: safeError.code === 'interrupted' ? 'interrupted'
46
+ : safeError.status === 404 ? 'not_found' : safeError.status === 429 ? 'rate_limit' : 'server_error',
47
+ code: safeError.code, status: safeError.status,
48
+ retryable: safeError.status === 429 || safeError.status >= 500
49
+ || ['pricing_rules_timeout', 'pricing_rules_network_error'].includes(safeError.code),
50
+ ...(safeError.retryAfter !== undefined ? { retry_after: safeError.retryAfter } : {}) }, charged: 'no',
51
+ quote_established: false, final_budget_enforced: false });
52
+ }
53
+ });
54
+ }