@evolinkai/cli 0.7.0 → 0.8.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.
- package/README.md +35 -6
- package/package.json +27 -8
- package/skills/evolink-cli/SKILL.md +5 -5
- package/skills/evolink-cli/references/capabilities.md +1 -1
- package/src/api.mjs +59 -0
- package/src/auth.mjs +6 -7
- package/src/cli.mjs +34 -30
- package/src/doctor.mjs +9 -6
- package/src/errors.mjs +21 -13
- package/src/files.mjs +61 -6
- package/src/help.mjs +8 -8
- package/src/media.mjs +11 -9
- package/src/network.mjs +12 -1
- package/src/oauth.mjs +90 -0
- package/src/platform/LICENSE +178 -0
- package/src/platform/NOTICE +6 -0
- package/src/platform/core/src/config.js +95 -0
- package/src/platform/core/src/data/model-constraints.js +37 -0
- package/src/platform/core/src/data/model-params.generated.js +4 -0
- package/src/platform/core/src/data/model-params.js +28 -0
- package/src/platform/core/src/platform-client.js +56 -0
- package/src/platform/core/src/platform-operations.js +22 -0
- package/src/platform/core/src/request-context.js +53 -0
- package/src/platform/core/src/services/api-client.js +232 -0
- package/src/platform/core/src/services/catalog-client.js +45 -0
- package/src/platform/core/src/services/error-handler.js +452 -0
- package/src/platform/core/src/services/file-client.js +165 -0
- package/src/platform/core/src/services/http-policy.js +186 -0
- package/src/platform/core/src/services/model-capabilities.js +24 -0
- package/src/platform/core/src/services/model-catalog.js +68 -0
- package/src/platform/core/src/services/model-recommendations.js +35 -0
- package/src/platform/core/src/services/param-validator.js +201 -0
- package/src/platform/core/src/services/pricing-client.js +451 -0
- package/src/platform/core/src/services/public-error.js +63 -0
- package/src/platform/core/src/services/utm.js +65 -0
- package/src/platform/core/src/tool-guidance.js +50 -0
- package/src/platform/core/src/tools/check-balance.js +90 -0
- package/src/platform/core/src/tools/discovery.js +86 -0
- package/src/platform/core/src/tools/estimate-cost.js +136 -0
- package/src/platform/core/src/tools/generate.js +237 -0
- package/src/platform/core/src/tools/get-model.js +146 -0
- package/src/platform/core/src/tools/get-task.js +57 -0
- package/src/platform/core/src/tools/list-tasks.js +170 -0
- package/src/platform/core/src/tools/search-models.js +115 -0
- package/src/platform/core/src/tools/shared.js +158 -0
- package/src/platform/core/src/tools/task-billing.js +31 -0
- package/src/platform/core/src/tools/task-format.js +264 -0
- package/src/platform/core/src/tools/task-usage.js +108 -0
- package/src/platform/core/src/version.js +4 -0
- package/src/platform/source.json +84 -0
- package/src/setup.mjs +9 -5
- package/src/mcp.mjs +0 -43
|
@@ -0,0 +1,186 @@
|
|
|
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 { randomUUID } from 'node:crypto';
|
|
4
|
+
import { currentRequestCredentials, currentClientName } from '../request-context.js';
|
|
5
|
+
import { MCP_VERSION } from '../version.js';
|
|
6
|
+
export const DEFAULT_READ_TIMEOUT_MS = 15_000;
|
|
7
|
+
export const DEFAULT_WRITE_TIMEOUT_MS = 120_000;
|
|
8
|
+
/** A generation submit only queues a task; keep it well inside the ~60 s tool-call limit of Codex and Cursor. */
|
|
9
|
+
export const DEFAULT_SUBMIT_TIMEOUT_MS = 30_000;
|
|
10
|
+
export const MAX_RETRY_DELAY_MS = 30_000;
|
|
11
|
+
/** Public site for console links in errors and results. */
|
|
12
|
+
export const EVOLINK_SITE = 'https://evolink.ai';
|
|
13
|
+
export const TOP_UP_URL = `${EVOLINK_SITE}/dashboard/credits`;
|
|
14
|
+
export const API_KEYS_URL = `${EVOLINK_SITE}/dashboard/keys`;
|
|
15
|
+
/**
|
|
16
|
+
* Where a signed-in user manages the EvoLink MCP limit and pause. Until the
|
|
17
|
+
* console has an MCP section, the account's internal MCP key is listed under
|
|
18
|
+
* API Keys (as MCP_KEY_NAME) and its limit and on/off switch are set there.
|
|
19
|
+
* The gateway's action_url, when it sends one, takes precedence.
|
|
20
|
+
*/
|
|
21
|
+
export const MCP_CONSOLE_URL = API_KEYS_URL;
|
|
22
|
+
/** Name of the account's internal MCP key in the API Keys list (set by the gateway). */
|
|
23
|
+
export const MCP_KEY_NAME = 'EvoLink MCP (OAuth)';
|
|
24
|
+
/** The gateway accepts Idempotency-Key values of 16–96 characters from this set. */
|
|
25
|
+
export const CLIENT_REQUEST_ID_PATTERN = /^[A-Za-z0-9._-]{16,96}$/;
|
|
26
|
+
export class RequestTimeoutError extends Error {
|
|
27
|
+
timeoutMs;
|
|
28
|
+
constructor(timeoutMs) {
|
|
29
|
+
super(`request timed out after ${timeoutMs}ms`);
|
|
30
|
+
this.timeoutMs = timeoutMs;
|
|
31
|
+
this.name = 'RequestTimeoutError';
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export class SubmissionNotStartedError extends Error {
|
|
35
|
+
cause;
|
|
36
|
+
constructor(cause) {
|
|
37
|
+
super('Generation was not submitted.');
|
|
38
|
+
this.cause = cause;
|
|
39
|
+
this.name = 'SubmissionNotStartedError';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export class PaidRequestOutcomeUnknownError extends Error {
|
|
43
|
+
cause;
|
|
44
|
+
idempotencyKey;
|
|
45
|
+
constructor(cause, idempotencyKey) {
|
|
46
|
+
super('paid request outcome is unknown after the bounded idempotent retry; do not create a new paid intent');
|
|
47
|
+
this.cause = cause;
|
|
48
|
+
this.idempotencyKey = idempotencyKey;
|
|
49
|
+
this.name = 'PaidRequestOutcomeUnknownError';
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function newRunId() {
|
|
53
|
+
return `run_${randomUUID().replaceAll('-', '')}`;
|
|
54
|
+
}
|
|
55
|
+
/** Headers that tell the gateway this call came from the MCP server, which tool and which assistant. */
|
|
56
|
+
export function evoHeaders(tool) {
|
|
57
|
+
const headers = {
|
|
58
|
+
'X-Evo-Client': currentRequestCredentials()?.http?.client ?? 'mcp',
|
|
59
|
+
'X-Evo-Client-Version': currentRequestCredentials()?.http?.version ?? MCP_VERSION,
|
|
60
|
+
'X-Evo-Tool': tool,
|
|
61
|
+
};
|
|
62
|
+
const clientName = currentClientName();
|
|
63
|
+
if (clientName)
|
|
64
|
+
headers['X-Evo-Client-Name'] = clientName;
|
|
65
|
+
return headers;
|
|
66
|
+
}
|
|
67
|
+
/** Turns a console path such as /dashboard/credits into a full link; full https links pass through. */
|
|
68
|
+
export function siteUrl(pathOrUrl, fallback) {
|
|
69
|
+
const value = (pathOrUrl ?? '').trim();
|
|
70
|
+
try {
|
|
71
|
+
if (value.startsWith('//') || /[\\\u0000-\u0020]/.test(value))
|
|
72
|
+
return fallback;
|
|
73
|
+
const url = new URL(value, EVOLINK_SITE);
|
|
74
|
+
if (url.origin !== EVOLINK_SITE || url.username || url.password || url.hash
|
|
75
|
+
|| !['/dashboard/credits', '/dashboard/keys', '/dashboard/mcp'].includes(url.pathname))
|
|
76
|
+
return fallback;
|
|
77
|
+
// Only the documented console tab is accepted. Tracking is added locally.
|
|
78
|
+
if ([...url.searchParams].some(([key, v]) => key !== 'tab' || v !== 'mcp'))
|
|
79
|
+
return fallback;
|
|
80
|
+
return url.href;
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return fallback;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export function timeoutFromEnv(name, fallback) {
|
|
87
|
+
const raw = process.env[name];
|
|
88
|
+
if (!raw)
|
|
89
|
+
return fallback;
|
|
90
|
+
const parsed = Number(raw);
|
|
91
|
+
if (!Number.isInteger(parsed) || parsed < 1_000 || parsed > 600_000) {
|
|
92
|
+
throw new Error(`${name} must be an integer between 1000 and 600000 milliseconds`);
|
|
93
|
+
}
|
|
94
|
+
return parsed;
|
|
95
|
+
}
|
|
96
|
+
export function parseRetryAfter(value, nowMs = Date.now()) {
|
|
97
|
+
if (!value)
|
|
98
|
+
return undefined;
|
|
99
|
+
const seconds = Number(value.trim());
|
|
100
|
+
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
101
|
+
return Math.min(Math.ceil(seconds * 1000), MAX_RETRY_DELAY_MS);
|
|
102
|
+
}
|
|
103
|
+
const dateMs = Date.parse(value);
|
|
104
|
+
if (!Number.isFinite(dateMs))
|
|
105
|
+
return undefined;
|
|
106
|
+
return Math.min(Math.max(0, dateMs - nowMs), MAX_RETRY_DELAY_MS);
|
|
107
|
+
}
|
|
108
|
+
export function responseRequestId(headers) {
|
|
109
|
+
return headers.get('x-request-id')?.trim()
|
|
110
|
+
|| headers.get('x-oneapi-request-id')?.trim()
|
|
111
|
+
|| undefined;
|
|
112
|
+
}
|
|
113
|
+
export async function fetchWithTimeout(url, init, timeoutMs, fetchImpl) {
|
|
114
|
+
const controller = new AbortController();
|
|
115
|
+
const context = currentRequestCredentials()?.http;
|
|
116
|
+
const signals = [init.signal, context?.signal].filter((signal) => !!signal);
|
|
117
|
+
const abort = () => controller.abort();
|
|
118
|
+
for (const signal of signals) {
|
|
119
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
120
|
+
if (signal.aborted)
|
|
121
|
+
abort();
|
|
122
|
+
}
|
|
123
|
+
let timedOut = false;
|
|
124
|
+
const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
|
|
125
|
+
try {
|
|
126
|
+
const headers = new Headers(init.headers);
|
|
127
|
+
if (context?.userAgent)
|
|
128
|
+
headers.set('User-Agent', context.userAgent);
|
|
129
|
+
return await (fetchImpl ?? context?.fetch ?? fetch)(url, { ...init, headers,
|
|
130
|
+
...(context ? { redirect: 'error' } : {}), signal: controller.signal });
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
if (timedOut) {
|
|
134
|
+
throw new RequestTimeoutError(timeoutMs);
|
|
135
|
+
}
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
clearTimeout(timer);
|
|
140
|
+
for (const signal of signals)
|
|
141
|
+
signal.removeEventListener('abort', abort);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/** Bound body consumption as well as response headers. Cancelling a reader also closes stalled streams. */
|
|
145
|
+
export async function readJsonBody(response, timeoutMs = DEFAULT_READ_TIMEOUT_MS) {
|
|
146
|
+
const signal = currentRequestCredentials()?.http?.signal;
|
|
147
|
+
const reader = response.body?.getReader();
|
|
148
|
+
let timer;
|
|
149
|
+
let abort;
|
|
150
|
+
const read = async () => {
|
|
151
|
+
if (!reader)
|
|
152
|
+
return response.text();
|
|
153
|
+
const decoder = new TextDecoder();
|
|
154
|
+
let body = '';
|
|
155
|
+
for (;;) {
|
|
156
|
+
const chunk = await reader.read();
|
|
157
|
+
if (chunk.done)
|
|
158
|
+
return body + decoder.decode();
|
|
159
|
+
body += decoder.decode(chunk.value, { stream: true });
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
try {
|
|
163
|
+
const body = await Promise.race([read(), new Promise((_, reject) => {
|
|
164
|
+
const stop = (error) => { reject(error); void reader?.cancel().catch(() => undefined); };
|
|
165
|
+
timer = setTimeout(() => stop(new RequestTimeoutError(timeoutMs)), timeoutMs);
|
|
166
|
+
abort = () => stop(new Error('Request interrupted during response read'));
|
|
167
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
168
|
+
if (signal?.aborted)
|
|
169
|
+
abort();
|
|
170
|
+
})]);
|
|
171
|
+
if (!body)
|
|
172
|
+
return {};
|
|
173
|
+
try {
|
|
174
|
+
return JSON.parse(body);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return { message: body.slice(0, 2000) };
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
clearTimeout(timer);
|
|
182
|
+
if (abort)
|
|
183
|
+
signal?.removeEventListener('abort', abort);
|
|
184
|
+
reader?.releaseLock();
|
|
185
|
+
}
|
|
186
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
/** Published input fields are evidence of accepted references, not of visual quality. */
|
|
4
|
+
export function referenceInputs(spec) {
|
|
5
|
+
if (!spec)
|
|
6
|
+
return [];
|
|
7
|
+
const result = [];
|
|
8
|
+
for (const [parameter, value] of Object.entries(spec.params)) {
|
|
9
|
+
let kind;
|
|
10
|
+
if (/^(?:.*_)?image_urls?$|^(?:images|image|input_image|first_frame|last_frame)$/.test(parameter))
|
|
11
|
+
kind = 'image';
|
|
12
|
+
else if (/^(?:.*_)?video_urls?$|^videos$/.test(parameter))
|
|
13
|
+
kind = 'video';
|
|
14
|
+
else if (/^(?:.*_)?audio_urls?$|^audios$/.test(parameter))
|
|
15
|
+
kind = 'audio';
|
|
16
|
+
else if (parameter === 'source_task_id')
|
|
17
|
+
kind = 'task';
|
|
18
|
+
else if (parameter === 'voice_id' || parameter === 'persona_id')
|
|
19
|
+
kind = 'resource';
|
|
20
|
+
if (kind)
|
|
21
|
+
result.push({ parameter, kind, required: !!value.required, multiple: value.type === 'array' });
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
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 { findModelParams } from '../data/model-params.js';
|
|
4
|
+
import { currentRequestCredentials } from '../request-context.js';
|
|
5
|
+
import { getAvailableModelIds } from './api-client.js';
|
|
6
|
+
import { currentModels } from './catalog-client.js';
|
|
7
|
+
import { closestMatches } from './param-validator.js';
|
|
8
|
+
import { getPricing } from './pricing-client.js';
|
|
9
|
+
function isMediaKind(value) {
|
|
10
|
+
return value === 'image' || value === 'video' || value === 'audio';
|
|
11
|
+
}
|
|
12
|
+
/** Live available IDs are authoritative; their published aliases join documentation and prices. */
|
|
13
|
+
export async function loadCatalog(config, pricingOptions = {}) {
|
|
14
|
+
const live = await currentModels();
|
|
15
|
+
// /v1/models is credential-specific. OAuth currently allows only media/task/credit
|
|
16
|
+
// routes, so its catalog uses public health (enabled abilities/channels), not a rejected call.
|
|
17
|
+
let allowed;
|
|
18
|
+
if (config && !currentRequestCredentials()?.serviceChannel) {
|
|
19
|
+
allowed = new Set((await getAvailableModelIds(config)).map(id => id.toLowerCase()));
|
|
20
|
+
}
|
|
21
|
+
const entries = new Map();
|
|
22
|
+
for (const model of live.models) {
|
|
23
|
+
if (model.lifecycle === 'retired' || !live.available.has(model.model_id.toLowerCase()))
|
|
24
|
+
continue;
|
|
25
|
+
const names = [model.model_id, ...model.aliases];
|
|
26
|
+
if (allowed && !names.some(name => allowed.has(name.toLowerCase())))
|
|
27
|
+
continue;
|
|
28
|
+
const spec = names.map(findModelParams).find(Boolean);
|
|
29
|
+
const kind = model.capabilities.find(isMediaKind);
|
|
30
|
+
if (!kind || (spec && spec.kind !== kind))
|
|
31
|
+
continue;
|
|
32
|
+
const protocol = { image: 'openai-images', video: 'evolink-video-generations', audio: 'openai-audio' }[kind];
|
|
33
|
+
if (!spec && !model.protocols.includes(protocol))
|
|
34
|
+
continue;
|
|
35
|
+
entries.set(model.model_id, { id: model.model_id, kind, aliases: model.aliases, title: model.display_name,
|
|
36
|
+
...(spec ? { spec: { ...spec, model: model.model_id } } : {}) });
|
|
37
|
+
}
|
|
38
|
+
let pricingWarning;
|
|
39
|
+
try {
|
|
40
|
+
const pricing = await getPricing(pricingOptions);
|
|
41
|
+
if (pricing.source === 'stale-cache')
|
|
42
|
+
pricingWarning = 'Prices could not be refreshed; showing the last known prices.';
|
|
43
|
+
for (const entry of entries.values()) {
|
|
44
|
+
const prices = [entry.id, ...(entry.aliases ?? [])].flatMap(name => [...pricing.models.values()].filter(price => price.id.toLowerCase() === name.toLowerCase()));
|
|
45
|
+
if (prices.length)
|
|
46
|
+
entry.priced = { ...prices[0], id: entry.id, pricingIncomplete: prices.some(model => model.pricingIncomplete), prices: [...new Map(prices.flatMap(model => model.prices).map(price => [price.sku_id, price])).values()] };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
pricingWarning = `Prices are unavailable right now (${error instanceof Error ? error.message : 'unknown error'}).`;
|
|
51
|
+
}
|
|
52
|
+
return { entries: [...entries.values()], pricingWarning };
|
|
53
|
+
}
|
|
54
|
+
export function findEntry(catalog, id) {
|
|
55
|
+
const lower = id.trim().toLowerCase();
|
|
56
|
+
return catalog.entries.find(entry => entry.id.toLowerCase() === lower)
|
|
57
|
+
?? catalog.entries.find(entry => entry.aliases?.some(alias => alias.toLowerCase() === lower));
|
|
58
|
+
}
|
|
59
|
+
export function suggestModels(catalog, id, kind) {
|
|
60
|
+
const pool = catalog.entries.filter(entry => !kind || entry.kind === kind).map(entry => entry.id);
|
|
61
|
+
return closestMatches(id, pool, 5);
|
|
62
|
+
}
|
|
63
|
+
/** Looks a model up for one request; prices are best effort. */
|
|
64
|
+
export async function resolveModel(id, config, pricingOptions = {}) {
|
|
65
|
+
const catalog = await loadCatalog(config, pricingOptions);
|
|
66
|
+
const entry = findEntry(catalog, id);
|
|
67
|
+
return { catalog, entry };
|
|
68
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
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 { startingPrice } from './pricing-client.js';
|
|
4
|
+
/** Editorial platform preferences, not measured popularity or a quality ranking.
|
|
5
|
+
* Only live catalog entries with documented inputs and published rates qualify.
|
|
6
|
+
* Specialized editing routes remain searchable without a general-generation boost.
|
|
7
|
+
*/
|
|
8
|
+
const PREFERENCES = [
|
|
9
|
+
{ kind: 'image', pattern: /^gpt-image-2\.5-(flare|sunburst)$/, family: 'gpt-image-2.5', useCase: 'image_generation' },
|
|
10
|
+
{ kind: 'image', pattern: /^gpt-image-2$/, family: 'gpt-image-2', useCase: 'image_generation' },
|
|
11
|
+
{ kind: 'image', pattern: /^doubao-seedream-5\.0-(flash|lite|pro)$/, family: 'seedream-5.0', useCase: 'image_generation' },
|
|
12
|
+
{ kind: 'video', pattern: /^seedance-2\.5-(text|image|reference)-to-video$/, family: 'seedance-2.5', useCase: 'video_generation' },
|
|
13
|
+
{ kind: 'video', pattern: /^seedance-2\.0-(?:(fast|mini)-)?(text|image|reference)-to-video$/, family: 'seedance-2.0', useCase: 'video_generation' },
|
|
14
|
+
{ kind: 'video', pattern: /^wan3\.0-(?:prime-)?(text-to-video|image-to-video|reference-video)$/, family: 'wan3.0', useCase: 'video_generation' },
|
|
15
|
+
{ kind: 'audio', pattern: /^suno-v6(?:-(mini|wild))?$/, family: 'suno-v6', useCase: 'music' },
|
|
16
|
+
];
|
|
17
|
+
export function modelPreference(entry) {
|
|
18
|
+
if (!entry.spec || !entry.priced || !startingPrice(entry.priced))
|
|
19
|
+
return undefined;
|
|
20
|
+
const priority = PREFERENCES.findIndex(item => item.kind === entry.kind && item.pattern.test(entry.id));
|
|
21
|
+
if (priority < 0)
|
|
22
|
+
return undefined;
|
|
23
|
+
const item = PREFERENCES[priority];
|
|
24
|
+
return { priority, basis: 'platform_preference', family: item.family, use_case: item.useCase };
|
|
25
|
+
}
|
|
26
|
+
export const MODEL_SELECTION_GUIDANCE = [
|
|
27
|
+
'Respect the user\'s explicit model/provider choice, required capabilities and budget before platform preferences.',
|
|
28
|
+
'For an unspecified model, consider available GPT Image 2.5/2 and Seedream 5.0 for images, Seedance 2.5/2.0 and Wan 3.0 for videos, and Suno v6 for music.',
|
|
29
|
+
'Use speech models for narration/TTS; Suno is a music preference, not a speech default.',
|
|
30
|
+
'Search the preferred families with search_models, then compare suitable candidates with get_model for reference inputs, output settings and billing; choose the correct text/image/reference/edit route.',
|
|
31
|
+
'Explain briefly why the chosen model fits. Fall back to other available models when preferences do not fit the task or budget.',
|
|
32
|
+
'Search order and platform_preference labels are editorial discovery hints, not measured popularity, release dates, quality rankings or the total task cost.',
|
|
33
|
+
'Do not automatically select the first result or a Beta model. Prefer a suitable non-Beta route when comparable, and explain why if choosing Beta.',
|
|
34
|
+
'Do not invent model IDs, availability, release dates, parameters or prices; missing documentation or rates must be resolved or disclosed before proposing a paid call.',
|
|
35
|
+
].join(' ');
|
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
/** Parameters an assistant may not set through MCP, with the reason shown to it. */
|
|
4
|
+
const BLOCKED_PARAMS = {
|
|
5
|
+
callback_url: 'callbacks are not available through MCP; use get_task to wait for the result',
|
|
6
|
+
};
|
|
7
|
+
/** Levenshtein distance, capped for long strings. */
|
|
8
|
+
function distance(a, b) {
|
|
9
|
+
if (a === b)
|
|
10
|
+
return 0;
|
|
11
|
+
const rows = a.length + 1;
|
|
12
|
+
const cols = b.length + 1;
|
|
13
|
+
let previous = Array.from({ length: cols }, (_, j) => j);
|
|
14
|
+
for (let i = 1; i < rows; i++) {
|
|
15
|
+
const current = [i];
|
|
16
|
+
for (let j = 1; j < cols; j++) {
|
|
17
|
+
current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
18
|
+
}
|
|
19
|
+
previous = current;
|
|
20
|
+
}
|
|
21
|
+
return previous[cols - 1];
|
|
22
|
+
}
|
|
23
|
+
/** Up to `limit` candidates that look like `value`, best first. */
|
|
24
|
+
export function closestMatches(value, candidates, limit = 3) {
|
|
25
|
+
const needle = value.toLowerCase();
|
|
26
|
+
return candidates
|
|
27
|
+
.map(candidate => {
|
|
28
|
+
const lower = candidate.toLowerCase();
|
|
29
|
+
const contains = lower.includes(needle) || needle.includes(lower);
|
|
30
|
+
const score = distance(needle, lower) / Math.max(needle.length, lower.length, 1) - (contains ? 0.5 : 0);
|
|
31
|
+
return { candidate, score };
|
|
32
|
+
})
|
|
33
|
+
.filter(item => item.score <= 0.45)
|
|
34
|
+
.sort((a, b) => a.score - b.score || a.candidate.localeCompare(b.candidate))
|
|
35
|
+
.slice(0, limit)
|
|
36
|
+
.map(item => item.candidate);
|
|
37
|
+
}
|
|
38
|
+
function describeType(type) {
|
|
39
|
+
return type.split('|').map(part => (part === 'integer' ? 'a whole number' : part === 'array' ? 'a list' : `a ${part}`)).join(' or ');
|
|
40
|
+
}
|
|
41
|
+
function matchesType(type, value) {
|
|
42
|
+
if (!type)
|
|
43
|
+
return true;
|
|
44
|
+
return type.split('|').some(part => {
|
|
45
|
+
switch (part) {
|
|
46
|
+
case 'string': return typeof value === 'string';
|
|
47
|
+
case 'integer': return typeof value === 'number' && Number.isInteger(value);
|
|
48
|
+
case 'number': return typeof value === 'number' && Number.isFinite(value);
|
|
49
|
+
case 'boolean': return typeof value === 'boolean';
|
|
50
|
+
case 'array': return Array.isArray(value);
|
|
51
|
+
case 'object': return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
52
|
+
case 'null': return value === null;
|
|
53
|
+
default: return true;
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function show(value) {
|
|
58
|
+
const json = JSON.stringify(value);
|
|
59
|
+
return json && json.length > 60 ? `${json.slice(0, 57)}…` : json ?? String(value);
|
|
60
|
+
}
|
|
61
|
+
function checkValue(name, spec, value, result) {
|
|
62
|
+
if (value === undefined)
|
|
63
|
+
return;
|
|
64
|
+
if (spec.anyOf?.length) {
|
|
65
|
+
const alternatives = spec.anyOf.map(option => {
|
|
66
|
+
const branch = { errors: [], warnings: [] };
|
|
67
|
+
checkValue(name, option, value, branch);
|
|
68
|
+
return branch;
|
|
69
|
+
});
|
|
70
|
+
if (alternatives.every(branch => branch.errors.length > 0)) {
|
|
71
|
+
result.errors.push({ param: name, problem: `must match one of the documented alternatives (${alternatives.map(branch => branch.errors.map(issue => issue.problem).join(' ')).join(' OR ')}).` });
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (!matchesType(spec.type, value)) {
|
|
76
|
+
const numericString = typeof value === 'string' && value.trim() !== '' && !Number.isNaN(Number(value));
|
|
77
|
+
const hint = numericString && /integer|number/.test(spec.type ?? '') ? ` Use ${Number(value)} (a number), not "${value}".` : '';
|
|
78
|
+
result.errors.push({ param: name, problem: `must be ${describeType(spec.type)}, got ${show(value)}.${hint}` });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (spec.enum && spec.enum.length > 0 && (typeof value !== 'object' || value === null)) {
|
|
82
|
+
if (!spec.enum.some(option => option === value)) {
|
|
83
|
+
const caseMatch = typeof value === 'string'
|
|
84
|
+
? spec.enum.find(option => typeof option === 'string' && option.toLowerCase() === value.toLowerCase())
|
|
85
|
+
: undefined;
|
|
86
|
+
result.errors.push({
|
|
87
|
+
param: name,
|
|
88
|
+
problem: caseMatch !== undefined
|
|
89
|
+
? `use ${show(caseMatch)} (values are case-sensitive), got ${show(value)}.`
|
|
90
|
+
: `must be one of ${spec.enum.map(show).join(', ')}; got ${show(value)}.`,
|
|
91
|
+
});
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (typeof value === 'number') {
|
|
96
|
+
if (spec.minimum !== undefined && value < spec.minimum)
|
|
97
|
+
result.errors.push({ param: name, problem: `must be at least ${spec.minimum}, got ${value}.` });
|
|
98
|
+
if (spec.maximum !== undefined && value > spec.maximum)
|
|
99
|
+
result.errors.push({ param: name, problem: `must be at most ${spec.maximum}, got ${value}.` });
|
|
100
|
+
if (spec.exclusiveMinimum !== undefined && value <= spec.exclusiveMinimum)
|
|
101
|
+
result.errors.push({ param: name, problem: `must be greater than ${spec.exclusiveMinimum}, got ${value}.` });
|
|
102
|
+
if (spec.exclusiveMaximum !== undefined && value >= spec.exclusiveMaximum)
|
|
103
|
+
result.errors.push({ param: name, problem: `must be less than ${spec.exclusiveMaximum}, got ${value}.` });
|
|
104
|
+
}
|
|
105
|
+
if (typeof value === 'string') {
|
|
106
|
+
if (spec.maxLength !== undefined && value.length > spec.maxLength) {
|
|
107
|
+
result.warnings.push({ param: name, problem: `is ${value.length} characters; the documented limit is ${spec.maxLength}. The gateway may reject it.` });
|
|
108
|
+
}
|
|
109
|
+
if (spec.minLength !== undefined && value.length < spec.minLength) {
|
|
110
|
+
result.errors.push({ param: name, problem: `must be at least ${spec.minLength} characters.` });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (Array.isArray(value)) {
|
|
114
|
+
if (spec.maxItems !== undefined && value.length > spec.maxItems)
|
|
115
|
+
result.errors.push({ param: name, problem: `allows at most ${spec.maxItems} items, got ${value.length}.` });
|
|
116
|
+
if (spec.minItems !== undefined && value.length < spec.minItems)
|
|
117
|
+
result.errors.push({ param: name, problem: `needs at least ${spec.minItems} items, got ${value.length}.` });
|
|
118
|
+
const items = spec.items;
|
|
119
|
+
if (items) {
|
|
120
|
+
value.forEach((item, position) => {
|
|
121
|
+
checkValue(`${name}[${position}]`, { type: items.type, enum: items.enum, properties: items.properties }, item, result);
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (spec.properties && value && typeof value === 'object' && !Array.isArray(value)) {
|
|
126
|
+
checkObject(name, spec.properties, value, result);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function checkObject(prefix, properties, value, result) {
|
|
130
|
+
const known = Object.keys(properties);
|
|
131
|
+
for (const [key, nested] of Object.entries(value)) {
|
|
132
|
+
const spec = properties[key];
|
|
133
|
+
const path = prefix ? `${prefix}.${key}` : key;
|
|
134
|
+
if (!spec) {
|
|
135
|
+
const suggestions = closestMatches(key, known);
|
|
136
|
+
result.errors.push({
|
|
137
|
+
param: path,
|
|
138
|
+
problem: `is not a parameter here.${suggestions.length ? ` Did you mean ${suggestions.map(s => `"${s}"`).join(' or ')}?` : ''} Allowed: ${known.join(', ') || 'none'}.`,
|
|
139
|
+
});
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
checkValue(path, spec, nested, result);
|
|
143
|
+
}
|
|
144
|
+
for (const [key, spec] of Object.entries(properties)) {
|
|
145
|
+
if (spec.required && value[key] === undefined) {
|
|
146
|
+
result.errors.push({ param: prefix ? `${prefix}.${key}` : key, problem: 'is required.' });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Checks a generation input against the documented parameters before
|
|
152
|
+
* anything is sent: unknown names, wrong types, values outside the documented
|
|
153
|
+
* choices or ranges. The gateway still validates the request in full.
|
|
154
|
+
*/
|
|
155
|
+
export function validateInput(spec, input) {
|
|
156
|
+
const result = { errors: [], warnings: [] };
|
|
157
|
+
const rest = {};
|
|
158
|
+
for (const [key, value] of Object.entries(input)) {
|
|
159
|
+
if (key === 'model') {
|
|
160
|
+
if (value !== undefined && value !== spec.model) {
|
|
161
|
+
result.errors.push({ param: 'model', problem: `set the model with the model argument, not inside input (input has ${show(value)}).` });
|
|
162
|
+
}
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (BLOCKED_PARAMS[key]) {
|
|
166
|
+
result.errors.push({ param: key, problem: `${BLOCKED_PARAMS[key]}.` });
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
rest[key] = value;
|
|
170
|
+
}
|
|
171
|
+
checkObject('', spec.params, rest, result);
|
|
172
|
+
for (const group of spec.constraints?.mutuallyExclusive ?? []) {
|
|
173
|
+
const present = group.filter(name => Array.isArray(rest[name]) ? rest[name].length > 0 : rest[name] !== undefined && rest[name] !== null && rest[name] !== '');
|
|
174
|
+
if (present.length > 1)
|
|
175
|
+
result.errors.push({ param: present.join(', '), problem: 'are mutually exclusive; pass only one reference type.' });
|
|
176
|
+
}
|
|
177
|
+
const size = spec.constraints?.imageSize;
|
|
178
|
+
const value = size ? rest[size.param] : undefined;
|
|
179
|
+
if (size && typeof value === 'string' && !size.allowed.includes(value)) {
|
|
180
|
+
const pixels = /^(\d+)[x×](\d+)$/.exec(value);
|
|
181
|
+
if (!pixels || !size.allowPixels) {
|
|
182
|
+
result.errors.push({ param: size.param, problem: `must be one of ${size.allowed.join(', ')}${size.allowPixels ? ', or a valid WxH pixel size' : ''}.` });
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
const width = Number(pixels[1]), height = Number(pixels[2]), total = width * height;
|
|
186
|
+
if (!Number.isSafeInteger(total) || width < size.minEdge || height < size.minEdge || width > size.maxEdge || height > size.maxEdge
|
|
187
|
+
|| width % size.step !== 0 || height % size.step !== 0 || total < size.minPixels || total > size.maxPixels
|
|
188
|
+
|| Math.max(width, height) > size.maxRatio * Math.min(width, height)) {
|
|
189
|
+
result.errors.push({ param: size.param, problem: `requires edges ${size.minEdge}–${size.maxEdge}, multiples of ${size.step}, ${size.minPixels}–${size.maxPixels} pixels, and an aspect ratio at most ${size.maxRatio}:1.` });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (size?.ratioResolution && typeof value === 'string' && value !== 'auto' && rest.resolution !== undefined
|
|
194
|
+
&& String(rest.resolution).toUpperCase() !== size.ratioResolution) {
|
|
195
|
+
result.errors.push({ param: 'resolution', problem: `must be ${size.ratioResolution} when size is a ratio.` });
|
|
196
|
+
}
|
|
197
|
+
return result;
|
|
198
|
+
}
|
|
199
|
+
export function formatIssues(issues) {
|
|
200
|
+
return issues.map(issue => `- ${issue.param} ${issue.problem}`);
|
|
201
|
+
}
|