@evolinkai/cli 0.12.0 → 0.14.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 (35) hide show
  1. package/README.md +20 -6
  2. package/package.json +2 -2
  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 +148 -37
  10. package/src/platform/core/src/data/model-constraints.js +13 -1
  11. package/src/platform/core/src/data/model-params.overrides.generated.js +1 -1
  12. package/src/platform/core/src/platform-operations.js +1 -1
  13. package/src/platform/core/src/services/api-client.js +1 -1
  14. package/src/platform/core/src/services/batch-generation.js +117 -0
  15. package/src/platform/core/src/services/catalog-client.js +28 -2
  16. package/src/platform/core/src/services/gpt-image-tokens.js +264 -0
  17. package/src/platform/core/src/services/mj-prompt.js +18 -0
  18. package/src/platform/core/src/services/model-capabilities.js +2 -1
  19. package/src/platform/core/src/services/omni-tokens.js +245 -0
  20. package/src/platform/core/src/services/param-validator.js +48 -1
  21. package/src/platform/core/src/services/pricing-call-limit.js +40 -0
  22. package/src/platform/core/src/services/pricing-derived.js +59 -0
  23. package/src/platform/core/src/services/pricing-quote-client.js +30 -7
  24. package/src/platform/core/src/services/pricing-rules-client.js +56 -3
  25. package/src/platform/core/src/services/pricing-rules-estimate.js +376 -59
  26. package/src/platform/core/src/tool-guidance.js +25 -2
  27. package/src/platform/core/src/tools/estimate-cost.js +220 -63
  28. package/src/platform/core/src/tools/generate.js +505 -71
  29. package/src/platform/core/src/tools/get-model.js +28 -0
  30. package/src/platform/core/src/tools/get-pricing-rules.js +15 -5
  31. package/src/platform/core/src/tools/search-models.js +4 -1
  32. package/src/platform/core/src/tools/shared.js +5 -1
  33. package/src/platform/core/src/version.js +1 -1
  34. package/src/platform/source.json +54 -42
  35. package/src/state.mjs +12 -1
