@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
@@ -14,7 +14,7 @@ export function registerPlatformOperations(registry, config) {
14
14
  registerSearchModels(registry, config);
15
15
  registerDiscovery(registry, config);
16
16
  registerGetModel(registry, config);
17
- registerPricingRules(registry);
17
+ registerPricingRules(registry, config);
18
18
  registerEstimateCost(registry, config);
19
19
  registerGenerateTools(registry, config);
20
20
  registerGetTask(registry, config);
@@ -173,7 +173,7 @@ export async function submitTask(config, options) {
173
173
  body: options.body,
174
174
  tool: options.tool,
175
175
  idempotencyKey,
176
- }), 1, 500);
176
+ }).catch((error) => { options.onAttemptError?.(error); throw error; }), 1, 500);
177
177
  const receipt = parseTaskReceipt(data, requestId);
178
178
  if (headers.get('idempotency-replayed') === 'true')
179
179
  receipt.idempotency_replayed = true;
@@ -0,0 +1,117 @@
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 { ApiHttpError, submitTask } from './api-client.js';
4
+ import { remainingMs } from './http-policy.js';
5
+ import { QuoteError, quoteRequestHash } from './pricing-quote-client.js';
6
+ import { APPROVAL_TTL_MS, MAX_BATCH_ITEMS, amountsForUC } from './pricing-rules-estimate.js';
7
+ export { MAX_BATCH_ITEMS };
8
+ /** Submissions of one batch in flight at once. */
9
+ export const BATCH_SUBMIT_CONCURRENCY = 10;
10
+ /**
11
+ * No item of a batch starts later than this after the call began. Submissions usually take 1–3 s, so 50 items need
12
+ * 5–15 s; the rest of a slow batch is reported not submitted, to be finished with the same client_request_id.
13
+ */
14
+ export const BATCH_SUBMIT_DEADLINE_MS = 25_000;
15
+ /** A batch client_request_id leaves room for the ".NN" each item adds, within the gateway's 96 characters. */
16
+ export const BATCH_REQUEST_ID_MAX = 93;
17
+ let submitDeadlineMs = BATCH_SUBMIT_DEADLINE_MS;
18
+ /** Tests shorten the submission deadline; undefined restores it. */
19
+ export function setBatchSubmitDeadlineForTests(ms) { submitDeadlineMs = ms ?? BATCH_SUBMIT_DEADLINE_MS; }
20
+ /** Item `index` of the batch `batchId` always has this idempotency key, so a retry finds what an earlier call submitted. */
21
+ export function batchItemRequestId(batchId, index) {
22
+ return `${batchId}.${String(index).padStart(2, '0')}`;
23
+ }
24
+ const unique = (lines) => [...new Set(lines)];
25
+ /**
26
+ * The inputs' estimates as one: complete only when every input is. Any input that still needs usage leaves the batch
27
+ * without a total (needs_input), any partial one makes it partial; amounts add up exactly in UC.
28
+ */
29
+ export function batchTotal(model, items) {
30
+ const statusOf = (item) => item.estimate.status;
31
+ const needsInput = items.flatMap((item, index) => statusOf(item) === 'needs_input' ? [index] : []);
32
+ const partial = items.flatMap((item, index) => statusOf(item) === 'partial' ? [index] : []);
33
+ const status = needsInput.length ? 'needs_input' : partial.length ? 'partial'
34
+ : items.some(item => statusOf(item) === 'token_billed') ? 'token_billed' : 'estimated';
35
+ const amounts = amountsForUC(String(items.reduce((sum, item) => sum + BigInt(item.amounts.uc), 0n)));
36
+ const approval = { source: 'pricing_rules', price_scope: 'public_default', model_id: model,
37
+ request_hash: quoteRequestHash(model, { batch: items.map(item => item.approval.request_hash) }),
38
+ fingerprint: quoteRequestHash(model, { batch: items.map(item => item.approval.fingerprint) }),
39
+ total_uc: amounts.uc, expires_at: new Date(Date.now() + APPROVAL_TTL_MS).toISOString(), batch_items: items.length };
40
+ const missing = unique(items.flatMap(item => item.estimate.missing_usage ?? [])).sort();
41
+ const basis = unique(items.flatMap(item => item.estimate.basis));
42
+ const estimate = { status,
43
+ ...(status === 'needs_input' ? {} : { min_usd: Number(amounts.usd), max_usd: Number(amounts.usd),
44
+ min_credits: Number(amounts.credits), max_credits: Number(amounts.credits) }),
45
+ total_known: status === 'estimated',
46
+ // A reference price names each input's tokens; past a few inputs only the first one is shown.
47
+ basis: basis.length > 3 ? [basis[0], `The other inputs are priced the same way (${basis.length - 1} more lines; see items).`] : basis,
48
+ possible_extras: unique(items.flatMap(item => item.estimate.possible_extras)),
49
+ notes: unique(items.flatMap(item => item.estimate.notes)),
50
+ ...(missing.length ? { uncheckable_reason: 'usage', missing_usage: missing,
51
+ usage_help: unique(items.flatMap(item => item.estimate.usage_help ?? [])) } : {}) };
52
+ return { status, amounts, approval, estimate, partial, needsInput };
53
+ }
54
+ function fail(code, message) { throw new QuoteError(code, message); }
55
+ /**
56
+ * A batch approval holds for the same inputs, in the same order, at the same total; past its expires_at it still holds
57
+ * when neither changed. An approval of one input never approves a batch.
58
+ */
59
+ export function checkBatchApproval(approval, fresh) {
60
+ const expired = Date.parse(approval.expires_at) <= Date.now();
61
+ if (approval.batch_items === undefined) {
62
+ fail('quote_input_changed', 'This pricing_quote approves one input; estimate these inputs together (inputs) and obtain approval.');
63
+ }
64
+ if (approval.batch_items !== fresh.batch_items || approval.request_hash !== fresh.request_hash || approval.model_id !== fresh.model_id) {
65
+ fail('quote_input_changed', 'The inputs differ from the approved batch estimate (the same inputs, in the same order).');
66
+ }
67
+ if (approval.fingerprint !== fresh.fingerprint || approval.total_uc !== fresh.total_uc) {
68
+ fail('price_changed', 'The pricing rules or estimated price changed. Estimate again and obtain approval.');
69
+ }
70
+ return { expired };
71
+ }
72
+ /**
73
+ * The gateway answered every attempt without running it: a rate limit (it releases the key, so the same key can be
74
+ * submitted again) or a key already used for a different input. Only then is a failed item certainly not submitted.
75
+ */
76
+ export function refusedBeforeRunning(submission) {
77
+ return submission.attempts.length > 0 && submission.attempts.every(error => error instanceof ApiHttpError
78
+ && (error.status === 429 || error.status === 409 && error.info?.code === 'idempotency_conflict'));
79
+ }
80
+ /** The item's key was used before for a different input: the same call conflicts again, so only exactly that input finishes it. */
81
+ export function keyConflict(submission) {
82
+ return submission.attempts.some(error => error instanceof ApiHttpError && error.status === 409 && error.info?.code === 'idempotency_conflict');
83
+ }
84
+ /**
85
+ * A refusal the gateway keeps for the key: it checks the key's model access after recording the key and releases a
86
+ * key only after a 402 or 429 refusal, so the same client_request_id gets this refusal again for 24 hours. Other
87
+ * refusals before dispatch are fixed and finished with the same client_request_id (auth refusals come before the key).
88
+ */
89
+ export function keptRefusal(code) {
90
+ return code?.toLowerCase() === 'key_model_not_allowed';
91
+ }
92
+ /**
93
+ * Submits every body, at most BATCH_SUBMIT_CONCURRENCY at once, each with its item's idempotency key. No submission
94
+ * starts after the deadline or once `signal` is aborted; one already started is never interrupted.
95
+ */
96
+ export async function submitBatch(config, options) {
97
+ const deadline = options.startedMono + submitDeadlineMs;
98
+ const submissions = options.bodies.map((_, index) => ({ index, requestId: batchItemRequestId(options.batchId, index),
99
+ started: false, attempts: [] }));
100
+ let next = 0, done = 0;
101
+ const worker = async () => {
102
+ while (next < submissions.length && !options.signal?.aborted && remainingMs(deadline) > 0) {
103
+ const item = submissions[next++];
104
+ item.started = true;
105
+ try {
106
+ item.receipt = await submitTask(config, { path: options.path, body: options.bodies[item.index], tool: options.tool,
107
+ idempotencyKey: item.requestId, onAttemptError: error => item.attempts.push(error) });
108
+ }
109
+ catch (error) {
110
+ item.error = error;
111
+ }
112
+ options.onSubmitted?.(++done);
113
+ }
114
+ };
115
+ await Promise.all(Array.from({ length: Math.min(BATCH_SUBMIT_CONCURRENCY, submissions.length) }, worker));
116
+ return submissions;
117
+ }
@@ -4,10 +4,18 @@ import { controlBaseURL } from './pricing-client.js';
4
4
  import { DEFAULT_READ_TIMEOUT_MS, evoHeaders, fetchWithTimeout, readJsonBody, timeoutFromEnv } from './http-policy.js';
