@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.
Files changed (52) hide show
  1. package/README.md +35 -6
  2. package/package.json +27 -8
  3. package/skills/evolink-cli/SKILL.md +5 -5
  4. package/skills/evolink-cli/references/capabilities.md +1 -1
  5. package/src/api.mjs +59 -0
  6. package/src/auth.mjs +6 -7
  7. package/src/cli.mjs +34 -30
  8. package/src/doctor.mjs +9 -6
  9. package/src/errors.mjs +21 -13
  10. package/src/files.mjs +61 -6
  11. package/src/help.mjs +8 -8
  12. package/src/media.mjs +11 -9
  13. package/src/network.mjs +12 -1
  14. package/src/oauth.mjs +90 -0
  15. package/src/platform/LICENSE +178 -0
  16. package/src/platform/NOTICE +6 -0
  17. package/src/platform/core/src/config.js +95 -0
  18. package/src/platform/core/src/data/model-constraints.js +37 -0
  19. package/src/platform/core/src/data/model-params.generated.js +4 -0
  20. package/src/platform/core/src/data/model-params.js +28 -0
  21. package/src/platform/core/src/platform-client.js +56 -0
  22. package/src/platform/core/src/platform-operations.js +22 -0
  23. package/src/platform/core/src/request-context.js +53 -0
  24. package/src/platform/core/src/services/api-client.js +232 -0
  25. package/src/platform/core/src/services/catalog-client.js +45 -0
  26. package/src/platform/core/src/services/error-handler.js +452 -0
  27. package/src/platform/core/src/services/file-client.js +165 -0
  28. package/src/platform/core/src/services/http-policy.js +186 -0
  29. package/src/platform/core/src/services/model-capabilities.js +24 -0
  30. package/src/platform/core/src/services/model-catalog.js +68 -0
  31. package/src/platform/core/src/services/model-recommendations.js +35 -0
  32. package/src/platform/core/src/services/param-validator.js +201 -0
  33. package/src/platform/core/src/services/pricing-client.js +451 -0
  34. package/src/platform/core/src/services/public-error.js +63 -0
  35. package/src/platform/core/src/services/utm.js +65 -0
  36. package/src/platform/core/src/tool-guidance.js +50 -0
  37. package/src/platform/core/src/tools/check-balance.js +90 -0
  38. package/src/platform/core/src/tools/discovery.js +86 -0
  39. package/src/platform/core/src/tools/estimate-cost.js +136 -0
  40. package/src/platform/core/src/tools/generate.js +237 -0
  41. package/src/platform/core/src/tools/get-model.js +146 -0
  42. package/src/platform/core/src/tools/get-task.js +57 -0
  43. package/src/platform/core/src/tools/list-tasks.js +170 -0
  44. package/src/platform/core/src/tools/search-models.js +115 -0
  45. package/src/platform/core/src/tools/shared.js +158 -0
  46. package/src/platform/core/src/tools/task-billing.js +31 -0
  47. package/src/platform/core/src/tools/task-format.js +264 -0
  48. package/src/platform/core/src/tools/task-usage.js +108 -0
  49. package/src/platform/core/src/version.js +4 -0
  50. package/src/platform/source.json +84 -0
  51. package/src/setup.mjs +9 -5
  52. package/src/mcp.mjs +0 -43