@@ -0,0 +1,245 @@
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
+ import { CJK } from './gpt-image-tokens.js';
5
+ const TIERS = ['360p', '720p', '1080p', '4k'];
6
+ /** Video tokens per second by resolution (1.1 and 1.2), for the output and for input and reference videos alike. */
7
+ const RATE = { '360p': 1931, '720p': 5792, '1080p': 8688, '4k': 17376 };
8
+ /** Reserved for each input image, and for the other output (text and thinking) of every task except an upscale. */
9
+ export const OMNI_IMAGE_TOKENS = 2020, OMNI_OTHER_OUTPUT_TOKENS = 1000;
10
+ /** The resolution the gateway reserves at when it cannot read an input video's, and the one MCP counts. */
11
+ export const OMNI_UNREAD_TIER = '4k';
12
+ const DEFAULT_TIER = '720p';
13
+ /** 1.0 (gemini-omni-flash-*): one 720p output rate, a fixed input video rate, outputs of 3–10 seconds, 10 by default. */
14
+ const V10 = { output: 5792, inputVideo: 5760, defaultSeconds: 10, minSeconds: 3, maxSeconds: 10, maxInputSeconds: 10 };
15
+ /** 1.2 upscale output tokens per second, by source and target resolution; an upscale bills nothing else. */
16
+ const UPSCALE = { '360p>720p': 2896, '720p>1080p': 2896, '360p>1080p': 5792, '720p>4k': 11584, '1080p>4k': 11584 };
17
+ const G11 = { label: '1.1', maxOutput: 10, maxFrameOutput: 10, maxExtend: 10,
18
+ maxInput: { edit: 10, extend: 30, reference: 10, upscale: 10 }, referenceVideosAboveTen: 0, maxVideoOutputTokens: 17376 * 10 };
19
+ const G12 = { label: '1.2', maxOutput: 15, maxFrameOutput: 10, maxExtend: 10,
20
+ maxInput: { edit: 15, extend: 30, reference: 10, upscale: 15 }, referenceVideosAboveTen: 1, maxVideoOutputTokens: 17376 * 15 };
21
+ const ROUTES = { 'text-to-video': 'text', 'image-to-video': 'image', 'reference-to-video': 'reference',
22
+ 'video-edit': 'edit', 'video-extend': 'extend', 'video-upscale': 'upscale' };
23
+ function omniModel(model) {
24
+ const match = /^gemini-omni-(?:(1\.[12])-)?flash-([a-z-]+)$/.exec(model.trim().toLowerCase());
25
+ const route = match ? ROUTES[match[2]] : undefined;
26
+ if (!match || !route)
27
+ return undefined;
28
+ if (!match[1])
29
+ return ['text', 'image', 'reference', 'edit'].includes(route) ? { route } : undefined;
30
+ if (match[1] === '1.1' && route === 'upscale')
31
+ return undefined;
32
+ return { generation: match[1] === '1.1' ? G11 : G12, route };
33
+ }
34
+ /** Gemini Omni Flash video models (1.0, 1.1 and 1.2), which the gateway reserves and bills by token counts. */
35
+ export const isOmniTokenModel = (model) => omniModel(model) !== undefined;
36
+ // Hundredths of a token per character, by class, for the gpt-4 encoding the gateway counts Omni prompts with. Calibrated
37
+ // on 11-07 against the gateway's counts (scripts/omni-reservation): typical prompts come out 0.8 to 1.8 times the exact
38
+ // count, most a little above it.
39
+ const LETTER = 22, DIGIT_OR_MARK = 85, CJK_CHARACTER = 160, OTHER_SCRIPT = 95, ASTRAL = 375;
40
+ /**
41
+ * Prompt tokens, approximately: the gateway counts them with the gpt-4 encoding, which this package does not ship.
42
+ * Prompt tokens are a small part of a video's price, and the task settles at the count the upstream reports.
43
+ */
44
+ export function approximateOmniPromptTokens(prompt) {
45
+ let hundredths = 0;
46
+ for (const character of prompt) {
47
+ const code = character.codePointAt(0);
48
+ hundredths += code < 0x80 ? /[A-Za-z\s]/.test(character) ? LETTER : DIGIT_OR_MARK
49
+ : code > 0xffff ? ASTRAL : CJK.test(character) ? CJK_CHARACTER : OTHER_SCRIPT;
50
+ }
51
+ return Math.ceil(hundredths / 100);
52
+ }
53
+ function invalid(param, message) { throw new QuoteError('invalid_quote_parameter', message, param); }
54
+ const textOf = (value) => typeof value === 'string' ? value : '';
55
+ /** parseFlexibleStringArray: one string or a list; empty and non-string entries do not count. */
56
+ const flexible = (value) => typeof value === 'string' ? value === '' ? [] : [value]
57
+ : Array.isArray(value) ? value.filter((item) => typeof item === 'string' && item !== '') : [];
58
+ /** dedupeNonEmptyImageURLs: trimmed, without blanks or repeats, in order. */
59
+ const dedupe = (values) => [...new Set(values.map(value => value.trim()).filter(Boolean))];
60
+ const isHTTP = (url) => /^https?:\/\//i.test(url.trim());
61
+ /** 1.0 reads every image and video field and keeps repeats (getGeminiOmniImageInputs / getGeminiOmniVideoInputs). */
62
+ function media10(input, list, single, legacy) {
63
+ const one = textOf(input[legacy]);
64
+ return [...flexible(input[list]), ...flexible(input[single]), ...(one.trim() !== '' ? [one] : [])];
65
+ }
66
+ /** 1.1 and 1.2: image_urls with image_url, else image_start and image_end, else image; repeats count once. */
67
+ function images11(input) {
68
+ const modern = dedupe([...flexible(input.image_urls), ...flexible(input.image_url)]);
69
+ if (modern.length)
70
+ return modern;
71
+ const frames = dedupe([textOf(input.image_start), textOf(input.image_end)]);
72
+ return frames.length ? frames : dedupe([textOf(input.image)]);
73
+ }
74
+ function videos11(input) {
75
+ const modern = dedupe([...flexible(input.video_urls), ...flexible(input.video_url)]);
76
+ return modern.length ? modern : dedupe([textOf(input.video)]);
77
+ }
78
+ /** An integer duration as given; "auto" and absence are 0, which each route reads as its default. */
79
+ const durationOf = (value) => typeof value === 'number' && Number.isInteger(value) ? value : 0;
80
+ /** clampOmniSeconds: 0 is the default of 3 seconds; otherwise 3 to the route's maximum. */
81
+ const clampSeconds = (seconds, max) => seconds <= 0 ? 3 : Math.min(Math.max(seconds, 3), max);
82
+ /** The input seconds the gateway counts: rounded up, at most the route's longest input. */
83
+ const wholeSeconds = (seconds, max) => { const whole = Math.ceil(seconds); return whole <= 0 || whole > max ? max : whole; };
84
+ const upscaleMax = (target) => Math.max(0, ...Object.entries(UPSCALE).filter(([pair]) => pair.endsWith(`>${target}`)).map(([, rate]) => rate));
85
+ /** The source resolution that bills the most for an upscale target, as the gateway reserves when it cannot read the size. */
86
+ const upscaleSource = (target) => TIERS.find(tier => UPSCALE[`${tier}>${target}`] === upscaleMax(target));
87
+ function checkLength(mediaSeconds, max, what, model) {
88
+ if (mediaSeconds > max)
89
+ invalid('media_seconds', `${what} must be ${max} seconds or shorter for ${model}; media_seconds is ${mediaSeconds}.`);
90
+ }
91
+ function requirePrompt(input, model) {
92
+ const prompt = textOf(input.prompt);
93
+ if (prompt.trim() === '')
94
+ invalid('prompt', `prompt is required for ${model}.`);
95
+ return prompt;
96
+ }
97
+ /**
98
+ * The tokens the gateway reserves at submission for this input, or the length it needs first. inputTier counts the input
99
+ * and reference videos at that resolution instead of the highest (for the price of a lower-resolution input).
100
+ * countPromptTokens replaces the approximate prompt count when the gateway's exact count is known.
101
+ */
102
+ export function omniReservation(model, input, mediaSeconds, options = {}) {
103
+ const id = model.trim().toLowerCase(), found = omniModel(id) ?? invalid('model', `${model} is not a Gemini Omni Flash model.`);
104
+ const count = options.countPromptTokens ?? approximateOmniPromptTokens, route = found.route, g = found.generation;
105
+ const tokensOf = (prompt) => prompt === '' ? 0 : count(prompt);
106
+ if (!g)
107
+ return reservation10(id, route, input, mediaSeconds, tokensOf);
108
+ const images = images11(input), videos = videos11(input);
109
+ // validateGeminiOmni11FrameParams and validateGeminiOmni11MediaCounts: the media each route takes.
110
+ const start = textOf(input.image_start).trim(), end = textOf(input.image_end).trim();
111
+ if (start || end) {
112
+ if (route !== 'image')
113
+ invalid('image_start', `image_start and image_end are only for gemini-omni-${g.label}-flash-image-to-video.`);
114
+ if (end && !start)
115
+ invalid('image_end', 'image_end needs image_start: a last frame only is not supported.');
116
+ }
117
+ const duration = durationOf(input.duration);
118
+ if (route === 'text' && (images.length || videos.length))
119
+ invalid('image_urls', `${id} takes no image or video input.`);
120
+ if (route === 'image') {
121
+ if (images.length < 1 || images.length > 2)
122
+ invalid('image_urls', `${id} takes 1 or 2 images (a first frame, then a last frame), got ${images.length}.`);
123
+ if (videos.length)
124
+ invalid('video_urls', `${id} takes no video input.`);
125
+ if (images.length === 2 && duration > g.maxFrameOutput)
126
+ invalid('duration', `first and last frame generation supports up to ${g.maxFrameOutput} seconds on ${id}, got ${duration}.`);
127
+ }
128
+ if (route === 'reference') {
129
+ if (images.length < 1)
130
+ invalid('image_urls', `${id} needs at least 1 image.`);
131
+ if (g.referenceVideosAboveTen && duration > 10 && videos.length > g.referenceVideosAboveTen) {
132
+ invalid('video_urls', `${id} takes at most ${g.referenceVideosAboveTen} reference video when duration is longer than 10 seconds, got ${videos.length}.`);
133
+ }
134
+ }
135
+ if (route === 'upscale' && images.length)
136
+ invalid('image_urls', `${id} takes no image input.`);
137
+ if (['edit', 'extend', 'upscale'].includes(route)) {
138
+ if (videos.length !== 1)
139
+ invalid('video_urls', `${id} takes exactly 1 video, got ${videos.length}.`);
140
+ if (!isHTTP(videos[0]))
141
+ invalid('video_urls', `${id} takes the video as an http(s) URL.`);
142
+ }
143
+ // An upscale takes no prompt; the gateway drops one.
144
+ const prompt = route === 'upscale' ? '' : requirePrompt(input, id);
145
+ const quality = textOf(input.quality).trim().toLowerCase();
146
+ const follows = (route === 'edit' || route === 'extend') && (quality === '' || quality === 'auto');
147
+ if (quality !== '' && !follows && !TIERS.includes(quality))
148
+ invalid('quality', `quality ${input.quality} is not supported by ${id}.`);
149
+ if (route === 'upscale' && (quality === '' || quality === '360p'))
150
+ invalid('quality', `quality on ${id} is the target resolution: 720p, 1080p or 4k.`);
151
+ const tier = (quality === '' || quality === 'auto' ? DEFAULT_TIER : quality);
152
+ // Input and reference videos: the gateway reads their length at submission and refuses one that is too long.
153
+ let input_videos;
154
+ if (videos.length) {
155
+ if (mediaSeconds === undefined)
156
+ return { needs: 'media_seconds', videos: videos.length };
157
+ const max = g.maxInput[route] ?? g.maxInput.edit;
158
+ checkLength(mediaSeconds, max, videos.length > 1 ? 'each reference video' : 'the input video', id);
159
+ const resolution = options.inputTier ?? OMNI_UNREAD_TIER;
160
+ input_videos = { count: videos.length, seconds: wholeSeconds(mediaSeconds, max), resolution, resolution_assumed: options.inputTier === undefined };
161
+ }
162
+ const cap = (tokens) => Math.min(tokens, g.maxVideoOutputTokens);
163
+ // omniInputVideoTokens: each video's seconds at its own rate or the output's, whichever is higher.
164
+ const videoTokens = (output) => input_videos ? input_videos.count * input_videos.seconds * Math.max(RATE[input_videos.resolution], RATE[output]) : 0;
165
+ const promptTokens = tokensOf(prompt), imageTokens = images.length * OMNI_IMAGE_TOKENS;
166
+ const base = { generation: g.label, prompt_tokens: promptTokens, images: images.length, ...(input_videos ? { input_videos } : {}) };
167
+ switch (route) {
168
+ case 'upscale': {
169
+ const target = quality, source = options.inputTier ?? upscaleSource(target);
170
+ const rate = UPSCALE[`${source}>${target}`];
171
+ if (rate === undefined)
172
+ invalid('quality', `${id} cannot upscale ${source} to ${target}; supported: 360p to 720p or 1080p, 720p to 1080p or 4k, 1080p to 4k.`);
173
+ return { ...base, route, prompt_tokens: 0, output: { resolution: target, seconds: input_videos.seconds },
174
+ upscale: { target, source, source_assumed: options.inputTier === undefined, tokens_per_second: rate },
175
+ tokens: { input_tokens: 0, video_output_tokens: cap(rate * input_videos.seconds), other_output_tokens: 0 } };
176
+ }
177
+ case 'edit':
178
+ case 'extend': {
179
+ const output = follows ? input_videos.resolution : tier;
180
+ const seconds = route === 'edit' ? input_videos.seconds : clampSeconds(duration, g.maxExtend);
181
+ return { ...base, route, output: { resolution: output, seconds, ...(follows ? { follows_input: true } : {}) },
182
+ tokens: { input_tokens: promptTokens + imageTokens + videoTokens(output), video_output_tokens: cap(RATE[output] * seconds),
183
+ other_output_tokens: OMNI_OTHER_OUTPUT_TOKENS } };
184
+ }
185
+ default: {
186
+ const seconds = clampSeconds(duration, g.maxOutput);
187
+ return { ...base, route, output: { resolution: tier, seconds },
188
+ tokens: { input_tokens: promptTokens + (route === 'text' ? 0 : imageTokens) + (route === 'reference' ? videoTokens(tier) : 0),
189
+ video_output_tokens: cap(RATE[tier] * seconds), other_output_tokens: OMNI_OTHER_OUTPUT_TOKENS } };
190
+ }
191
+ }
192
+ }
193
+ /** EstimateGeminiOmniPreCharge, for 1.0: one 720p rate; an edit's output counts 10 seconds whatever its input. */
194
+ function reservation10(id, route, input, mediaSeconds, tokensOf) {
195
+ const images = media10(input, 'image_urls', 'image_url', 'image'), videos = media10(input, 'video_urls', 'video_url', 'video');
196
+ // validateGeminiOmniFlashRequest: no resolution or frame fields, an edit takes no duration, and the media each route takes.
197
+ if (textOf(input.quality) !== '')
198
+ invalid('quality', `quality is not supported by ${id}.`);
199
+ if (textOf(input.image_start) !== '' || textOf(input.image_end) !== '')
200
+ invalid('image_start', `image_start and image_end are not supported by ${id}; use image_urls.`);
201
+ if (route === 'edit' && (durationOf(input.duration) !== 0 || input.duration === 'auto'))
202
+ invalid('duration', `duration is not supported by ${id}.`);
203
+ if (route === 'text' && (images.length || videos.length))
204
+ invalid('image_urls', `${id} takes no image or video input.`);
205
+ if (route === 'image' && images.length !== 1)
206
+ invalid('image_urls', `${id} takes exactly 1 image, got ${images.length}.`);
207
+ if (route === 'reference' && (images.length < 1 || images.length > 6))
208
+ invalid('image_urls', `${id} takes 1 to 6 images, got ${images.length}.`);
209
+ if ((route === 'image' || route === 'reference') && videos.length)
210
+ invalid('video_urls', `${id} takes no video input.`);
211
+ if (route === 'edit') {
212
+ if (images.length)
213
+ invalid('image_urls', `${id} takes no image input.`);
214
+ if (videos.length !== 1)
215
+ invalid('video_urls', `${id} takes exactly 1 video, got ${videos.length}.`);
216
+ if (!isHTTP(videos[0]))
217
+ invalid('video_urls', `${id} takes the video as an http(s) URL.`);
218
+ }
219
+ const prompt = requirePrompt(input, id), promptTokens = tokensOf(prompt);
220
+ let input_videos, inputTokens = promptTokens;
221
+ if (route === 'image' || route === 'reference')
222
+ inputTokens += images.length * OMNI_IMAGE_TOKENS;
223
+ if (route === 'edit') {
224
+ if (mediaSeconds === undefined)
225
+ return { needs: 'media_seconds', videos: 1 };
226
+ checkLength(mediaSeconds, V10.maxInputSeconds, 'the input video', id);
227
+ const seconds = wholeSeconds(mediaSeconds, V10.maxInputSeconds);
228
+ input_videos = { count: 1, seconds, resolution: DEFAULT_TIER, resolution_assumed: false };
229
+ inputTokens += seconds * V10.inputVideo;
230
+ }
231
+ const given = route === 'edit' ? 0 : durationOf(input.duration);
232
+ const seconds = given <= 0 ? V10.defaultSeconds : Math.min(Math.max(given, V10.minSeconds), V10.maxSeconds);
233
+ return { generation: '1.0', route, prompt_tokens: promptTokens, images: images.length, output: { resolution: DEFAULT_TIER, seconds },
234
+ ...(input_videos ? { input_videos } : {}),
235
+ tokens: { input_tokens: inputTokens, video_output_tokens: seconds * V10.output, other_output_tokens: OMNI_OTHER_OUTPUT_TOKENS } };
236
+ }
237
+ /** The lower-resolution input a reference price can also be given for: 720p, or for an upscale the cheaper source. */
238
+ export function omniLowerInputTier(reservation) {
239
+ if (reservation.upscale) {
240
+ const target = reservation.upscale.target;
241
+ const cheaper = TIERS.filter(tier => UPSCALE[`${tier}>${target}`] !== undefined && UPSCALE[`${tier}>${target}`] < reservation.upscale.tokens_per_second);
242
+ return reservation.upscale.source_assumed ? cheaper.at(-1) : undefined;
243
+ }
244
+ return reservation.input_videos?.resolution_assumed ? '720p' : undefined;
245
+ }
@@ -174,9 +174,44 @@ export function validateInput(spec, input) {
174
174
  if (present.length > 1)
175
175
  result.errors.push({ param: present.join(', '), problem: 'are mutually exclusive; pass only one reference type.' });
176
176
  }
