@evolinkai/cli 0.8.1 → 0.9.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.
@@ -0,0 +1,239 @@
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 { createHash } from 'node:crypto';
4
+ import { z } from 'zod';
5
+ import { requestAccountQuote } from './api-client.js';
6
+ import { getPricingRules, PricingMoney } from './pricing-rules-client.js';
7
+ const decimal = z.string().max(64).regex(/^(?:0|[1-9]\d*)(?:\.\d+)?$/);
8
+ const identifier = z.string().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/);
9
+ const rational = z.string().max(128).regex(/^(?:0|[1-9]\d*)(?:\.\d+|\/[1-9]\d*)?$/);
10
+ export const QuoteParameters = z.record(z.string().min(1).max(100), z.union([z.string().max(128), z.number().finite(), z.boolean()]))
11
+ .refine(value => Object.keys(value).length <= 100, 'At most 100 pricing parameters are allowed.');
12
+ const Component = z.object({ id: identifier, role: identifier, dimension: identifier, sku_id: identifier,
13
+ quantity: rational, billed_quantity: rational, unit: identifier, unit_price: decimal, subtotal: decimal,
14
+ unit_price_amounts: PricingMoney, subtotal_amounts: PricingMoney, minimum_charge_amounts: PricingMoney,
15
+ tier_multiplier: decimal.refine(value => compareDecimal(value, '0') > 0), minimum_charge_applied: z.boolean(), billing_rule: identifier,
16
+ applied_rules: z.array(z.string().max(128)).max(100) });
17
+ export const AccountQuoteSchema = z.object({ estimate_id: identifier, catalog_version: identifier,
18
+ pricing_version: identifier, exchange_rate_version: z.literal('pricing-fx/v1:USD-CNY=6.8'),
19
+ price_scope: z.literal('account'), policy_version: z.number().int().positive(),
20
+ policy_checksum: z.string().regex(/^[a-f0-9]{64}$/), model_id: identifier, product_id: identifier,
21
+ operation: identifier, settlement_basis: z.enum(['request_only', 'actual_usage', 'request_then_actual']),
22
+ currency: z.literal('USD'), amount: decimal, amounts: PricingMoney,
23
+ components: z.array(Component).min(1).max(200), assumptions: z.array(z.string().max(2000)).max(100),
24
+ expires_at: z.string().datetime({ offset: true }) });
25
+ export const ApprovedAccountQuote = z.object({ quote: AccountQuoteSchema,
26
+ request_hash: z.string().regex(/^[a-f0-9]{64}$/), parameters: QuoteParameters }).strict();
27
+ export class QuoteError extends Error {
28
+ code;
29
+ param;
30
+ constructor(code, message, param) {
31
+ super(message);
32
+ this.code = code;
33
+ this.param = param;
34
+ }
35
+ }
36
+ function canonical(value) {
37
+ if (Array.isArray(value))
38
+ return `[${value.map(canonical).join(',')}]`;
39
+ if (value && typeof value === 'object')
40
+ return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b))
41
+ .filter(([, v]) => v !== undefined).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;
42
+ return JSON.stringify(value);
43
+ }
44
+ export function quoteRequestHash(model, input, mediaSeconds, pricingParameters = {}) {
45
+ return createHash('sha256').update(canonical({ model: model.toLowerCase(), input, media_seconds: mediaSeconds,
46
+ pricing_parameters: pricingParameters })).digest('hex');
47
+ }
48
+ function fail(code, message, param) { throw new QuoteError(code, message, param); }
49
+ const aliases = { duration_seconds: ['duration'], output_seconds: ['duration'], image_count: ['n', 'count'],
50
+ video_count: ['n', 'count'], resolution: ['quality'], quality: ['resolution'] };
51
+ const measured = /(?:tokens|input_seconds|output_seconds|source_output_seconds|first_input_video_seconds|search_count)$/;
52
+ /** Map only declared billing parameters. Prompts and asset URLs stay in generation input. */
53
+ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {}, mediaSeconds, allowMissingUsage = false) {
54
+ const declared = new Map((rule.parameters ?? []).map(p => [p.name, p]));
55
+ for (const name of Object.keys(pricingParameters))
56
+ if (!declared.has(name)) {
57
+ fail('unsupported_quote_parameter', `The pricing policy does not declare parameter ${name}.`, name);
58
+ }
59
+ const parameters = {};
60
+ for (const [name, p] of declared) {
61
+ // A declared duration and duration_seconds have different meanings (smart duration).
62
+ const generationNames = [name, ...(aliases[name] ?? []).filter(alias => !declared.has(alias))];
63
+ const supplied = generationNames.filter(key => input[key] !== undefined).map(key => input[key]);
64
+ if (supplied.some(value => String(value) !== String(supplied[0]))) {
65
+ fail('conflicting_quote_parameter', `Conflicting generation values for ${name}.`, name);
66
+ }
67
+ let value = supplied[0];
68
+ if (value === undefined && name === 'input_images') {
69
+ if (Array.isArray(input.image_urls))
70
+ value = input.image_urls.length;
71
+ else if (typeof input.image_url === 'string')
72
+ value = 1;
73
+ else
74
+ value = 0;
75
+ }
76
+ // Expected usage cannot change settings or references the model will actually receive.
77
+ if (value === undefined && pricingParameters[name] !== undefined && !measured.test(name)
78
+ && generationNames.some(key => entry.spec?.params[key] !== undefined)) {
79
+ value = generationNames.map(key => entry.spec?.params[key]?.default).find(v => v !== undefined) ?? p.default;
80
+ }
81
+ if (pricingParameters[name] !== undefined) {
82
+ if (value !== undefined && String(value) !== String(pricingParameters[name])) {
83
+ fail('conflicting_quote_parameter', `Pricing parameter ${name} differs from the generation input.`, name);
84
+ }
85
+ value = pricingParameters[name];
86
+ }
87
+ if (name === 'input_seconds' && value !== undefined && mediaSeconds !== undefined
88
+ && String(value) !== String(mediaSeconds)) {
89
+ fail('conflicting_quote_parameter', 'input_seconds differs from media_seconds.', name);
90
+ }
91
+ // media_seconds describes measured input length, never an unknown generated output.
92
+ if (value === undefined && name === 'input_seconds' && mediaSeconds !== undefined)
93
+ value = mediaSeconds;
94
+ if (value === undefined && name === 'first_input_video_seconds' && mediaSeconds !== undefined)
95
+ value = mediaSeconds;
96
+ if (value === undefined && ['output_seconds', 'duration_seconds'].includes(name) && mediaSeconds !== undefined && entry.spec && !entry.spec.params.duration && !declared.has('duration') && entry.spec?.constraints?.outputDuration !== 'unknown')
97
+ value = mediaSeconds;
98
+ if (value === undefined && name === 'duration_seconds' && declared.has('duration') && String(input.duration ?? pricingParameters.duration ?? entry.spec?.params.duration?.default ?? declared.get('duration')?.default) === '-1') {
99
+ if (allowMissingUsage)
100
+ continue;
101
+ fail('quote_usage_required', 'Provide expected generated duration_seconds for automatic duration in pricing_parameters.', name);
102
+ }
103
+ if (value === undefined && ['duration_seconds', 'output_seconds'].includes(name) && entry.spec?.constraints?.outputDuration === 'unknown') {
104
+ if (allowMissingUsage)
105
+ continue;
106
+ fail('quote_usage_required', `Provide expected generated ${name} in pricing_parameters.`, name);
107
+ }
108
+ if (value === undefined && !measured.test(name)) {
109
+ const defaults = generationNames.map(key => entry.spec?.params[key]?.default).filter(v => v !== undefined);
110
+ value = defaults[0];
111
+ }
112
+ const references = Array.isArray(input.video_urls) && input.video_urls.length > 0
113
+ || typeof input.video_url === 'string' && input.video_url.trim().length > 0
114
+ || typeof input.source_task_id === 'string' && input.source_task_id.trim().length > 0;
115
+ if (value === undefined && measured.test(name) && (p.required || references || /tokens$/.test(name) || (name === 'search_count' && input.web_search === true) || p.default === undefined)) {
116
+ if (allowMissingUsage)
117
+ continue;
118
+ fail('quote_usage_required', `Provide measured or expected usage for ${name} in pricing_parameters.`, name);
119
+ }
120
+ if (value === undefined)
121
+ value = p.default;
122
+ if (value === undefined) {
123
+ if (p.required)
124
+ fail('quote_parameter_required', `Pricing parameter ${name} is required.`, name);
125
+ continue;
126
+ }
127
+ if (!['string', 'number', 'boolean'].includes(typeof value) || (typeof value === 'number' && !Number.isFinite(value))) {
128
+ fail('invalid_quote_parameter', `Pricing parameter ${name} must be a finite scalar.`, name);
129
+ }
130
+ if (typeof value === 'string' && value.length > 128)
131
+ fail('invalid_quote_parameter', `Pricing parameter ${name} is too long.`, name);
132
+ if (p.type === 'integer' || p.type === 'decimal') {
133
+ if (typeof value === 'number' && String(value).includes('e')) {
134
+ const negative = value < 0, [mantissa, exponent] = String(Math.abs(value)).split('e');
135
+ const [whole, part = ''] = mantissa.split('.'), digits = whole + part, point = whole.length + Number(exponent);
136
+ value = (negative ? '-' : '') + (point <= 0 ? '0.' + '0'.repeat(-point) + digits
137
+ : point >= digits.length ? digits + '0'.repeat(point - digits.length) : digits.slice(0, point) + '.' + digits.slice(point));
138
+ if (String(value).length > 128)
139
+ fail('invalid_quote_parameter', `Pricing parameter ${name} is too long.`, name);
140
+ }
141
+ if (typeof value === 'boolean' || !/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(String(value))
142
+ || (p.type === 'integer' && !/^-?(?:0|[1-9]\d*)$/.test(String(value)))) {
143
+ fail('invalid_quote_parameter', `Pricing parameter ${name} must be ${p.type}.`, name);
144
+ }
145
+ if ((p.minimum !== undefined && compareDecimal(String(value), p.minimum) < 0)
146
+ || (p.maximum !== undefined && compareDecimal(String(value), p.maximum) > 0)) {
147
+ fail('invalid_quote_parameter', `Pricing parameter ${name} is outside the published range.`, name);
148
+ }
149
+ }
150
+ else if (p.type === 'boolean' && typeof value !== 'boolean') {
151
+ fail('invalid_quote_parameter', `Pricing parameter ${name} must be boolean.`, name);
152
+ }
153
+ const allowed = p.values ?? p.enum;
154
+ if (allowed && !allowed.some(candidate => candidate === value))
155
+ fail('invalid_quote_parameter', `Pricing parameter ${name} is not an allowed value.`, name);
156
+ parameters[name] = value;
157
+ }
158
+ return parameters;
159
+ }
160
+ function decimalFraction(value) {
161
+ const negative = value.startsWith('-');
162
+ const [mantissa, exponent = '0'] = (negative ? value.slice(1) : value).toLowerCase().split('e');
163
+ const [whole, part = ''] = mantissa.split('.');
164
+ const scale = part.length - Number(exponent);
165
+ const numerator = (negative ? -1n : 1n) * BigInt(whole + part);
166
+ return scale >= 0 ? [numerator, 10n ** BigInt(scale)] : [numerator * 10n ** BigInt(-scale), 1n];
167
+ }
168
+ export function compareDecimal(left, right) {
169
+ const [l, ld] = decimalFraction(left), [r, rd] = decimalFraction(right);
170
+ return l * rd < r * ld ? -1 : l * rd > r * ld ? 1 : 0;
171
+ }
172
+ export function validateAccountQuote(raw, request, now = Date.now()) {
173
+ const parsed = AccountQuoteSchema.safeParse(raw);
174
+ if (!parsed.success)
175
+ fail('invalid_account_quote', 'The account quote response is incomplete or invalid.');
176
+ const quote = parsed.data;
177
+ if (quote.model_id !== request.model_id || quote.operation !== request.operation)
178
+ fail('mismatched_account_quote', 'The account quote belongs to a different model or operation.');
179
+ if (Date.parse(quote.expires_at) <= now)
180
+ fail('expired_account_quote', 'The account quote has expired. Request a fresh quote.');
181
+ if (!/^\d+$/.test(quote.amounts.uc) || !Number.isSafeInteger(Number(quote.amounts.uc))
182
+ || compareDecimal(quote.amount, quote.amounts.usd) !== 0)
183
+ fail('invalid_account_quote', 'The account quote has inconsistent amounts.');
184
+ let total = 0n;
185
+ const ids = new Set();
186
+ for (const item of quote.components) {
187
+ if (ids.has(item.id) || !/^\d+$/.test(item.subtotal_amounts.uc)
188
+ || compareDecimal(item.subtotal, item.subtotal_amounts.usd) !== 0
189
+ || compareDecimal(item.unit_price, item.unit_price_amounts.usd) !== 0) {
190
+ fail('invalid_account_quote', 'The account quote component amounts are inconsistent.');
191
+ }
192
+ ids.add(item.id);
193
+ total += BigInt(item.subtotal_amounts.uc);
194
+ }
195
+ if (total !== BigInt(quote.amounts.uc))
196
+ fail('invalid_account_quote', 'The account quote components do not sum to its total.');
197
+ return quote;
198
+ }
199
+ export async function createAccountQuote(config, entry, input, options = {}) {
200
+ const { body } = await getPricingRules({ model: entry.id.toLowerCase(), view: 'full' }, { fresh: true });
201
+ const rule = 'model' in body ? body.model : body.models[0];
202
+ if (!rule || rule.modality !== entry.kind || rule.policy_source !== 'published' || rule.pricing_status !== 'available') {
203
+ fail('account_quote_unavailable', 'This model has no available published media pricing policy.');
204
+ }
205
+ const parameters = prepareQuoteParameters(rule, entry, input, options.pricingParameters, options.mediaSeconds);
206
+ const request = { model_id: rule.model_id, operation: rule.operation, parameters, expected_usage: {} };
207
+ const quote = validateAccountQuote(await requestAccountQuote(config, request), request);
208
+ if (quote.policy_version !== rule.policy_version || quote.policy_checksum !== rule.policy_checksum
209
+ || quote.product_id !== rule.product_id || quote.settlement_basis !== rule.settlement_basis) {
210
+ fail('quote_policy_changed', 'The published policy changed while quoting. Request another quote.');
211
+ }
212
+ for (const component of quote.components) {
213
+ const policyComponent = rule.components.find(item => item.id === component.id);
214
+ if (!policyComponent || policyComponent.role !== component.role || policyComponent.unit !== component.unit
215
+ || ![policyComponent.sku_id, ...policyComponent.tiers.map(item => item.sku_id)].includes(component.sku_id)) {
216
+ fail('mismatched_account_quote', 'The account quote components do not match the published policy.');
217
+ }
218
+ }
219
+ const approval = { quote, parameters,
220
+ request_hash: quoteRequestHash(entry.id, input, options.mediaSeconds, options.pricingParameters) };
221
+ return { quote, approval, estimate: accountCostEstimate(quote) };
222
+ }
223
+ export function accountCostEstimate(quote) {
224
+ return { status: 'estimated', min_usd: Number(quote.amount), max_usd: Number(quote.amount),
225
+ min_credits: Number(quote.amounts.credits), max_credits: Number(quote.amounts.credits),
226
+ basis: ['Authenticated account Quote using the published policy.'], possible_extras: [],
227
+ notes: [quote.settlement_basis === 'request_only'
228
+ ? 'Estimated for the requested settings; the task reports the final charge when it finishes.'
229
+ : 'Final cost depends on actual billed usage and may differ from this estimate.'] };
230
+ }
231
+ export function checkApprovedAccountQuote(approval, model, input, mediaSeconds, pricingParameters, cap) {
232
+ const quote = validateAccountQuote(approval.quote, { model_id: model.toLowerCase(), operation: approval.quote.operation });
233
+ if (approval.request_hash !== quoteRequestHash(model, input, mediaSeconds, pricingParameters)) {
234
+ fail('quote_input_changed', 'The generation input differs from the approved account quote. Request a new quote.');
235
+ }
236
+ if (cap !== undefined && compareDecimal(quote.amount, String(cap)) > 0)
237
+ fail('cost_exceeds_cap', 'The account estimate exceeds max_cost_usd.');
238
+ return quote;
239
+ }
@@ -0,0 +1,222 @@
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 { currentRequestCredentials } from '../request-context.js';
5
+ import { controlBaseURL } from './pricing-client.js';
6
+ import { DEFAULT_READ_TIMEOUT_MS, evoHeaders, fetchWithTimeout, timeoutFromEnv } from './http-policy.js';
7
+ const MAX_BODY_BYTES = 2 * 1024 * 1024;
8
+ const MAX_CACHE_ENTRIES = 64;
9
+ const CACHE_TTL_MS = 60_000;
10
+ // Media policies nest arrays and lookup keys around their expressions. Keep
11
+ // bounded JSON traversal while allowing the published schema's deeper trees.
12
+ const MAX_JSON_DEPTH = 64;
13
+ const decimal = z.string().max(64).regex(/^(?:0|[1-9]\d*)(?:\.\d+)?$/);
14
+ const signedDecimal = z.string().max(64).regex(/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/);
15
+ const identifier = (max) => z.string().trim().max(max).regex(/^[a-z0-9][a-z0-9._:-]*$/);
16
+ const optionalFilter = (schema) => z.preprocess(value => typeof value === 'string' && value.trim() === '' ? undefined : value, schema.optional());
17
+ export const PricingRulesQuery = z.object({
18
+ model: optionalFilter(identifier(100)), product_id: optionalFilter(identifier(100)),
19
+ operation: optionalFilter(z.string().trim().toLowerCase().pipe(identifier(50))),
20
+ modality: optionalFilter(z.string().trim().toLowerCase().pipe(z.enum(['text', 'image', 'video', 'audio']))),
21
+ lifecycle: optionalFilter(z.string().trim().toLowerCase().pipe(z.enum(['active', 'preview', 'deprecated']))),
22
+ view: z.preprocess(value => typeof value === 'string' && value.trim() === '' ? undefined : value, z.string().trim().toLowerCase().pipe(z.enum(['summary', 'full'])).default('full')),
23
+ }).strict();
24
+ // Preserve decimal strings. Do not sum display USD floats or infer a bill.
25
+ function fraction(value) {
26
+ const [whole, part = ''] = value.split('.');
27
+ return [BigInt(whole + part), 10n ** BigInt(part.length)];
28
+ }
29
+ export const PricingMoney = z.object({ uc: decimal, credits: decimal, cny: decimal, usd: decimal })
30
+ .refine(value => {
31
+ // Live configuration rates can contain fractional UC (e.g. 1102.5),
32
+ // although the initial HTML describes UC as an integer. Settlement
33
+ // rounding belongs to the server; never truncate configuration amounts.
34
+ if (!Object.values(value).every(part => typeof part === 'string' && /^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(part)))
35
+ return false;
36
+ const [uc, udc] = fraction(value.uc), [credits, cd] = fraction(value.credits), [cny, yd] = fraction(value.cny), [usd, ud] = fraction(value.usd);
37
+ const delta = usd * 680000n * udc - uc * ud;
38
+ return credits * 10000n * udc === uc * cd && cny * 100000n * udc === uc * yd
39
+ && (delta < 0n ? -delta : delta) * 100000000n <= 680000n * ud * udc;
40
+ }, 'Currency fields must represent the same UC amount.');
41
+ const LookupValues = z.record(z.string().min(1).max(100), signedDecimal)
42
+ .refine(values => Object.keys(values).length > 0 && Object.keys(values).length <= 100, 'Lookup tables must contain between 1 and 100 entries.');
43
+ const ExpressionSchema = z.lazy(() => z.object({
44
+ op: z.string().min(1).max(40), name: z.string().max(100).optional(), value: z.string().max(128).optional(),
45
+ args: z.array(ExpressionSchema).max(32).optional(),
46
+ key: ExpressionSchema.optional(), values: LookupValues.optional(),
47
+ }).refine(node => node.op !== 'lookup' || (node.key !== undefined && node.values !== undefined), 'Lookup expressions require a key and a values table.'));
48
+ const Rounding = z.object({ point: z.string().max(80), mode: z.string().max(40) });
49
+ const rateFields = {
50
+ sku_id: z.string().min(1).max(100), rate: PricingMoney, official_rate: PricingMoney.optional(), minimum_charge: PricingMoney,
51
+ billing_rule: z.string().min(1).max(60), pricing_status: z.enum(['available', 'unavailable']),
52
+ effective_at: z.string().datetime({ offset: true }),
53
+ };
54
+ const Tier = z.object({ ...rateFields, multiplier: decimal.refine(value => /^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(value)
55
+ && fraction(value)[0] > 0n), when: ExpressionSchema.optional() });
56
+ const Component = z.object({ ...rateFields, id: z.string().min(1).max(100), role: z.string().min(1).max(100),
57
+ label_key: z.string().min(1).max(100).optional(),
58
+ dimension: z.string().min(1).max(100), unit: z.string().min(1).max(100),
59
+ billing_unit_size: z.number().int().positive().max(1_000_000_000), display_unit_size: z.number().int().positive().max(1_000_000_000),
60
+ condition: ExpressionSchema.optional(), quantity_rule: ExpressionSchema.optional(), rounding: Rounding.optional(),
61
+ tiers: z.array(Tier).max(100),
62
+ });
63
+ const Parameter = z.object({ name: z.string().min(1).max(100), type: z.string().min(1).max(60),
64
+ required: z.boolean().optional(), default: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),
65
+ enum: z.array(z.union([z.string(), z.number(), z.boolean()])).max(100).optional(),
66
+ values: z.array(z.union([z.string(), z.number(), z.boolean()])).max(100).optional(),
67
+ description: z.string().max(2000).optional(), minimum: signedDecimal.optional(), maximum: signedDecimal.optional(),
68
+ });
69
+ const Model = z.object({
70
+ model_id: identifier(100), product_id: identifier(100), operation: identifier(50),
71
+ modality: z.enum(['text', 'image', 'video', 'audio']), lifecycle: z.enum(['active', 'preview', 'deprecated']),
72
+ pricing_status: z.enum(['available', 'unavailable']), settlement_basis: z.string().min(1).max(100),
73
+ policy_version: z.number().int().nonnegative(), policy_checksum: z.string().regex(/^[a-f0-9]{64}$/),
74
+ policy_source: z.enum(['published', 'legacy_text_adapter']), parameters: z.array(Parameter).max(100).optional(),
75
+ components: z.array(Component).min(1).max(200),
76
+ });
77
+ const Meta = z.object({ schema_version: z.literal('2'), catalog_version: z.string().min(1).max(128),
78
+ pricing_version: z.string().min(1).max(128), price_scope: z.literal('public_default'), currency: z.literal('USD'),
79
+ price_selection: z.enum(['configured_minimum', 'route_priority']).optional(),
80
+ exchange_rate_version: z.literal('pricing-fx/v1:USD-CNY=6.8'),
81
+ updated_at: z.string().datetime({ offset: true }), fresh_until: z.string().datetime({ offset: true }),
82
+ });
83
+ const List = z.object({ meta: Meta, models: z.array(Model).max(1000) });
84
+ const Single = z.object({ meta: Meta, model: Model });
85
+ const cache = new Map();
86
+ const pending = new Map();
87
+ export class PricingRulesError extends Error {
88
+ code;
89
+ status;
90
+ retryAfter;
91
+ constructor(code, status = 0, retryAfter) {
92
+ super('Public pricing rules are unavailable or invalid. No quote or spending limit was established.');
93
+ this.code = code;
94
+ this.status = status;
95
+ this.retryAfter = retryAfter;
96
+ }
97
+ }
98
+ function bounded(value, depth = 0, budget = { nodes: 0 }) {
99
+ if (depth > MAX_JSON_DEPTH || ++budget.nodes > 100_000)
100
+ return false;
101
+ if (Array.isArray(value))
102
+ return value.every(item => bounded(item, depth + 1, budget));
103
+ if (value && typeof value === 'object')
104
+ return Object.values(value).every(item => bounded(item, depth + 1, budget));
105
+ return true;
106
+ }
107
+ export function validatePricingRules(body, single) {
108
+ if (!bounded(body))
109
+ throw new PricingRulesError('invalid_pricing_rules');
110
+ const parsed = (single ? Single : List).safeParse(body);
111
+ if (!parsed.success)
112
+ throw new PricingRulesError('invalid_pricing_rules');
113
+ if (Date.parse(parsed.data.meta.fresh_until) <= Date.now())
114
+ throw new PricingRulesError('expired_pricing_rules');
115
+ return parsed.data;
116
+ }
117
+ async function readBody(response) {
118
+ if (!response.body)
119
+ throw new PricingRulesError('invalid_pricing_rules');
120
+ const reader = response.body.getReader(), chunks = [];
121
+ let size = 0;
122
+ let rejectRead;
123
+ const stopped = new Promise((_resolve, reject) => { rejectRead = reject; });
124
+ const stop = (code) => { rejectRead(new PricingRulesError(code)); void reader.cancel().catch(() => { }); };
125
+ const timer = setTimeout(() => stop('pricing_rules_timeout'), timeoutFromEnv('EVOLINK_MCP_READ_TIMEOUT_MS', DEFAULT_READ_TIMEOUT_MS));
126
+ const signal = currentRequestCredentials()?.http?.signal;
127
+ const abort = () => stop('interrupted');
128
+ signal?.addEventListener('abort', abort, { once: true });
129
+ if (signal?.aborted)
130
+ abort();
131
+ try {
132
+ while (true) {
133
+ const { done, value } = await Promise.race([reader.read(), stopped]);
134
+ if (done)
135
+ break;
136
+ size += value.byteLength;
137
+ if (size > MAX_BODY_BYTES)
138
+ throw new PricingRulesError('pricing_rules_too_large');
139
+ chunks.push(value);
140
+ }
141
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
142
+ }
143
+ catch (error) {
144
+ await reader.cancel().catch(() => { });
145
+ if (error instanceof PricingRulesError)
146
+ throw error;
147
+ throw new PricingRulesError('invalid_pricing_rules');
148
+ }
149
+ finally {
150
+ clearTimeout(timer);
151
+ signal?.removeEventListener('abort', abort);
152
+ reader.releaseLock();
153
+ }
154
+ }
155
+ export async function getPricingRules(input, options = {}) {
156
+ const query = PricingRulesQuery.parse(input), base = controlBaseURL();
157
+ const url = new URL(query.model ? `${base}/v1/catalog/models/${encodeURIComponent(query.model)}/pricing-rules`
158
+ : `${base}/v1/catalog/pricing-rules`);
159
+ for (const key of ['product_id', 'operation', 'modality', 'lifecycle', 'view']) {
160
+ if (query[key] !== undefined)
161
+ url.searchParams.set(key, query[key]);
162
+ }
163
+ const key = url.href, old = cache.get(key);
164
+ if (!options.fresh && old && old.expires > Date.now())
165
+ return { body: old.body, source: 'cache' };
166
+ const existing = pending.get(key);
167
+ if (existing)
168
+ return existing;
169
+ const task = (async () => {
170
+ let conditional = Boolean(old?.etag);
171
+ for (let attempt = 0; attempt < 2; attempt++) {
172
+ const response = await fetchWithTimeout(key, { method: 'GET', redirect: 'error',
173
+ headers: { Accept: 'application/json', 'Cache-Control': 'no-cache', ...evoHeaders('get_pricing_rules'),
174
+ ...(conditional ? { 'If-None-Match': old.etag } : {}) },
175
+ }, timeoutFromEnv('EVOLINK_MCP_READ_TIMEOUT_MS', DEFAULT_READ_TIMEOUT_MS));
176
+ if (response.status === 304) {
177
+ if (!conditional || !old)
178
+ throw new PricingRulesError('invalid_pricing_rules', 304);
179
+ if (Date.parse(old.body.meta.fresh_until) <= Date.now()) {
180
+ conditional = false;
181
+ continue;
182
+ }
183
+ old.expires = Math.min(Date.now() + CACHE_TTL_MS, Date.parse(old.body.meta.fresh_until));
184
+ return { body: old.body, source: 'revalidated' };
185
+ }
186
+ if (!response.ok) {
187
+ const status = response.status;
188
+ await response.body?.cancel();
189
+ throw new PricingRulesError(status === 404 ? 'not_found' : status === 429 ? 'rate_limit_exceeded'
190
+ : status === 503 ? 'pricing_rules_unavailable' : 'pricing_rules_http_error', status, status === 429 ? retryAfterSeconds(response.headers.get('Retry-After')) : undefined);
191
+ }
192
+ const body = validatePricingRules(await readBody(response), Boolean(query.model));
193
+ const models = 'model' in body ? [body.model] : body.models;
194
+ if (models.some(model => (query.model && model.model_id !== query.model)
195
+ || (query.product_id && model.product_id !== query.product_id) || (query.operation && model.operation !== query.operation)
196
+ || (query.modality && model.modality !== query.modality) || (query.lifecycle && model.lifecycle !== query.lifecycle))) {
197
+ throw new PricingRulesError('mismatched_pricing_rules');
198
+ }
199
+ if (query.view === 'full' && models.some(model => model.components.some(component => !component.quantity_rule || !component.rounding
200
+ || component.tiers.some(tier => !tier.when))))
201
+ throw new PricingRulesError('incomplete_pricing_rules');
202
+ if (cache.size >= MAX_CACHE_ENTRIES)
203
+ cache.delete(cache.keys().next().value);
204
+ cache.set(key, { body, etag: response.headers.get('ETag') ?? undefined,
205
+ expires: Math.min(Date.now() + CACHE_TTL_MS, Date.parse(body.meta.fresh_until)) });
206
+ return { body, source: 'live' };
207
+ }
208
+ throw new PricingRulesError('expired_pricing_rules');
209
+ })().finally(() => pending.delete(key));
210
+ pending.set(key, task);
211
+ return task;
212
+ }
213
+ export function resetPricingRulesCacheForTests() { cache.clear(); pending.clear(); }
214
+ function retryAfterSeconds(value) {
215
+ if (!value)
216
+ return undefined;
217
+ const seconds = Number(value);
218
+ if (Number.isFinite(seconds) && seconds >= 0)
219
+ return Math.ceil(seconds);
220
+ const until = Date.parse(value);
221
+ return Number.isFinite(until) ? Math.max(0, Math.ceil((until - Date.now()) / 1000)) : undefined;
222
+ }