5
5
  const catalogs = new Map();
6
6
  const healths = new Map();
7
+ /** While the platform limits catalog requests, a catalog or availability list read this recently is used again. */
8
+ const LIMITED_REUSE_MS = 10 * 60_000;
9
+ class CatalogLimitedError extends Error {
10
+ }
7
11
  async function read(path) {
8
12
  const response = await fetchWithTimeout(`${controlBaseURL()}${path}`, {
9
13
  method: 'GET', headers: { Accept: 'application/json', ...evoHeaders('model_catalog') },
10
14
  }, timeoutFromEnv('EVOLINK_MCP_READ_TIMEOUT_MS', DEFAULT_READ_TIMEOUT_MS));
15
+ if (response.status === 429) {
16
+ await response.body?.cancel();
17
+ throw new CatalogLimitedError('The current model catalog is unavailable; try again before selecting or submitting a model.');
18
+ }
11
19
  const body = await readJsonBody(response);
12
20
  if (!response.ok || !Array.isArray(body.models))
13
21
  throw new Error('The current model catalog is unavailable; try again before selecting or submitting a model.');
@@ -17,11 +25,21 @@ export async function currentModels() {
17
25
  const now = Date.now();
18
26
  const key = controlBaseURL();
19
27
  const catalog = catalogs.get(key), health = healths.get(key);
28
+ // A stale availability list can only let through a model the gateway then refuses; it never changes a price.
29
+ const reusable = (cached, error) => error instanceof CatalogLimitedError && cached !== undefined && now - cached.fetchedAt < LIMITED_REUSE_MS;
20
30
  const [models, available] = await Promise.all([
21
31
  (async () => {
22
32
  if (catalog && now - catalog.fetchedAt < 5 * 60_000)
23
33
  return catalog.models;
24
- const body = await read('/v1/catalog/models');
34
+ let body;
35
+ try {
36
+ body = await read('/v1/catalog/models');
37
+ }
38
+ catch (error) {
39
+ if (reusable(catalog, error))
40
+ return catalog.models;
41
+ throw error;
42
+ }
25
43
  const models = body.models.filter(model => typeof model.model_id === 'string'
26
44
  && Array.isArray(model.aliases) && Array.isArray(model.capabilities) && Array.isArray(model.protocols));
27
45
  catalogs.set(key, { models, fetchedAt: now });
@@ -30,7 +48,15 @@ export async function currentModels() {
30
48
  (async () => {
31
49
  if (health && now - health.fetchedAt < 30_000)
32
50
  return health.available;
33
- const body = await read('/v1/catalog/health');
51
+ let body;
52
+ try {
53
+ body = await read('/v1/catalog/health');
54
+ }
55
+ catch (error) {
56
+ if (reusable(health, error))
57
+ return health.available;
58
+ throw error;
59
+ }
34
60
  const available = new Set(body.models
35
61
  .filter(model => typeof model.model_id === 'string' && model.status === 'available').map(model => model.model_id.toLowerCase()));
36
62
  healths.set(key, { available, fetchedAt: now });
@@ -0,0 +1,264 @@
1
+ // Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
2
+ // Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
3
+ import { QuoteError } from './pricing-quote-client.js';
4
+ // The tokens the gateway reserves for a GPT Image task at submission. Ported from GroAPI (feat/task-microservice-split)
5
+ // common/gpt_image2_token.go, common/gpt_image26_gif.go, the GPT Image 2.6 checks in controller/unified_images_gpt_image26.go
6
+ // and the token image pre-charge in controller/unified_images.go. The output token calculator is the one on OpenAI's image
7
+ // generation guide; its floating-point steps keep the same order, so every count matches the gateway's. The task itself
8
+ // settles at the tokens the upstream reports.
9
+ const STEP = 16, MIN_PIXELS = 655_360, MAX_PIXELS = 8_294_400, MAX_EDGE = 3840, MAX_RATIO = 3;
10
+ const RATIOS = { '1:1': [1, 1], '1:2': [1, 2], '2:1': [2, 1], '1:3': [1, 3], '3:1': [3, 1],
11
+ '2:3': [2, 3], '3:2': [3, 2], '3:4': [3, 4], '4:3': [4, 3], '4:5': [4, 5], '5:4': [5, 4], '9:16': [9, 16], '16:9': [16, 9],
12
+ '21:9': [21, 9], '9:21': [9, 21] };
13
+ /** Pixel budget of each resolution tier for a ratio size. */
14
+ const BUDGETS = { '1K': 1024 * 1024, '2K': 2048 * 2048, '4K': MAX_PIXELS };
15
+ /** Long-edge tile base by quality: gpt-image-2, and the 2.5 generation, whose tiers sit lower. */
16
+ const BASE_2 = { low: 16, medium: 48, high: 96 };
17
+ const BASE_25 = { low: 16, medium: 24, high: 48, xhigh: 64, max: 96 };
18
+ /** 2.6 multiplies the 2.5 count by quality, in tenths, rounding up with integer steps as the gateway does. */
19
+ const TENTHS_26 = { low: 42, medium: 33, high: 10, xhigh: 10, max: 10 };
20
+ /** gpt-image-1 and 1.5 bill fixed tiles by quality: portrait, landscape, square. */
21
+ const TILES_1 = { low: [408, 400, 272], medium: [1584, 1568, 1056], high: [6240, 6208, 4160] };
22
+ /** Reserved for each reference image or mask: the most a 1024² input has used. Larger inputs can use more. */
23
+ export const INPUT_IMAGE_TOKENS = 1536;
24
+ /** A 2.6 GIF's frames are drawn on one sheet, which is what is billed; size auto uses frames of this edge. */
25
+ const GIF_AUTO_FRAME = 512, GIF_DEFAULT_FRAMES = 9;
26
+ const family26 = (model) => model.trim().toLowerCase().startsWith('gpt-image-2.6');
27
+ /** The 2.5 generation: 2.5 and 2.6 share qualities, tile bases and sizes. */
28
+ const family25 = (model) => model.trim().toLowerCase().startsWith('gpt-image-2.5') || family26(model);
29
+ const family1 = (model) => model === 'gpt-image-1.5' || model === 'gpt-image-1';
30
+ /** Models the gateway reserves and bills by token counts. */
31
+ export const isTokenImageModel = (model) => model === 'gpt-image-2' || family1(model) || family25(model);
32
+ function invalid(param, message) { throw new QuoteError('invalid_quote_parameter', message, param); }
33
+ const text = (param, value) => value === undefined ? '' : typeof value === 'string' ? value : invalid(param, `${param} must be a string.`);
34
+ const nestedParams = (input) => input.model_params && typeof input.model_params === 'object' && !Array.isArray(input.model_params)
35
+ ? input.model_params : {};
36
+ const lower = (value) => typeof value === 'string' ? value.trim().toLowerCase() : '';
37
+ /** strconv.Atoi for the sizes the gateway reads; a longer number is not a size it can accept. */
38
+ const integer = (part) => /^[+-]?\d{1,15}$/.test(part) ? Number(part) : NaN;
39
+ function pixelSize(size) {
40
+ if (size === '')
41
+ return undefined;
42
+ const lower = size.toLowerCase();
43
+ for (const separator of ['x', '×']) {
44
+ const at = lower.indexOf(separator);
45
+ if (at < 0)
46
+ continue;
47
+ const width = integer(lower.slice(0, at).trim()), height = integer(lower.slice(at + separator.length).trim());
48
+ if (width > 0 && height > 0)
49
+ return [width, height];
50
+ }
51
+ return undefined;
52
+ }
53
+ function checkPixels(width, height) {
54
+ const longer = Math.max(width, height), shorter = Math.min(width, height), pixels = width * height;
55
+ if (width % STEP || height % STEP || pixels > MAX_PIXELS || pixels < MIN_PIXELS || longer > MAX_EDGE || longer > MAX_RATIO * shorter) {
56
+ invalid('size', `size ${width}x${height} needs edges that are multiples of ${STEP}, ${MIN_PIXELS}–${MAX_PIXELS} pixels, an edge of at most ${MAX_EDGE} and an aspect ratio of at most ${MAX_RATIO}:1.`);
57
+ }
58
+ }
59
+ const roundToStep = (n) => n < STEP ? STEP : Math.trunc((n + STEP / 2) / STEP) * STEP;
60
+ const floorToStep = (n) => n < STEP ? STEP : Math.trunc(n / STEP) * STEP;
61
+ /** Scales a ratio size into the pixel and edge limits, keeping its aspect ratio. */
62
+ function fitBudget(width, height) {
63
+ const pixels = width * height, edge = Math.max(width, height);
64
+ if (pixels <= MAX_PIXELS && edge <= MAX_EDGE)
65
+ return [width, height];
66
+ let scale = 1;
67
+ if (pixels > MAX_PIXELS)
68
+ scale = Math.min(scale, Math.sqrt(MAX_PIXELS / pixels));
69
+ if (edge > MAX_EDGE)
70
+ scale = Math.min(scale, MAX_EDGE / edge);
71
+ // Nearest multiple of 16 first (2:1 at 4K is 3840×1920); rounding down only when that leaves the limits.
72
+ const near = [roundToStep(Math.round(width * scale)), roundToStep(Math.round(height * scale))];
73
+ return near[0] * near[1] > MAX_PIXELS || Math.max(...near) > MAX_EDGE
74
+ ? [floorToStep(Math.trunc(width * scale)), floorToStep(Math.trunc(height * scale))] : near;
75
+ }
76
+ /** ResolveGPTImage2Size: explicit pixels as given; a ratio fitted to the resolution's pixel budget. */
77
+ function outputSize(size, resolution) {
78
+ const trimmed = size.trim(), pixels = pixelSize(trimmed);
79
+ if (pixels) {
80
+ checkPixels(...pixels);
81
+ return pixels;
82
+ }
83
+ const ratio = ['', 'auto'].includes(trimmed.toLowerCase()) ? '1:1' : trimmed.toLowerCase();
84
+ const aspect = RATIOS[ratio] ?? invalid('size', `size ${size} is not a supported ratio or WxH pixel size.`);
85
+ const tier = resolution.trim().toUpperCase() || '1K', budget = BUDGETS[tier] ?? invalid('resolution', `resolution ${resolution} must be 1K, 2K or 4K.`);
86
+ const [width, height] = fitBudget(roundToStep(Math.trunc(Math.sqrt(budget * aspect[0] / aspect[1]))), roundToStep(Math.trunc(Math.sqrt(budget * aspect[1] / aspect[0]))));
87
+ checkPixels(width, height);
88
+ return [width, height];
89
+ }
90
+ /** resolveGPTImage1FamilySize: gpt-image-1 and 1.5 take three sizes. */
91
+ function family1Size(size) {
92
+ const value = size.trim().toLowerCase();
93
+ if (['', '1024x1024', '1024×1024', '1:1'].includes(value))
94
+ return [1024, 1024];
95
+ if (['1024x1536', '1024×1536', '2:3'].includes(value))
96
+ return [1024, 1536];
97
+ if (['1536x1024', '1536×1024', '3:2'].includes(value))
98
+ return [1536, 1024];
99
+ return invalid('size', `size ${size} must be 1024x1024, 1024x1536, 1536x1024, 1:1, 2:3 or 3:2.`);
100
+ }
101
+ function scaledTiles(base, longer, shorter) {
102
+ // The calculator's own order of division: base * shorter / longer differs in the last bit for a few sizes.
103
+ const c = base / (longer / shorter), p = Math.floor(c);
104
+ return c - p === 0.5 ? p + p % 2 : Math.round(c);
105
+ }
106
+ /** Output tokens for one image. */
107
+ export function imageOutputTokens(model, width, height, quality) {
108
+ if (family1(model)) {
109
+ const tiles = TILES_1[quality];
110
+ return width < height ? tiles[0] : width > height ? tiles[1] : tiles[2];
111
+ }
112
+ const base = (family25(model) ? BASE_25 : BASE_2)[quality];
113
+ const tokens = Math.ceil(base * scaledTiles(base, Math.max(width, height), Math.min(width, height)) * (2_000_000 + width * height) / 4_000_000);
114
+ return family26(model) ? Math.trunc((tokens * TENTHS_26[quality] + 9) / 10) : tokens;
115
+ }
116
+ /** The layouts, columns × rows, the upstream tries for a GIF's frame count, in its order. */
117
+ function gifGrids(frames) {
118
+ if (frames >= 2 && frames <= 8)
119
+ return [[4, 2], [2, 4]];
120
+ if (frames === 9)
121
+ return [[3, 3]];
122
+ if (frames >= 10 && frames <= 12)
123
+ return [[3, 4], [4, 3], [4, 4]];
124
+ if (frames >= 13 && frames <= 16)
125
+ return [[4, 4]];
126
+ return [];
127
+ }
128
+ /** A sheet keeps to the limits of a single image; its minimum pixel count is left to the upstream. */
129
+ function sheetFits(width, height) {
130
+ const longer = Math.max(width, height), shorter = Math.min(width, height);
131
+ return shorter > 0 && longer <= MAX_EDGE && width * height <= MAX_PIXELS && longer <= MAX_RATIO * shorter;
132
+ }
133
+ /** model_params.frame_count and frame_duration_ms of a GIF, as the gateway checks them; 9 frames when absent. */
134
+ function gifFrames(params) {
135
+ const duration = params.frame_duration_ms;
136
+ if (duration !== undefined && duration !== null && !(Number.isInteger(duration) && duration >= 20 && duration <= 2000)) {
137
+ invalid('model_params.frame_duration_ms', 'model_params.frame_duration_ms must be a whole number from 20 to 2000.');
138
+ }
139
+ const frames = params.frame_count;
140
+ if (frames === undefined || frames === null)
141
+ return GIF_DEFAULT_FRAMES;
142
+ return Number.isInteger(frames) && frames >= 2 && frames <= 16 ? frames
143
+ : invalid('model_params.frame_count', 'model_params.frame_count must be a whole number from 2 to 16.');
144
+ }
145
+ /**
146
+ * The sheet a 2.6 GIF is billed for: frames of the size given (512×512 for auto) laid out on the layout of the fewest
147
+ * cells that fits; of two orientations that both fit, the one with more output tokens (EstimateGPTImage26GIFOutputTokens).
148
+ */
149
+ function gifSheet(model, size, frames, quality) {
150
+ const trimmed = size.trim();
151
+ let frameWidth = GIF_AUTO_FRAME, frameHeight = GIF_AUTO_FRAME;
152
+ if (!['', 'auto'].includes(trimmed.toLowerCase())) {
153
+ const pixels = trimmed.includes(':') ? undefined : pixelSize(trimmed);
154
+ if (!pixels)
155
+ invalid('size', `With output_format gif, size is auto or the WIDTHxHEIGHT of each frame, not ${size}.`);
156
+ [frameWidth, frameHeight] = pixels;
157
+ if (frameWidth % STEP || frameHeight % STEP || frameWidth > MAX_EDGE || frameHeight > MAX_EDGE) {
158
+ invalid('size', `GIF frame edges must be multiples of ${STEP} and at most ${MAX_EDGE}px, got ${frameWidth}x${frameHeight}.`);
159
+ }
160
+ }
161
+ const grids = gifGrids(frames);
162
+ let fewest = 0, best;
163
+ for (const [columns, rows] of grids) {
164
+ const width = columns * frameWidth, height = rows * frameHeight, cells = columns * rows;
165
+ if (!sheetFits(width, height) || fewest && cells > fewest)
166
+ continue;
167
+ fewest = cells;
168
+ const tokens = imageOutputTokens(model, width, height, quality);
169
+ if (!best || tokens > best.tokens)
170
+ best = { width, height, columns, rows, tokens };
171
+ }
172
+ if (!best) {
173
+ const [columns, rows] = grids[0];
174
+ invalid('size', `GIF frames of ${frameWidth}x${frameHeight} do not fit: for frame_count=${frames} the frames are tiled ${columns}x${rows} into one image of at most ${MAX_EDGE}px per edge and ${MAX_PIXELS} pixels, so each frame has at most ${Math.trunc(MAX_PIXELS / (columns * rows))} pixels, one edge up to ${Math.trunc(MAX_EDGE / columns)} and the other up to ${Math.trunc(MAX_EDGE / rows)} (size auto uses ${GIF_AUTO_FRAME}x${GIF_AUTO_FRAME} frames).`);
175
+ }
176
+ return { ...best, frames, frame_width: frameWidth, frame_height: frameHeight };
177
+ }
178
+ /** CJK ideographs, kana, Hangul and their punctuation and full-width forms. */
179
+ export const CJK = /[ᄀ-ᇿ⺀-鿿ꥠ-꥿가-퟿豈-﫿︰-﹏＀-￯]/u;
180
+ // Hundredths of a token per character, by class. Calibrated on 10-31 against the gateway's o200k_base counts
181
+ // (scripts/gpt-image-reservation): typical prompts come out 0.8 to 1.8 times the exact count, most a little above it.
182
+ const LETTER = 25, DIGIT_OR_MARK = 75, CJK_CHARACTER = 110, OTHER_SCRIPT = 50, ASTRAL = 300;
183
+ /**
184
+ * Prompt tokens, approximately: the gateway counts them with the o200k_base encoding, which this package does not
185
+ * ship. Prompt tokens are a small part of an image's price, and the task settles at the count the upstream reports.
186
+ */
187
+ export function approximatePromptTokens(prompt) {
188
+ let hundredths = 0;
189
+ for (const character of prompt) {
190
+ const code = character.codePointAt(0);
191
+ hundredths += code < 0x80 ? /[A-Za-z\s]/.test(character) ? LETTER : DIGIT_OR_MARK
192
+ : code > 0xffff ? ASTRAL : CJK.test(character) ? CJK_CHARACTER : OTHER_SCRIPT;
193
+ }
194
+ return Math.ceil(hundredths / 100);
195
+ }
196
+ const filled = (value) => typeof value === 'string' && value !== '';
197
+ /** parseFlexibleStringArray: one string or a list; empty and non-string entries do not count. */
198
+ const referenceCount = (value) => Array.isArray(value) ? value.filter(filled).length : filled(value) ? 1 : 0;
199
+ /**
200
+ * The output settings the gateway refuses before it reserves anything, for gpt-image-2 and the 2.5 generation; true for
201
+ * a GPT Image 2.6 GIF. The format and background are read as the gateway reads them: the top-level value, then
202
+ * model_params, trimmed and lower-cased.
203
+ */
204
+ function gifOutput(model, input, images) {
205
+ const params = nestedParams(input);
206
+ const format = lower(input.output_format) || lower(params.output_format), background = lower(input.background) || lower(params.background);
207
+ if (background === 'transparent' && (format === 'jpeg' || format === 'jpg'))
208
+ invalid('background', `background transparent needs png or webp output; ${format} cannot keep transparency.`);
209
+ if (!family26(model))
210
+ return false;
211
+ // SVG output is paused on the gateway, and its author model would be priced on top, so it is never quoted.
212
+ if (format === 'svg')
213
+ invalid('output_format', `output_format svg is not available on ${model}; use png, jpeg, webp or gif.`);
214
+ if (['svg_model', 'svg_reasoning_effort'].some(key => Object.hasOwn(params, key)))
215
+ invalid('model_params', 'model_params.svg_model and svg_reasoning_effort need output_format svg, which is not available.');
216
+ if (format !== 'gif' && ['frame_count', 'frame_duration_ms'].some(key => Object.hasOwn(params, key)))
217
+ invalid('model_params', 'model_params.frame_count and frame_duration_ms need output_format gif.');
218
+ const markup = [input.markup_url, params.markup_url].map(value => typeof value === 'string' ? value.trim() : '').find(Boolean);
219
+ if (markup) {
220
+ if (!(referenceCount(input.image_url) + referenceCount(input.image_urls) + referenceCount(params.image_url) + referenceCount(params.image_urls))) {
221
+ invalid('markup_url', 'markup_url marks up the first reference image, so it needs image_urls.');
222
+ }
223
+ if ([input.mask_url, params.mask_url].some(value => typeof value === 'string' && value.trim() !== ''))
224
+ invalid('markup_url', 'markup_url cannot be combined with mask_url.');
225
+ }
226
+ if (format !== 'gif')
227
+ return false;
228
+ if (images > 1)
229
+ invalid('n', `output_format gif on ${model} needs n=1.`);
230
+ if (background === 'transparent')
231
+ invalid('background', 'background transparent needs png or webp output, not gif.');
232
+ return true;
233
+ }
234
+ /**
235
+ * The tokens the gateway reserves at submission for this input, as the reference price counts them. Without a size (or
236
+ * with auto) gpt-image-2 and the 2.5 generation count a 2048×2048 output, and a 2.6 GIF counts 512×512 frames; quality
237
+ * defaults to medium, high for gpt-image-1 and 1.5. A markup layer is not counted as a reference image.
238
+ * countPromptTokens replaces the approximation when the exact count is known.
239
+ */
240
+ export function tokenImageReservation(model, input, countPromptTokens = approximatePromptTokens) {
241
+ const n = input.n === undefined ? 1 : Number.isInteger(input.n) ? Math.max(1, input.n) : invalid('n', 'n must be a whole number.');
242
+ const given = text('quality', input.quality);
243
+ const quality = given === '' ? family1(model) ? 'high' : 'medium' : given.trim().toLowerCase();
244
+ if (!Object.hasOwn(family1(model) ? TILES_1 : family25(model) ? BASE_25 : BASE_2, quality))
245
+ invalid('quality', `quality ${given} is not supported by ${model}.`);
246
+ const size = text('size', input.size), resolution = text('resolution', input.resolution);
247
+ const auto = !family1(model) && ['', 'auto'].includes(size.trim().toLowerCase());
248
+ let output, outputTokens;
249
+ if (!family1(model) && gifOutput(model, input, n)) {
250
+ const { tokens, width, height, ...gif } = gifSheet(model, size, gifFrames(nestedParams(input)), quality);
251
+ output = { width, height, quality, size: auto ? 'auto' : 'pixels', gif };
252
+ outputTokens = tokens;
253
+ }
254
+ else {
255
+ const [width, height] = auto ? [2048, 2048] : family1(model) ? family1Size(size) : outputSize(size, resolution);
256
+ output = { width, height, quality, size: family1(model) ? 'fixed' : auto ? 'auto' : pixelSize(size.trim()) ? 'pixels' : 'ratio' };
257
+ outputTokens = imageOutputTokens(model, width, height, quality);
258
+ }
259
+ const mask = text('mask_url', input.mask_url);
260
+ const references = referenceCount(input.image_url) + referenceCount(input.image_urls) + (mask !== '' ? 1 : 0);
261
+ const prompt = text('prompt', input.prompt);
262
+ return { per_image: { image_output_tokens: outputTokens, text_input_tokens: prompt === '' ? 0 : countPromptTokens(prompt),
263
+ image_input_tokens: INPUT_IMAGE_TOKENS * references }, images: n, output, reference_images: references };
264
+ }
@@ -0,0 +1,18 @@
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
+ // The gateway decides whether a Midjourney V7 edit is promptless after removing controlled parameters
4
+ // (provider SDK EffectiveMJV7EditPrompt, which wraps cleanRemixPrompt in provider/client_youchuan.go).
5
+ // These patterns keep the SDK's boundaries: RE2 \s is ASCII only, (?i) folds the long s (U+017F) with s, and Go's
6
+ // strings.TrimSpace removes NEL but not BOM, unlike String.prototype.trim.
7
+ const space = '[\\t\\n\\f\\r ]';
8
+ const nonSpace = '[^\\t\\n\\f\\r ]';
9
+ const fold = (words) => words.replace(/s/g, '[s\u017f]');
10
+ const forbidden = new RegExp(`${space}*--(${fold('version|v')})${space}*${nonSpace}+|${space}*--niji(?:${space}+\\d+)?\\b`, 'gi');
11
+ const billing = new RegExp(`${space}*--(${fold('fast|turbo|draft|relax')})\\b`, 'gi');
12
+ const unsupportedArgs = new RegExp(`${space}*--(${fold('stop|cref|cw|repeat|r|personalize|p')})\\b(?:${space}+${nonSpace}+)?`, 'gi');
13
+ const unsupportedFlags = new RegExp(`${space}*--(${fold('stealth|public')})\\b`, 'gi');
14
+ const goTrimSpace = /^[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/g;
15
+ /** The prompt text a Midjourney V7 edit keeps; an empty result runs and bills the edit as fast. */
16
+ export function effectiveMjV7EditPrompt(prompt) {
17
+ return prompt.replace(forbidden, '').replace(billing, '').replace(unsupportedArgs, '').replace(unsupportedFlags, '').replace(goTrimSpace, '');
18
+ }
@@ -7,7 +7,8 @@ export function referenceInputs(spec) {
7
7
  const result = [];
8
8
  for (const [parameter, value] of Object.entries(spec.params)) {
9
9
  let kind;
10
- if (/^(?:.*_)?image_urls?$|^(?:images|image|input_image|first_frame|last_frame)$/.test(parameter))
10
+ // Kling 4.0 and MiniMax H3 take first and last frames as image_start / image_end, and Kling 4.0 middle frames as keyframes.
11
+ if (/^(?:.*_)?image_urls?$|^(?:images|image|input_image|first_frame|last_frame|image_start|image_end|keyframes)$/.test(parameter))
11
12
  kind = 'image';
12
13
  else if (/^(?:.*_)?video_urls?$|^videos$/.test(parameter))
13
14
  kind = 'video';