@@ -0,0 +1,452 @@
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 { publicIdentifier, publicLabel, publicNumber } from './public-error.js';
4
+ import { currentCredentialMode } from '../request-context.js';
5
+ import { API_KEYS_URL, MCP_CONSOLE_URL, MCP_KEY_NAME, TOP_UP_URL, siteUrl } from './http-policy.js';
6
+ import { trackedLink } from './utm.js';
7
+ /** Gateway display rate: 1 USD = 6.8 CNY and 1 CNY = 10 credits. */
8
+ export const CREDITS_PER_USD = 68;
9
+ const ACCOUNT_CODES = new Set(['insufficient_quota', 'insufficient_user_quota', 'quota_not_enough', 'account_balance_insufficient']);
10
+ const KEY_QUOTA_CODES = new Set(['insufficient_token_quota', 'key_quota_exhausted']);
11
+ const KEY_DAILY_CODES = new Set(['token_daily_quota_exceeded', 'key_daily_quota_exhausted']);
12
+ const CONTENT_CODES = new Set(['content_policy_violation', 'content_filter', 'sensitive_content', 'moderation_blocked', 'input_moderation_failed']);
13
+ const UNAVAILABLE_CODES = new Set(['no_available_channel', 'model_unavailable', 'channel_selection_failed']);
14
+ /** Hosted service channel (key custody A): the connection itself is gone and needs a new sign-in. */
15
+ const CONNECTION_ENDED_CODES = new Set(['connection_not_found', 'connection_revoked', 'session_inactive', 'session_expired', 'mcp_scope_missing']);
16
+ /** The hosted service, not the user's connection, was refused or sent a request the channel does not serve. */
17
+ const SERVICE_CODES = new Set(['mcp_service_unauthorized', 'mcp_connection_required', 'mcp_route_not_allowed']);
18
+ const DETAIL_FIELDS = [
19
+ 'key_name',
20
+ 'estimated_credits',
21
+ 'account_balance_credits',
22
+ 'total_limit_credits',
23
+ 'used_credits',
24
+ 'remaining_credits',
25
+ 'daily_limit_credits',
26
+ 'daily_used_credits',
27
+ 'reset_timezone',
28
+ 'allowed_models',
29
+ 'expired_at',
30
+ ];
31
+ function envelope(body) {
32
+ if (!body || typeof body !== 'object')
33
+ return {};
34
+ const record = body;
35
+ if (record.error && typeof record.error === 'object')
36
+ return record.error;
37
+ // files-api: { success: false, code, msg }; OAuth-style: { error: "x", error_description: "…" }
38
+ return {
39
+ code: typeof record.error === 'string' ? record.error : record.code,
40
+ message: record.msg ?? record.error_description ?? record.message,
41
+ };
42
+ }
43
+ function text(value) {
44
+ if (typeof value === 'string' && value.trim())
45
+ return value.trim();
46
+ if (typeof value === 'number' && Number.isFinite(value))
47
+ return String(value);
48
+ return undefined;
49
+ }
50
+ /**
51
+ * @param mcpLimits the key limits are the account's EvoLink MCP limit: a
52
+ * signed-in connection, or the gateway said so with limit_scope "mcp".
53
+ */
54
+ function categorize(status, code, mode, mcpLimits) {
55
+ const lower = code.toLowerCase();
56
+ if (ACCOUNT_CODES.has(lower))
57
+ return 'account_balance_insufficient';
58
+ if (KEY_QUOTA_CODES.has(lower))
59
+ return mcpLimits ? 'mcp_limit_reached' : 'key_quota_exhausted';
60
+ if (KEY_DAILY_CODES.has(lower))
61
+ return mcpLimits ? 'mcp_daily_limit_reached' : 'key_daily_quota_exhausted';
62
+ if (lower === 'mcp_paused')
63
+ return 'mcp_paused';
64
+ if (lower === 'mcp_key_expired')
65
+ return 'mcp_key_expired';
66
+ // EvoLink turned the MCP channel off (the gateway's MCPChannelEnabled switch): a 503, but not a model problem.
67
+ if (lower === 'mcp_channel_disabled')
68
+ return 'mcp_channel_disabled';
69
+ // The account's MCP key is only ever disabled by "pause all" in the console.
70
+ if (lower === 'key_disabled')
71
+ return mode === 'signed_in' ? 'mcp_paused' : 'key_disabled';
72
+ // A signed-in connection spends the account's MCP key, so an expired key is that key's expiry date, not the connection.
73
+ if (lower === 'key_expired')
74
+ return mode === 'signed_in' ? 'mcp_key_expired' : 'key_expired';
75
+ if (lower === 'key_model_not_allowed')
76
+ return 'model_not_allowed';
77
+ if (lower === 'idempotency_conflict')
78
+ return 'idempotency_conflict';
79
+ if (lower === 'paid_outcome_unknown')
80
+ return 'outcome_unknown';
81
+ if (CONTENT_CODES.has(lower))
82
+ return 'content_policy';
83
+ if (lower === 'service_unavailable')
84
+ return 'service_unavailable';
85
+ if (UNAVAILABLE_CODES.has(lower))
86
+ return 'model_unavailable';
87
+ if (CONNECTION_ENDED_CODES.has(lower))
88
+ return 'connection_ended';
89
+ if (lower === 'agent_session_unavailable')
90
+ return 'session_check_unavailable';
91
+ if (lower === 'mcp_connection_create_failed')
92
+ return 'connection_setup_failed';
93
+ if (SERVICE_CODES.has(lower))
94
+ return 'service_misconfigured';
95
+ // The gateway did not take the forwarded sign-in token, most likely because it expired during the call.
96
+ if (lower === 'mcp_token_invalid')
97
+ return 'sign_in_token_rejected';
98
+ if (lower === 'user_disabled')
99
+ return 'account_disabled';
100
+ // Upload tokens for signed-in connections (POST /v1/files/upload-token): a per-minute cap, and Redis being down.
101
+ if (lower === 'upload_token_rate_limited')
102
+ return 'rate_limited';
103
+ if (lower === 'upload_token_unavailable')
104
+ return 'server_error';
105
+ switch (status) {
106
+ case 401: return 'unauthorized';
107
+ case 402: return 'account_balance_insufficient';
108
+ case 403: return 'forbidden';
109
+ case 404: return 'not_found';
110
+ case 413: return 'request_too_large';
111
+ case 429: return 'rate_limited';
112
+ case 503: return 'service_unavailable';
113
+ }
114
+ if (status >= 500)
115
+ return 'server_error';
116
+ return 'invalid_request';
117
+ }
118
+ const RETRYABLE = new Set([
119
+ 'key_daily_quota_exhausted',
120
+ 'mcp_daily_limit_reached',
121
+ 'rate_limited',
122
+ 'model_unavailable',
123
+ 'service_unavailable',
124
+ 'outcome_unknown',
125
+ 'server_error',
126
+ 'session_check_unavailable',
127
+ 'connection_setup_failed',
128
+ 'sign_in_token_rejected',
129
+ ]);
130
+ /** Answers about the account's EvoLink MCP limit; their console link is the MCP settings, not API Keys. */
131
+ const MCP_LIMIT_CATEGORIES = new Set(['mcp_limit_reached', 'mcp_daily_limit_reached', 'mcp_paused', 'mcp_key_expired']);
132
+ const KEY_CATEGORIES = new Set([
133
+ 'key_quota_exhausted', 'key_daily_quota_exhausted', 'key_disabled', 'key_expired', 'model_not_allowed',
134
+ ]);
135
+ function credits(value) {
136
+ if (typeof value !== 'number' || !Number.isFinite(value))
137
+ return undefined;
138
+ return `${formatCredits(value)} credits (≈$${formatUsd(value / CREDITS_PER_USD)})`;
139
+ }
140
+ export function formatCredits(value) {
141
+ return Number(value.toFixed(4)).toString();
142
+ }
143
+ export function formatUsd(value) {
144
+ if (value === 0)
145
+ return '0';
146
+ if (Math.abs(value) >= 1)
147
+ return value.toFixed(2);
148
+ if (Math.abs(value) >= 0.01)
149
+ return value.toFixed(3);
150
+ return Number(value.toPrecision(2)).toString();
151
+ }
152
+ /** Sentences naming which limit stopped the request; the same words in every client. */
153
+ function headlineFor(category) {
154
+ switch (category) {
155
+ case 'mcp_limit_reached':
156
+ return 'EvoLink MCP spending limit reached. This is the limit set for MCP, not your account balance.';
157
+ case 'mcp_daily_limit_reached':
158
+ return 'EvoLink MCP daily limit reached. It resets at midnight; this is not your account balance.';
159
+ case 'mcp_paused':
160
+ return 'EvoLink MCP is paused for this account. Resume it in the console; you do not need to reconnect.';
161
+ case 'mcp_key_expired':
162
+ return 'EvoLink MCP key has expired. Extend or clear its expiry date in the console; you do not need to reconnect.';
163
+ case 'account_balance_insufficient':
164
+ return 'Your EvoLink account balance is too low for this request. The balance is shared by API, web and MCP.';
165
+ case 'key_quota_exhausted':
166
+ return 'This API key\'s spending limit is used up. This is the key\'s own limit, not your account balance.';
167
+ case 'key_daily_quota_exhausted':
168
+ return 'This API key\'s daily limit is used up. It resets at midnight; this is not your account balance.';
169
+ case 'connection_ended':
170
+ return 'This EvoLink connection was disconnected. Reconnect EvoLink in this client.';
171
+ // The gateway's own text ("Agent session validation…") is shared with the CLI and names an internal check.
172
+ case 'session_check_unavailable':
173
+ return 'EvoLink could not check this connection\'s sign-in just now. Retry in a minute; you do not need to reconnect.';
174
+ default:
175
+ return undefined;
176
+ }
177
+ }
178
+ /**
179
+ * Where the EvoLink MCP limit lives: while it is a key in API Keys, name the key
180
+ * so the user finds it; a dedicated MCP page needs no key name.
181
+ */
182
+ function mcpLimitPlace(url, details) {
183
+ return /\/dashboard\/keys(?:[?#]|$)/.test(url)
184
+ ? `${url} (the key named "${text(details.key_name) ?? MCP_KEY_NAME}")`
185
+ : url;
186
+ }
187
+ /** "Limit: …; used: …; left: …." from whatever figures the gateway attached. */
188
+ function limitFigures(details, label) {
189
+ const parts = [
190
+ credits(details.total_limit_credits) && `${label}: ${credits(details.total_limit_credits)}`,
191
+ credits(details.used_credits) && `used: ${credits(details.used_credits)}`,
192
+ credits(details.remaining_credits) && `left: ${credits(details.remaining_credits)}`,
193
+ ].filter(Boolean);
194
+ return parts.length ? `${parts.join('; ')}.` : '';
195
+ }
196
+ function sentences(...parts) {
197
+ return parts.filter(Boolean).join(' ');
198
+ }
199
+ function nextStep(category, info, mode) {
200
+ const details = info.details ?? {};
201
+ const action = info.action_url;
202
+ const needed = credits(details.estimated_credits);
203
+ const balance = credits(details.account_balance_credits);
204
+ const zone = text(details.reset_timezone);
205
+ switch (category) {
206
+ case 'account_balance_insufficient':
207
+ return sentences(balance && `Balance: ${balance}.`, needed && `This request needs about ${needed}.`, `Ask the user to top up at ${action ?? trackedLink(TOP_UP_URL, 'top_up')}, then retry.`);
208
+ case 'mcp_limit_reached':
209
+ return sentences(limitFigures(details, 'EvoLink MCP limit'), needed && `This request needs about ${needed}.`, balance && `Account balance: ${balance} (not the problem).`, `Ask the user to raise or remove the EvoLink MCP limit at ${mcpLimitPlace(action ?? trackedLink(MCP_CONSOLE_URL, 'api_keys'), details)}; it is shared by every assistant connected to their EvoLink account, including the CLI.`, 'Do not retry until they have changed it.');
210
+ case 'mcp_daily_limit_reached': {
211
+ const used = credits(details.daily_used_credits);
212
+ const limit = credits(details.daily_limit_credits);
213
+ return sentences(used && limit && `Today's EvoLink MCP spending: ${used} of the ${limit} daily limit.`, `It resets automatically at midnight${zone ? ` (${zone})` : ''}.`, balance && `Account balance: ${balance} (not the problem).`, `To continue today, ask the user to raise the EvoLink MCP daily limit at ${mcpLimitPlace(action ?? trackedLink(MCP_CONSOLE_URL, 'api_keys'), details)}; this daily limit is shared by CLI and MCP.`);
214
+ }
215
+ case 'mcp_paused':
216
+ return `Ask the user to resume EvoLink MCP at ${mcpLimitPlace(action ?? trackedLink(MCP_CONSOLE_URL, 'api_keys'), details)} (switch it back on; this resumes the shared CLI and MCP key). Do not ask them to reconnect, and do not retry until it is resumed.`;
217
+ case 'mcp_key_expired': {
218
+ const expiredAt = typeof details.expired_at === 'number' && Number.isFinite(details.expired_at) && details.expired_at > 0
219
+ ? new Date(details.expired_at * 1000).toISOString().slice(0, 10)
220
+ : undefined;
221
+ return sentences(expiredAt && `The EvoLink MCP key expired on ${expiredAt} (UTC).`, `Ask the user to extend or clear the expiry date of the EvoLink MCP key at ${mcpLimitPlace(action ?? trackedLink(MCP_CONSOLE_URL, 'api_keys'), details)}.`, 'Do not ask them to reconnect, and do not retry until it is changed.');
222
+ }
223
+ case 'key_quota_exhausted': {
224
+ const name = text(details.key_name);
225
+ return sentences(limitFigures(details, name ? `Limit of API key "${name}"` : 'API key limit'), needed && `This request needs about ${needed}.`, balance && `Account balance: ${balance} (not the problem).`, `Raise this API key's limit at ${action ?? trackedLink(API_KEYS_URL, 'api_keys')}, or use another key.`);
226
+ }
227
+ case 'key_daily_quota_exhausted':
228
+ return `It resets automatically at midnight${zone ? ` (${zone})` : ''}; to continue today, raise this API key's daily limit at ${action ?? trackedLink(API_KEYS_URL, 'api_keys')}.`;
229
+ case 'key_disabled':
230
+ return `This API key is disabled. Enable it at ${action ?? trackedLink(API_KEYS_URL, 'api_keys')} or use another key.`;
231
+ case 'key_expired':
232
+ return `This API key has expired. Extend it at ${action ?? trackedLink(API_KEYS_URL, 'api_keys')} or use another key.`;
233
+ case 'model_not_allowed': {
234
+ const allowed = Array.isArray(details.allowed_models) ? details.allowed_models.slice(0, 20).join(', ') : '';
235
+ return `This key may not use this model.${allowed ? ` Allowed models: ${allowed}.` : ''} Pick an allowed model, or change the key's model list at ${action ?? trackedLink(API_KEYS_URL, 'api_keys')}.`;
236
+ }
237
+ case 'unauthorized':
238
+ if (mode === 'signed_in')
239
+ return 'The EvoLink connection was rejected. Ask the user to reconnect EvoLink in this client.';
240
+ return mode === 'api_key'
241
+ ? 'The API key was rejected. Ask the user to check the EvoLink API key configured in this client.'
242
+ : 'The API key was rejected. Check EVOLINK_API_KEY or the configured API-key credential helper. The browser CLI uses `evolink auth login` independently.';
243
+ case 'forbidden':
244
+ return 'Access to this resource is denied for this account.';
245
+ case 'rate_limited':
246
+ return `Too many requests. Wait ${info.retry_after_seconds ?? 30} seconds before retrying; do not loop paid submissions.`;
247
+ case 'invalid_request':
248
+ return 'Check the supplied parameters before retrying. get_model lists every parameter with its allowed values.';
249
+ case 'not_found':
250
+ return 'Nothing matches this ID. Check it, or use list_tasks to find recent tasks.';
251
+ case 'content_policy':
252
+ return 'The prompt or input was blocked by content review. Review the applicable content policy and revise the input. Do not bypass content review.';
253
+ case 'service_unavailable':
254
+ return 'EvoLink is temporarily unavailable. Check the original task or request ID before retrying a paid submission.';
255
+ case 'model_unavailable':
256
+ return 'The model is temporarily unavailable. Retry in a minute, or pick another model with search_models.';
257
+ case 'idempotency_conflict':
258
+ return 'This client_request_id was already used for a different request. Recover the original request first. A different generation requires a new estimate and explicit user approval; it is a separately paid task.';
259
+ case 'outcome_unknown':
260
+ return 'The earlier submission with this client_request_id is still being processed or its outcome is unknown. Do not submit it again with a new id: wait a minute and retry with the same client_request_id, or look it up with list_tasks.';
261
+ case 'request_too_large':
262
+ return 'The request is too large. Pass big files as links (a public URL, or one from upload_file where it is available) instead of inline data.';
263
+ case 'server_error':
264
+ return 'EvoLink had a temporary error. Retry in a minute; for paid generations check list_tasks first so the task is not submitted twice.';
265
+ case 'connection_ended':
266
+ return 'This EvoLink connection is no longer active (it was revoked, expired, or signed out). Ask the user to reconnect the existing EvoLink connection in this client instead of adding a new one.';
267
+ case 'session_check_unavailable':
268
+ return 'EvoLink sign-in verification is temporarily unavailable. Retry in a minute; do not reconnect.';
269
+ case 'connection_setup_failed':
270
+ return 'EvoLink could not set up this connection yet. Retry in a minute.';
271
+ case 'service_misconfigured':
272
+ return 'The EvoLink MCP service could not authenticate this request. This is a server-side problem, not the user\'s connection: do not reconnect, and try again later.';
273
+ case 'mcp_channel_disabled':
274
+ return 'EvoLink has temporarily turned off MCP access. Try again later; switching models, retrying right away or reconnecting will not help.';
275
+ case 'sign_in_token_rejected':
276
+ return 'EvoLink did not accept this connection\'s sign-in token; it may have just expired. Retry the call, which carries a refreshed token; if it keeps failing, ask the user to reconnect the existing EvoLink connection in this client.';
277
+ case 'account_disabled':
278
+ return 'This EvoLink account is disabled. Ask the user to contact EvoLink support.';
279
+ }
280
+ }
281
+ /** Classifies one non-2xx gateway or files-api response. */
282
+ export function classifyGatewayError(status, body, retryAfterMs, headerRequestId) {
283
+ const error = envelope(body);
284
+ const rawCode = text(error.code)?.toLowerCase();
285
+ const knownCodes = new Set([...ACCOUNT_CODES, ...KEY_QUOTA_CODES, ...KEY_DAILY_CODES, ...CONTENT_CODES, ...UNAVAILABLE_CODES, ...CONNECTION_ENDED_CODES, ...SERVICE_CODES,
286
+ 'mcp_paused', 'mcp_key_expired', 'mcp_channel_disabled', 'key_disabled', 'key_expired', 'key_model_not_allowed', 'idempotency_conflict', 'paid_outcome_unknown', 'agent_session_unavailable', 'mcp_connection_create_failed', 'mcp_token_invalid', 'user_disabled', 'upload_token_rate_limited', 'upload_token_unavailable', 'service_unavailable', 'invalid_token', 'internal_error', 'invalid_parameters', 'invalid_parameter', 'invalid_media_url', 'invalid_request']);
287
+ const code = rawCode && knownCodes.has(rawCode) ? rawCode : undefined;
288
+ const mode = currentCredentialMode();
289
+ const mcpScope = text(error.limit_scope)?.toLowerCase() === 'mcp';
290
+ const category = categorize(status, code ?? '', mode, mcpScope || mode === 'signed_in');
291
+ const requestId = publicIdentifier(error.request_id) ?? publicIdentifier(headerRequestId);
292
+ // Remote prose, stack traces and suggestions are never promoted into assistant instructions.
293
+ let message = headlineFor(category) ?? {
294
+ invalid_request: 'EvoLink rejected the request parameters. Check get_model for the current rules.',
295
+ content_policy: 'The prompt or input was blocked by content review.',
296
+ unauthorized: 'EvoLink could not authenticate this request.',
297
+ forbidden: 'Access to this resource is denied.',
298
+ not_found: 'The requested resource was not found.',
299
+ rate_limited: 'The request rate limit was reached.',
300
+ request_too_large: 'The request exceeds the allowed size.',
301
+ model_unavailable: 'The requested model is temporarily unavailable.',
302
+ service_unavailable: 'EvoLink is temporarily unavailable.',
303
+ idempotency_conflict: 'This request ID is already associated with a different request.',
304
+ outcome_unknown: 'The earlier submission outcome is unknown.',
305
+ }[category] ?? 'EvoLink could not complete this operation.';
306
+ if (status === 415 && category === 'invalid_request')
307
+ message = 'The request uses an unsupported file type or media format.';
308
+ const details = {};
309
+ for (const field of DETAIL_FIELDS) {
310
+ const value = error[field];
311
+ if (field.endsWith('_credits') || field === 'expired_at') {
312
+ const n = publicNumber(value);
313
+ if (n !== undefined && (field !== 'expired_at' || n <= 253402300799))
314
+ details[field] = n;
315
+ }
316
+ else if (field === 'allowed_models' && Array.isArray(value)) {
317
+ details[field] = value.slice(0, 20).map(publicIdentifier).filter(Boolean);
318
+ }
319
+ else {
320
+ const label = publicLabel(value);
321
+ if (label)
322
+ details[field] = label;
323
+ }
324
+ }
325
+ const param = typeof error.param === 'string' && /^[A-Za-z_][A-Za-z0-9_.\[\]]{0,100}$/.test(error.param) ? error.param : undefined;
326
+ if (category === 'invalid_request' && param) {
327
+ message += ` Parameter: ${param}.`;
328
+ for (const field of ['min', 'max']) {
329
+ const n = publicNumber(error[field]);
330
+ if (n !== undefined)
331
+ details[field] = n;
332
+ }
333
+ if (Array.isArray(error.allowed_values))
334
+ details.allowed_values = error.allowed_values.slice(0, 30)
335
+ .filter(value => publicNumber(value) !== undefined || publicLabel(value) !== undefined);
336
+ }
337
+ let actionUrl;
338
+ if (category === 'account_balance_insufficient') {
339
+ actionUrl = trackedLink(siteUrl(text(error.action_url), TOP_UP_URL), 'top_up');
340
+ }
341
+ else if (MCP_LIMIT_CATEGORIES.has(category)) {
342
+ actionUrl = trackedLink(siteUrl(text(error.action_url), MCP_CONSOLE_URL), 'api_keys');
343
+ }
344
+ else if (KEY_CATEGORIES.has(category)) {
345
+ actionUrl = trackedLink(siteUrl(text(error.action_url), API_KEYS_URL), 'api_keys');
346
+ }
347
+ const headline = headlineFor(category);
348
+ const info = {
349
+ status,
350
+ category,
351
+ ...(headline ? { headline } : {}),
352
+ code,
353
+ ...(param ? { param } : {}),
354
+ message,
355
+ next_step: '',
356
+ retryable: RETRYABLE.has(category),
357
+ retry_after_seconds: retryAfterMs !== undefined ? Math.max(1, Math.ceil(retryAfterMs / 1000)) : undefined,
358
+ action_url: actionUrl,
359
+ request_id: requestId,
360
+ details: Object.keys(details).length > 0 ? details : undefined,
361
+ };
362
+ info.next_step = nextStep(category, info, mode);
363
+ return info;
364
+ }
365
+ /**
366
+ * With a headline the first line says which limit it is; the gateway's own
367
+ * sentence is left out because it speaks of "API key …" even for the MCP key.
368
+ */
369
+ export function formatGatewayError(info) {
370
+ const status = `${info.status}${info.code ? ` ${info.code}` : ''}`;
371
+ const lines = info.headline
372
+ ? [info.headline, `Next step: ${info.next_step}`, `Error: HTTP ${status}`]
373
+ : [`[${status}] ${info.message}`, `Next step: ${info.next_step}`];
374
+ if (info.request_id)
375
+ lines.push(`Request ID: ${info.request_id}`);
376
+ return lines.join('\n');
377
+ }
378
+ export function formatApiError(status, body) {
379
+ return formatGatewayError(classifyGatewayError(status, body));
380
+ }
381
+ const TASK_ERROR_MAP = {
382
+ content_policy_violation: {
383
+ suggestion: 'Review the applicable content policy and revise the input. Do not bypass content review.',
384
+ retryable: false,
385
+ },
386
+ invalid_parameters: {
387
+ suggestion: 'Check the parameter values (prompt length, image size, duration, resolution) against get_model.',
388
+ retryable: false,
389
+ },
390
+ image_dimension_mismatch: {
391
+ suggestion: 'Check the input dimensions and aspect ratio against this model’s get_model rules.',
392
+ retryable: false,
393
+ },
394
+ image_processing_error: {
395
+ suggestion: 'The input image could not be processed. Check accessibility, format and size against this model’s get_model rules.',
396
+ retryable: false,
397
+ },
398
+ request_cancelled: {
399
+ suggestion: 'The task was cancelled. Check this task’s billing state before deciding whether to request another generation.',
400
+ retryable: false,
401
+ },
402
+ resource_not_found: {
403
+ suggestion: 'The task or an input resource was not found or has expired. Check the IDs and links.',
404
+ retryable: false,
405
+ },
406
+ generation_timeout: {
407
+ suggestion: 'The generation timed out. Check the original task and its billing state before considering another generation.',
408
+ retryable: true,
409
+ },
410
+ quota_exceeded: {
411
+ suggestion: `The generation encountered a quota limit. Check balance and limits before requesting another generation; top up at ${TOP_UP_URL} if the balance is low.`,
412
+ retryable: true,
413
+ },
414
+ resource_exhausted: {
415
+ suggestion: 'Generation capacity was temporarily exhausted. Wait before considering another generation.',
416
+ retryable: true,
417
+ },
418
+ generation_failed_no_content: {
419
+ suggestion: 'The model returned no output. The cause is not established; retain the task ID and contact EvoLink support if needed.',
420
+ retryable: false,
421
+ },
422
+ service_error: {
423
+ suggestion: 'The generation service reported an error. Retain the task ID and check its billing state.',
424
+ retryable: true,
425
+ },
426
+ service_unavailable: {
427
+ suggestion: 'The generation service was temporarily unavailable. Retain the task ID and check its billing state.',
428
+ retryable: true,
429
+ },
430
+ unknown_error: {
431
+ suggestion: 'The cause is unknown. Give the task ID to EvoLink support; do not generate again automatically.',
432
+ retryable: false,
433
+ },
434
+ };
435
+ export function getTaskErrorInfo(code) {
436
+ const info = TASK_ERROR_MAP[code] ?? TASK_ERROR_MAP.unknown_error;
437
+ // The top-up link is tagged for the caller when the hint is shown, not when the table is built.
438
+ return info.suggestion.includes(TOP_UP_URL)
439
+ ? { ...info, suggestion: info.suggestion.replace(TOP_UP_URL, trackedLink(TOP_UP_URL, 'top_up')) }
440
+ : info;
441
+ }
442
+ export function publicTaskError(error = {}) {
443
+ const code = Object.prototype.hasOwnProperty.call(TASK_ERROR_MAP, error.code ?? '')
444
+ ? error.code : 'unknown_error';
445
+ const info = getTaskErrorInfo(code);
446
+ return { code, message: code === 'unknown_error' ? 'Generation failed; the cause is unknown.'
447
+ : `Generation did not complete (${code}).`, ...info };
448
+ }
449
+ export function formatTaskError(error) {
450
+ const info = publicTaskError(error);
451
+ return `Error code: ${info.code}\nMessage: ${info.message}\nSuggestion: ${info.suggestion}`;
452
+ }
@@ -0,0 +1,165 @@
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 { createReadStream } from 'node:fs';
5
+ import { Readable } from 'node:stream';
6
+ import { currentRequestCredentials } from '../request-context.js';
7
+ import { getApiKey } from '../config.js';
8
+ import { ApiHttpError } from './api-client.js';
9
+ import { classifyGatewayError, formatGatewayError } from './error-handler.js';
10
+ import { DEFAULT_WRITE_TIMEOUT_MS, evoHeaders, fetchWithTimeout, newRunId, parseRetryAfter, readJsonBody, responseRequestId, timeoutFromEnv, } from './http-policy.js';
11
+ const DEFAULT_FILES_API_BASE_URL = 'https://files-api.evolink.ai';
12
+ /**
13
+ * EVOLINK_FILES_BASE_URL points uploads at a staging files-api. HTTPS is
14
+ * required except for loopback development hosts.
15
+ */
16
+ export function filesApiBaseUrl() {
17
+ const override = (currentRequestCredentials()?.http?.filesBaseUrl ?? process.env.EVOLINK_FILES_BASE_URL ?? '').trim().replace(/\/+$/, '');
18
+ if (!override)
19
+ return DEFAULT_FILES_API_BASE_URL;
20
+ let parsed;
21
+ try {
22
+ parsed = new URL(override);
23
+ }
24
+ catch {
25
+ throw new Error(`EVOLINK_FILES_BASE_URL is not a valid URL: ${override}`);
26
+ }
27
+ const loopback = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';
28
+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && loopback)) {
29
+ throw new Error('EVOLINK_FILES_BASE_URL must use HTTPS (or HTTP on localhost).');
30
+ }
31
+ return override;
32
+ }
33
+ function requestHeaders(tool, auth) {
34
+ const runId = newRunId();
35
+ return {
36
+ 'Authorization': `Bearer ${auth?.bearer ?? getApiKey()}`,
37
+ ...evoHeaders(tool),
38
+ 'Idempotency-Key': runId,
39
+ 'X-Evo-Run-Id': runId,
40
+ };
41
+ }
42
+ function apiError(status, data, headers) {
43
+ const retryAfterMs = parseRetryAfter(headers.get('retry-after'));
44
+ const info = classifyGatewayError(status, data, retryAfterMs, responseRequestId(headers));
45
+ return new ApiHttpError(status, formatGatewayError(info), retryAfterMs, info.request_id, info);
46
+ }
47
+ async function parseResponse(response) {
48
+ const data = await readJsonBody(response);
49
+ if (!response.ok)
50
+ throw apiError(response.status, data, response.headers);
51
+ const body = data;
52
+ if (body.success === false) {
53
+ const status = typeof body.code === 'number' && body.code >= 400 && body.code < 600 ? body.code : 400;
54
+ throw apiError(status, data, response.headers);
55
+ }
56
+ const requestId = responseRequestId(response.headers);
57
+ if (!body.request_id && requestId)
58
+ body.request_id = requestId;
59
+ return body;
60
+ }
61
+ async function jsonUpload(path, body, auth) {
62
+ const response = await fetchWithTimeout(`${filesApiBaseUrl()}${path}`, {
63
+ method: 'POST',
64
+ headers: { ...requestHeaders('upload_file', auth), 'Content-Type': 'application/json' },
65
+ body: JSON.stringify(body),
66
+ }, timeoutFromEnv('EVOLINK_MCP_WRITE_TIMEOUT_MS', DEFAULT_WRITE_TIMEOUT_MS));
67
+ return parseResponse(response);
68
+ }
69
+ export async function fileBase64Upload(base64Data, uploadPath, fileName, auth) {
70
+ const body = { base64_data: base64Data };
71
+ if (uploadPath)
72
+ body.upload_path = uploadPath;
73
+ if (fileName)
74
+ body.file_name = fileName;
75
+ return jsonUpload('/api/v1/files/upload/base64', body, auth);
76
+ }
77
+ function multipartField(name, value) {
78
+ return Buffer.from(`Content-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`);
79
+ }
80
+ function safeDispositionValue(value) {
81
+ return value.replaceAll(/["\r\n]/g, '_');
82
+ }
83
+ /**
84
+ * Streams a file to files-api as multipart/form-data without holding it in
85
+ * memory. With a known size the request carries Content-Length; otherwise it
86
+ * is sent chunked.
87
+ */
88
+ export async function fileStreamUploadFrom(source, size, mime, originalName, options = {}) {
89
+ const boundary = `----evolink-${randomUUID()}`;
90
+ const prefix = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${safeDispositionValue(originalName)}"\r\nContent-Type: ${mime}\r\n\r\n`);
91
+ const fields = [];
92
+ if (options.uploadPath)
93
+ fields.push(multipartField('uploadPath', options.uploadPath));
94
+ if (options.fileName)
95
+ fields.push(multipartField('fileName', options.fileName));
96
+ const tailParts = [Buffer.from('\r\n')];
97
+ for (const field of fields) {
98
+ tailParts.push(Buffer.from(`--${boundary}\r\n`), field);
99
+ }
100
+ tailParts.push(Buffer.from(`--${boundary}--\r\n`));
101
+ const suffix = Buffer.concat(tailParts);
102
+ async function* multipartBody() {
103
+ yield prefix;
104
+ for await (const chunk of source) {
105
+ yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
106
+ }
107
+ yield suffix;
108
+ }
109
+ const headers = requestHeaders(options.tool ?? 'upload_file', options.auth);
110
+ if (options.uploadId) {
111
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/.test(options.uploadId))
112
+ throw new Error('Invalid upload request ID');
113
+ headers['X-Evo-Upload-Id'] = options.uploadId;
114
+ }
115
+ headers['Content-Type'] = `multipart/form-data; boundary=${boundary}`;
116
+ if (size !== undefined)
117
+ headers['Content-Length'] = String(prefix.length + size + suffix.length);
118
+ const init = {
119
+ method: 'POST',
120
+ headers,
121
+ body: Readable.from(multipartBody()),
122
+ duplex: 'half',
123
+ signal: options.signal,
124
+ };
125
+ const response = await fetchWithTimeout(`${filesApiBaseUrl()}/api/v1/files/upload/stream`, init, options.timeoutMs ?? timeoutFromEnv('EVOLINK_MCP_WRITE_TIMEOUT_MS', DEFAULT_WRITE_TIMEOUT_MS));
126
+ return parseResponse(response);
127
+ }
128
+ /** A read-only owner-scoped lookup. Older file services return no receipt. */
129
+ export async function fileUploadReceipt(id, auth) {
130
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/.test(id))
131
+ throw new Error('Invalid upload request ID');
132
+ const response = await fetchWithTimeout(`${filesApiBaseUrl()}/api/v1/files/upload-receipts/${id}`, {
133
+ method: 'GET', headers: { Authorization: `Bearer ${auth.bearer}`, ...evoHeaders('get_upload') },
134
+ }, 30_000);
135
+ if (response.status === 404 || response.status === 405) {
136
+ await response.body?.cancel();
137
+ return undefined;
138
+ }
139
+ const result = (await parseResponse(response)).data;
140
+ if (!result || result.upload_id !== id || !['done', 'outcome_unknown'].includes(result.state))
141
+ throw new Error('Invalid upload receipt');
142
+ if (result.state === 'done') {
143
+ const file = result.file;
144
+ if (result.result_verified !== true || !file || typeof file.file_id !== 'string' || !file.file_id || typeof file.file_url !== 'string'
145
+ || !Number.isSafeInteger(file.file_size) || file.file_size <= 0)
146
+ throw new Error('Invalid completed upload receipt');
147
+ const url = new URL(file.file_url);
148
+ const base = new URL(filesApiBaseUrl());
149
+ const local = base.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(base.hostname);
150
+ if (url.username || url.password || url.hash || !(url.protocol === 'https:' || local && url.origin === base.origin))
151
+ throw new Error('Invalid upload receipt URL');
152
+ }
153
+ return result;
154
+ }
155
+ export async function fileStreamUpload(filePath, fileSize, mime, originalName, uploadPath, fileName, auth) {
156
+ return fileStreamUploadFrom(createReadStream(filePath), fileSize, mime, originalName, { uploadPath, fileName, auth });
157
+ }
158
+ export async function fileUrlUpload(fileUrl, uploadPath, fileName, auth) {
159
+ const body = { file_url: fileUrl };
160
+ if (uploadPath)
161
+ body.upload_path = uploadPath;
162
+ if (fileName)
163
+ body.file_name = fileName;
164
+ return jsonUpload('/api/v1/files/upload/url', body, auth);
165
+ }