177
+ // A documented condition: an input that matches its `if` must also meet its `then`.
178
+ for (const condition of spec.conditions ?? []) {
179
+ const meets = (name, limits) => {
180
+ const check = { errors: [], warnings: [] };
181
+ checkValue(name, limits, rest[name], check);
182
+ return check.errors.length === 0;
183
+ };
184
+ const matches = (condition.if.required ?? []).every(name => rest[name] !== undefined)
185
+ && Object.entries(condition.if.properties ?? {}).every(([name, limits]) => rest[name] === undefined || meets(name, limits));
186
+ if (!matches)
187
+ continue;
188
+ const then = { errors: [], warnings: [] };
189
+ for (const name of condition.then.required ?? [])
190
+ if (rest[name] === undefined)
191
+ then.errors.push({ param: name, problem: 'is required.' });
192
+ for (const [name, limits] of Object.entries(condition.then.properties ?? {}))
193
+ checkValue(name, limits, rest[name], then);
194
+ for (const issue of then.errors)
195
+ result.errors.push({ param: issue.param, problem: `${issue.problem.replace(/\.$/, '')} (documented condition: when ${conditionText(condition.if)}).` });
196
+ }
197
+ // A body documented as one of several shapes: the given parameters must fit one, with everything it requires.
198
+ if (spec.requestShapes?.length) {
199
+ const given = Object.keys(rest).filter(name => spec.params[name] && rest[name] !== undefined && rest[name] !== null && rest[name] !== '');
200
+ const fits = spec.requestShapes.some(shape => shape.required.every(name => given.includes(name)) && given.every(name => shape.params.includes(name)));
201
+ if (!fits)
202
+ result.errors.push({ param: given.join(', ') || 'input', problem: `must fit one of the documented request shapes: ${spec.requestShapes.map(shapeText).join('; or ')}.` });
203
+ }
177
204
  const size = spec.constraints?.imageSize;
178
205
  const value = size ? rest[size.param] : undefined;
179
- if (size && typeof value === 'string' && !size.allowed.includes(value)) {
206
+ const frames = size?.frames && rest.output_format === size.frames.outputFormat ? size.frames : undefined;
207
+ if (frames && typeof value === 'string' && value !== 'auto') {
208
+ const pixels = /^(\d+)[x×](\d+)$/.exec(value), width = Number(pixels?.[1]), height = Number(pixels?.[2]);
209
+ if (!pixels || width < frames.minEdge || height < frames.minEdge || width > frames.maxEdge || height > frames.maxEdge
210
+ || width % frames.step !== 0 || height % frames.step !== 0) {
211
+ result.errors.push({ param: size.param, problem: `with output_format ${frames.outputFormat} is each frame's size: auto, or WxH with edges ${frames.minEdge}–${frames.maxEdge} in multiples of ${frames.step}.` });
212
+ }
213
+ }
214
+ else if (size && typeof value === 'string' && !size.allowed.includes(value)) {
180
215
  const pixels = /^(\d+)[x×](\d+)$/.exec(value);
181
216
  if (!pixels || !size.allowPixels) {
182
217
  result.errors.push({ param: size.param, problem: `must be one of ${size.allowed.join(', ')}${size.allowPixels ? ', or a valid WxH pixel size' : ''}.` });
@@ -196,6 +231,18 @@ export function validateInput(spec, input) {
196
231
  }
197
232
  return result;
198
233
  }
234
+ /** One side of a documented condition in words, e.g. "image_urls minItems 2" or "duration minimum 11". */
235
+ export function conditionText(part) {
236
+ const limits = Object.entries(part.properties ?? {}).map(([name, limit]) => `${name} ${Object.entries(limit)
237
+ .filter(([key]) => key !== 'type' && key !== 'description').map(([key, value]) => `${key} ${show(value)}`).join(', ')}`.trim());
238
+ const present = (part.required ?? []).filter(name => !(part.properties ?? {})[name]).map(name => `${name} is given`);
239
+ return [...limits, ...present].join(' and ');
240
+ }
241
+ /** One request shape in words: what it requires, then what else it accepts. */
242
+ export function shapeText(shape) {
243
+ const optional = shape.params.filter(name => !shape.required.includes(name));
244
+ return `${shape.required.join(', ')}${optional.length ? ` (optional: ${optional.join(', ')})` : ''}`;
245
+ }
199
246
  export function formatIssues(issues) {
200
247
  return issues.map(issue => `- ${issue.param} ${issue.problem}`);
201
248
  }
@@ -0,0 +1,40 @@
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
+ const WINDOW_MS = 60_000;
5
+ const MAX_KEYS = 10_000;
6
+ const calls = new Map();
7
+ let clock = () => Date.now();
8
+ /**
9
+ * Price checks (estimate_cost, get_pricing_rules) that read the platform's pricing rules, per signed-in account, per
10
+ * minute and tool; one answered from rules read moments ago is not counted. The hosted service reaches the platform's
11
+ * per-IP catalog limit from one address for everyone, so one busy assistant must not use it up. A local server serves
12
+ * one user and is not limited here. EVOLINK_MCP_PRICING_CALLS_PER_MINUTE changes the number; 0 turns the limit off.
13
+ */
14
+ export function pricingCallsPerMinute() {
15
+ const raw = process.env.EVOLINK_MCP_PRICING_CALLS_PER_MINUTE;
16
+ const value = raw === undefined || raw.trim() === '' ? 30 : Number(raw);
17
+ return Number.isInteger(value) && value >= 0 && value <= 100_000 ? value : 30;
18
+ }
19
+ /** Counts one call. An account already at its limit is not counted; the result says when its oldest call leaves the window. */
20
+ export function pricingCallLimitReached(tool) {
21
+ const owner = currentRequestCredentials()?.uploadOwner, limit = pricingCallsPerMinute();
22
+ if (!owner || limit === 0)
23
+ return undefined;
24
+ const key = `${tool} ${owner}`, now = clock();
25
+ const recent = (calls.get(key) ?? []).filter(at => now - at < WINDOW_MS);
26
+ calls.delete(key);
27
+ if (recent.length >= limit) {
28
+ calls.set(key, recent);
29
+ return { limit, retryAfterSeconds: Math.max(1, Math.ceil((recent[0] + WINDOW_MS - now) / 1000)) };
30
+ }
31
+ calls.set(key, [...recent, now]);
32
+ // The least recently used account leaves first once the map is full.
33
+ if (calls.size > MAX_KEYS)
34
+ calls.delete(calls.keys().next().value);
35
+ return undefined;
36
+ }
37
+ export function resetPricingCallsForTests(now) {
38
+ calls.clear();
39
+ clock = now ?? (() => Date.now());
40
+ }
@@ -0,0 +1,59 @@
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
+ // Rule parameters the gateway derives from differently named request fields. Each mapping mirrors the gateway's
4
+ // pre-deduction code (GroAPI feat/task-microservice-split); without it the published default quotes the cheaper case.
5
+ const proTiers = { '1K': '1K', '1.5K': '1.5K', '2K': '2K' };
6
+ const proTier = (value) => typeof value === 'string' ? proTiers[value.trim().toUpperCase()] : undefined;
7
+ // service/multi_sku_billing_service.go seedDreamProOutputTierThresholdPixels. Every 1K and 1.5K ratio preset is
8
+ // below it and every 2K preset above it, so a ratio follows quality.
9
+ const SEEDREAM_PRO_2K_PIXELS = 2_610_000;
10
+ /** controller preprocessSeedream5ProParams, then service ResolveSeedDreamProOutput. */
11
+ function seedreamProTier(input) {
12
+ const size = typeof input.size === 'string' ? input.size.trim() : '';
13
+ if (size === '' || size === 'auto' || size.includes(':'))
14
+ return proTier(input.quality) ?? '1K';
15
+ const named = proTier(size);
16
+ if (named)
17
+ return named;
18
+ const pixels = /^(\d+)\s*x\s*(\d+)$/.exec(size.toLowerCase().replace(/\u00d7/g, 'x'));
19
+ return pixels && Number(pixels[1]) * Number(pixels[2]) > SEEDREAM_PRO_2K_PIXELS ? '2K' : '1K';
20
+ }
21
+ /** service/minimax_h3_models.go MiniMaxH3CountInputImages: first frame, last frame and references all count. */
22
+ function inputImageCount(input) {
23
+ const filled = (value) => typeof value === 'string' && value.trim() !== '';
24
+ return ['image_start', 'image_end'].filter(key => filled(input[key])).length
25
+ + (Array.isArray(input.image_urls) ? input.image_urls.filter(filled).length : 0);
26
+ }
27
+ const derived = {
28
+ 'doubao-seedream-5.0-pro output_images_2k': input => seedreamProTier(input) === '2K' ? 1 : 0,
29
+ 'doubao-seedream-5.0-pro output_images_standard': input => seedreamProTier(input) === '2K' ? 0 : 1,
30
+ 'minimax-h3-reference-to-video image_count': inputImageCount,
31
+ 'minimax-h3-max-reference-to-video image_count': inputImageCount,
32
+ // service/tencent_video_upscale.go: the output keeps the source frame rate up to max_fps (120 when unset),
33
+ // so only a 30 fps cap fixes the price tier before the source is measured.
34
+ 'tencent-video-upscale output_fps': (_input, modelParams) => String(modelParams.max_fps).trim() === '30' ? 30 : undefined,
35
+ };
36
+ /** Keys ("model parameter") the generation input decides; a different pricing_parameters value conflicts. */
37
+ export const DERIVED_QUOTE_PARAMETERS = new Set(Object.keys(derived));
38
+ export function derivedQuoteParameter(model, name, input, modelParams) {
39
+ return derived[`${model.toLowerCase()} ${name}`]?.(input, modelParams);
40
+ }
41
+ /** Settings the generation input cannot carry: without measured usage the higher-priced value is quoted. */
42
+ export const CONSERVATIVE_QUOTE_PARAMETERS = {
43
+ // controller/unified_videos.go rejects content_filter on a draft conversion; the draft's own setting is kept.
44
+ 'seedance-2.5-draft-to-video content_filter': { value: false,
45
+ note: 'Assumes the source draft was generated without the content filter (10% more); if it kept the default content_filter=true, pass pricing_parameters.content_filter=true.' },
46
+ };
47
+ /**
48
+ * A documented setting value that stands for the rule's own default. Kling 4.0 and 4.0 Flash video edit document
49
+ * duration "auto" (as long as the input video); their rules read duration_seconds 0 as the input length.
50
+ */
51
+ const RULE_DEFAULT_WORDS = { 'kling-v4-video-edit duration_seconds': 'auto', 'kling-v4-flash-video-edit duration_seconds': 'auto' };
52
+ export function isRuleDefaultWord(model, name, value) {
53
+ const word = RULE_DEFAULT_WORDS[`${model.toLowerCase()} ${name}`];
54
+ return word !== undefined && typeof value === 'string' && value.trim().toLowerCase() === word;
55
+ }
56
+ /** Usage the request cannot state: quoting it needs pricing_parameters unless a mapping above fixes it. */
57
+ export function derivedUsage(model, name) {
58
+ return model.toLowerCase() === 'tencent-video-upscale' && name === 'output_fps';
59
+ }
@@ -6,6 +6,8 @@ import { requestAccountQuote } from './api-client.js';
6
6
  import { getPricingRules, PricingMoney } from './pricing-rules-client.js';
7
7
  import { isSeedanceGeneration } from './seedance-input.js';
8
8
  import { searchUsage } from './search-usage.js';
9
+ import { effectiveMjV7EditPrompt } from './mj-prompt.js';
10
+ import { CONSERVATIVE_QUOTE_PARAMETERS, derivedQuoteParameter, derivedUsage, isRuleDefaultWord } from './pricing-derived.js';
9
11
  const decimal = z.string().max(64).regex(/^(?:0|[1-9]\d*)(?:\.\d+)?$/);
10
12
  const identifier = z.string().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/);
11
13
  const rational = z.string().max(128).regex(/^(?:0|[1-9]\d*)(?:\.\d+|\/[1-9]\d*)?$/);
@@ -51,6 +53,8 @@ function fail(code, message, param) { throw new QuoteError(code, message, param)
51
53
  const aliases = { duration_seconds: ['duration'], output_seconds: ['duration'], image_count: ['n', 'count'],
52
54
  video_count: ['n', 'count'], resolution: ['quality'], quality: ['resolution'] };
53
55
  const measured = /(?:tokens|input_seconds|output_seconds|source_output_seconds|first_input_video_seconds|search_count)$/;
56
+ /** A rule parameter that measures usage (tokens, seconds, searches, a derived rate) rather than a setting. */
57
+ export const isUsageParameter = (model, name) => measured.test(name) || derivedUsage(model, name);
54
58
  /** Map only declared billing parameters. Prompts and asset URLs stay in generation input. */
55
59
  export function prepareQuoteParameters(rule, entry, input, pricingParameters = {}, mediaSeconds, allowMissingUsage = false) {
56
60
  const declared = new Map((rule.parameters ?? []).map(p => [p.name, p]));
@@ -60,17 +64,34 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
60
64
  }
61
65
  const parameters = {};
62
66
  const searches = searchUsage(entry, input);
67
+ // Midjourney documents speed and upscale type inside model_params. A setting is read there only where the
68
+ // documentation puts it, so another model's model_params never changes its price.
69
+ const nestedSpec = entry.spec?.params.model_params?.properties ?? {};
70
+ const nestedInput = input.model_params && typeof input.model_params === 'object' && !Array.isArray(input.model_params)
71
+ ? input.model_params : {};
72
+ const documented = (key) => entry.spec?.params[key] ?? nestedSpec[key];
73
+ const given = (key) => input[key] !== undefined ? input[key] : nestedSpec[key] ? nestedInput[key] : undefined;
74
+ const model = entry.id ?? '';
75
+ const usage = (key) => isUsageParameter(model, key);
63
76
  for (const [name, p] of declared) {
64
77
  const search = searches.find(item => item.parameter === name);
65
78
  // A declared duration and duration_seconds have different meanings (smart duration).
66
79
  // Video edit's duration=-1 is an operation setting, never expected output seconds.
67
80
  const expectedEditDuration = name === 'duration_seconds' && entry.id === 'seedance-2.5-video-edit' && isSeedanceGeneration(entry);
68
81
  const generationNames = [name, ...(aliases[name] ?? []).filter(alias => !declared.has(alias) && !(expectedEditDuration && alias === 'duration'))];
69
- const supplied = generationNames.filter(key => input[key] !== undefined).map(key => input[key]);
82
+ // A documented word for the rule's own default (Kling 4.0 edit duration "auto") prices as that default.
83
+ const asRule = (value) => isRuleDefaultWord(model, name, value) ? p.default ?? value : value;
84
+ const supplied = generationNames.map(given).filter(value => value !== undefined).map(asRule);
70
85
  if (supplied.some(value => String(value) !== String(supplied[0]))) {
71
86
  fail('conflicting_quote_parameter', `Conflicting generation values for ${name}.`, name);
72
87
  }
73
88
  let value = supplied[0];
89
+ // A promptless Midjourney V7 edit runs and bills as fast whatever speed was requested.
90
+ if (value === undefined && name === 'prompt_present')
91
+ value = typeof input.prompt === 'string' && effectiveMjV7EditPrompt(input.prompt) !== '';
92
+ // Some rule parameters come from differently named request fields, as the gateway pre-deducts them.
93
+ if (value === undefined)
94
+ value = derivedQuoteParameter(model, name, input, nestedInput);
74
95
  if (value === undefined && name === 'input_images') {
75
96
  if (Array.isArray(input.image_urls))
76
97
  value = input.image_urls.length;
@@ -80,9 +101,9 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
80
101
  value = 0;
81
102
  }
82
103
  // Expected usage cannot change settings or references the model will actually receive.
83
- if (value === undefined && pricingParameters[name] !== undefined && !measured.test(name)
84
- && generationNames.some(key => entry.spec?.params[key] !== undefined)) {
85
- value = generationNames.map(key => entry.spec?.params[key]?.default).find(v => v !== undefined) ?? p.default;
104
+ if (value === undefined && pricingParameters[name] !== undefined && !usage(name)
105
+ && generationNames.some(key => documented(key) !== undefined)) {
106
+ value = asRule(generationNames.map(key => documented(key)?.default).find(v => v !== undefined) ?? p.default);
86
107
  }
87
108
  if (pricingParameters[name] !== undefined) {
88
109
  if (value !== undefined && String(value) !== String(pricingParameters[name])) {
@@ -111,8 +132,8 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
111
132
  continue;
112
133
  fail('quote_usage_required', `Provide expected generated ${name} in pricing_parameters.`, name);
113
134
  }
114
- if (value === undefined && !measured.test(name)) {
115
- const defaults = generationNames.map(key => entry.spec?.params[key]?.default).filter(v => v !== undefined);
135
+ if (value === undefined && !usage(name)) {
136
+ const defaults = generationNames.map(key => documented(key)?.default).filter(v => v !== undefined).map(asRule);
116
137
  value = defaults[0];
117
138
  }
118
139
  const references = Array.isArray(input.video_urls) && input.video_urls.length > 0
@@ -122,11 +143,13 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
122
143
  // The rules evaluator separately records the missing actual/expected search count.
123
144
  if (value === undefined && search?.enabled && allowMissingUsage)
124
145
  value = '0';
125
- if (value === undefined && measured.test(name) && (p.required || references || /tokens$/.test(name) || search?.enabled || (name === 'search_count' && input.web_search === true) || p.default === undefined)) {
146
+ if (value === undefined && usage(name) && (p.required || references || /tokens$/.test(name) || search?.enabled || (name === 'search_count' && input.web_search === true) || p.default === undefined)) {
126
147
  if (allowMissingUsage)
127
148
  continue;
128
149
  fail('quote_usage_required', `Provide measured or expected usage for ${name} in pricing_parameters.`, name);
129
150
  }
151
+ if (value === undefined)
152
+ value = CONSERVATIVE_QUOTE_PARAMETERS[`${model.toLowerCase()} ${name}`]?.value;
130
153
  if (value === undefined)
131
154
  value = p.default;
132
155
  if (value === undefined) {
@@ -197,15 +197,67 @@ async function readBody(response) {
197
197
  reader.releaseLock();
198
198
  }
199
199
  }
200
- export async function getPricingRules(input, options = {}) {
201
- const query = PricingRulesQuery.parse(input), base = controlBaseURL();
200
+ function rulesURL(query) {
201
+ const base = controlBaseURL();
202
202
  const url = new URL(query.model ? `${base}/v1/catalog/models/${encodeURIComponent(query.model)}/pricing-rules`
203
203
  : `${base}/v1/catalog/pricing-rules`);
204
204
  for (const key of ['product_id', 'operation', 'modality', 'lifecycle', 'view']) {
205
205
  if (query[key] !== undefined)
206
206
  url.searchParams.set(key, query[key]);
207
207
  }
208
+ return url;
209
+ }
210
+ /** The cached answer to this query while it is still within its cache time; nothing is requested. */
211
+ export function cachedPricingRules(input) {
212
+ const old = cache.get(rulesURL(PricingRulesQuery.parse(input)).href);
213
+ return old && old.expires > Date.now() ? old.body : undefined;
214
+ }
215
+ const stillFresh = (entry) => Date.parse(entry.body.meta.fresh_until) > Date.now();
216
+ /** One model's full rules from the cache: its own entry, else its row in the cached full list. */
217
+ function cachedModel(model, usable) {
218
+ const own = cache.get(rulesURL(PricingRulesQuery.parse({ model, view: 'full' })).href);
219
+ if (own && usable(own))
220
+ return own;
221
+ const list = cache.get(rulesURL(PricingRulesQuery.parse({ view: 'full' })).href);
222
+ const rule = list && usable(list) && 'models' in list.body ? list.body.models.find(item => item.model_id === model) : undefined;
223
+ return list && rule ? { body: { meta: list.body.meta, model: rule }, fetchedAt: list.fetchedAt } : undefined;
224
+ }
225
+ /** One model's full rules read at most maxAgeMs ago, even past their fresh_until: an estimate's fallback while the platform limits requests. */
226
+ export function recentModelRules(model, maxAgeMs) {
227
+ return cachedModel(model, entry => Date.now() - entry.fetchedAt <= maxAgeMs);
228
+ }
229
+ /** The cached answer to a query that `usable` accepts: a model's full rules may come from its row in the cached full list. */
230
+ function reusable(query, usable) {
231
+ if (query.model && query.view === 'full' && !query.product_id && !query.operation && !query.modality && !query.lifecycle)
232
+ return cachedModel(query.model, usable);
233
+ const old = cache.get(rulesURL(query).href);
234
+ return old && usable(old) ? old : undefined;
235
+ }
236
+ /** Whether getPricingRules(input, { reuseUntilFresh: true }) would answer from the cache now, without reading the platform. */
237
+ export function reusablePricingRules(input) {
238
+ return reusable(PricingRulesQuery.parse(input), stillFresh) !== undefined;
239
+ }
240
+ /**
241
+ * `reuseUntilFresh` serves a model's full rules from the cache (its own entry or the full list) until the rules' own
242
+ * fresh_until, which estimates use so a burst of them does not spend the platform's per-IP catalog limit; generation
243
+ * reads `fresh` rules and asks for a new approval when the price moved. `maxAgeMs` lets a fresh read take rules read
244
+ * that recently, still within their fresh_until, so a batch of generations reads them once. Concurrent reads of one
245
+ * query always share a single request.
246
+ */
247
+ export async function getPricingRules(input, options = {}) {
248
+ const query = PricingRulesQuery.parse(input), url = rulesURL(query);
208
249
  const key = url.href, old = cache.get(key);
250
+ if (options.reuseUntilFresh) {
251
+ const cached = reusable(query, stillFresh);
252
+ if (cached)
253
+ return { body: cached.body, source: 'cache' };
254
+ }
255
+ if (options.maxAgeMs !== undefined) {
256
+ const maxAgeMs = options.maxAgeMs;
257
+ const recent = reusable(query, entry => stillFresh(entry) && Date.now() - entry.fetchedAt <= maxAgeMs);
258
+ if (recent)
259
+ return { body: recent.body, source: 'recent' };
260
+ }
209
261
  if (!options.fresh && old && old.expires > Date.now())
210
262
  return { body: old.body, source: 'cache' };
211
263
  const existing = pending.get(key);
@@ -226,6 +278,7 @@ export async function getPricingRules(input, options = {}) {
226
278
  continue;
227
279
  }
228
280
  old.expires = Math.min(Date.now() + CACHE_TTL_MS, Date.parse(old.body.meta.fresh_until));
281
+ old.fetchedAt = Date.now();
229
282
  return { body: old.body, source: 'revalidated' };
230
283
  }
231
284
  if (!response.ok) {
@@ -246,7 +299,7 @@ export async function getPricingRules(input, options = {}) {
246
299
  if (cache.size >= MAX_CACHE_ENTRIES)
247
300
  cache.delete(cache.keys().next().value);
248
301
  cache.set(key, { body, etag: response.headers.get('ETag') ?? undefined,
249
- expires: Math.min(Date.now() + CACHE_TTL_MS, Date.parse(body.meta.fresh_until)) });
302
+ expires: Math.min(Date.now() + CACHE_TTL_MS, Date.parse(body.meta.fresh_until)), fetchedAt: Date.now() });
250
303
  return { body, source: 'live' };
251
304
  }
252
305
  throw new PricingRulesError('expired_pricing_rules');