@evolinkai/cli 0.8.0 → 0.9.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 (33) hide show
  1. package/README.md +57 -5
  2. package/package.json +1 -1
  3. package/skills/evolink-cli/SKILL.md +15 -3
  4. package/skills/evolink-cli/references/usage-and-budget.md +11 -1
  5. package/src/api.mjs +19 -2
  6. package/src/cli.mjs +32 -6
  7. package/src/errors.mjs +21 -13
  8. package/src/files.mjs +14 -2
  9. package/src/help.mjs +8 -2
  10. package/src/media.mjs +54 -15
  11. package/src/oauth.mjs +11 -3
  12. package/src/platform/core/src/config.js +7 -4
  13. package/src/platform/core/src/platform-client.js +9 -3
  14. package/src/platform/core/src/platform-operations.js +2 -0
  15. package/src/platform/core/src/services/api-client.js +61 -29
  16. package/src/platform/core/src/services/error-handler.js +89 -34
  17. package/src/platform/core/src/services/file-client.js +32 -0
  18. package/src/platform/core/src/services/http-policy.js +62 -12
  19. package/src/platform/core/src/services/model-catalog.js +13 -7
  20. package/src/platform/core/src/services/pricing-quote-client.js +239 -0
  21. package/src/platform/core/src/services/pricing-rules-client.js +222 -0
  22. package/src/platform/core/src/services/pricing-rules-estimate.js +231 -0
  23. package/src/platform/core/src/services/public-error.js +63 -0
  24. package/src/platform/core/src/tool-guidance.js +2 -0
  25. package/src/platform/core/src/tools/estimate-cost.js +36 -11
  26. package/src/platform/core/src/tools/generate.js +31 -7
  27. package/src/platform/core/src/tools/get-model.js +3 -1
  28. package/src/platform/core/src/tools/get-pricing-rules.js +54 -0
  29. package/src/platform/core/src/tools/shared.js +39 -19
  30. package/src/platform/core/src/tools/task-billing.js +31 -0
  31. package/src/platform/core/src/tools/task-format.js +31 -12
  32. package/src/platform/core/src/version.js +1 -1
  33. package/src/platform/source.json +47 -35
@@ -5,6 +5,9 @@ import { currentRequestCredentials, processCredentialsAllowed } from './request-
5
5
  import { API_KEYS_URL } from './services/http-policy.js';
6
6
  import { trackedLink } from './services/utm.js';
7
7
  import { MCP_VERSION } from './version.js';
8
+ export class CredentialError extends Error {
9
+ constructor(message) { super(message); this.name = 'CredentialError'; }
10
+ }
8
11
  const BASE_URLS = {
9
12
  official: 'https://api.evolink.ai',
10
13
  beta: 'https://beta-api.evolink.ai',
@@ -62,17 +65,17 @@ export function getApiKey() {
62
65
  if (scoped) {
63
66
  if (scoped.apiKey)
64
67
  return scoped.apiKey;
65
- throw new Error(scoped.unavailableReason ?? 'No EvoLink credential is available for this request.');
68
+ throw new CredentialError(scoped.unavailableReason ?? 'No EvoLink credential is available for this request.');
66
69
  }
67
70
  if (!processCredentialsAllowed()) {
68
- throw new Error('No EvoLink credential is available for this request.');
71
+ throw new CredentialError('No EvoLink credential is available for this request.');
69
72
  }
70
73
  const configured = process.env.EVOLINK_API_KEY?.trim();
71
74
  if (configured)
72
75
  return configured;
73
76
  const helper = process.env.EVOLINK_CREDENTIAL_HELPER?.trim() || 'evolink';
74
77
  if (helper.includes('\0'))
75
- throw new Error('EVOLINK_CREDENTIAL_HELPER is invalid');
78
+ throw new CredentialError('EVOLINK_CREDENTIAL_HELPER is invalid');
76
79
  try {
77
80
  const key = execFileSync(helper, ['credential', 'get'], {
78
81
  encoding: 'utf8',
@@ -86,7 +89,7 @@ export function getApiKey() {
86
89
  catch {
87
90
  // Return one stable recovery message without echoing helper stderr or key material.
88
91
  }
89
- throw new Error(`No EvoLink API key is available. Set EVOLINK_API_KEY to a key from ${trackedLink(API_KEYS_URL, 'api_keys')}, ` +
92
+ throw new CredentialError(`No EvoLink API key is available. Set EVOLINK_API_KEY to a key from ${trackedLink(API_KEYS_URL, 'api_keys')}, ` +
90
93
  'or set EVOLINK_CREDENTIAL_HELPER to an API-key helper that implements `credential get`. ' +
91
94
  'The browser-login @evolinkai/cli does not export API keys; use its own `evolink auth login` workflow or hosted MCP for OAuth.');
92
95
  }
@@ -4,7 +4,7 @@ import { z } from 'zod';
4
4
  import { registerPlatformOperations } from './platform-operations.js';
5
5
  import { runWithRequestCredentials } from './request-context.js';
6
6
  import { requestUploadToken } from './services/api-client.js';
7
- import { fileStreamUploadFrom } from './services/file-client.js';
7
+ import { fileStreamUploadFrom, fileUploadReceipt } from './services/file-client.js';
8
8
  import { errorResult, failure } from './tools/shared.js';
9
9
  /** Local execution of the shared operations. Network traffic is REST only. */
10
10
  export class PlatformClient {
@@ -40,11 +40,17 @@ export class PlatformClient {
40
40
  }
41
41
  });
42
42
  }
43
- async upload(source, size, mime, name, credentials, uploadPath) {
43
+ async upload(source, size, mime, name, credentials, uploadPath, uploadId) {
44
44
  return runWithRequestCredentials(credentials, async () => {
45
45
  const token = await requestUploadToken(this.config, 'upload_file');
46
- return fileStreamUploadFrom(source, size, mime, name, { uploadPath, auth: { bearer: token.token },
46
+ return fileStreamUploadFrom(source, size, mime, name, { uploadPath, uploadId, auth: { bearer: token.token },
47
47
  signal: credentials.http?.signal, timeoutMs: 900_000 });
48
48
  });
49
49
  }
50
+ async uploadReceipt(id, credentials) {
51
+ return runWithRequestCredentials(credentials, async () => {
52
+ const token = await requestUploadToken(this.config, 'get_upload');
53
+ return fileUploadReceipt(id, { bearer: token.token });
54
+ });
55
+ }
50
56
  }
@@ -6,6 +6,7 @@ import { registerCheckBalance } from './tools/check-balance.js';
6
6
  import { registerEstimateCost } from './tools/estimate-cost.js';
7
7
  import { registerGenerateTools } from './tools/generate.js';
8
8
  import { registerGetModel } from './tools/get-model.js';
9
+ import { registerPricingRules } from './tools/get-pricing-rules.js';
9
10
  import { registerGetTask } from './tools/get-task.js';
10
11
  import { registerListTasks } from './tools/list-tasks.js';
11
12
  import { registerSearchModels } from './tools/search-models.js';
@@ -13,6 +14,7 @@ export function registerPlatformOperations(registry, config) {
13
14
  registerSearchModels(registry, config);
14
15
  registerDiscovery(registry, config);
15
16
  registerGetModel(registry, config);
17
+ registerPricingRules(registry);
16
18
  registerEstimateCost(registry, config);
17
19
  registerGenerateTools(registry, config);
18
20
  registerGetTask(registry, config);
@@ -3,19 +3,21 @@
3
3
  import { gatewayAuthHeaders } from '../config.js';
4
4
  import { currentRequestCredentials } from '../request-context.js';
5
5
  import { classifyGatewayError, formatGatewayError } from './error-handler.js';
6
- import { DEFAULT_READ_TIMEOUT_MS, DEFAULT_SUBMIT_TIMEOUT_MS, MAX_RETRY_DELAY_MS, PaidRequestOutcomeUnknownError, RequestTimeoutError, evoHeaders, fetchWithTimeout, newRunId, parseRetryAfter, readJsonBody, responseRequestId, timeoutFromEnv, } from './http-policy.js';
6
+ import { DEFAULT_READ_TIMEOUT_MS, DEFAULT_SUBMIT_TIMEOUT_MS, MAX_RETRY_DELAY_MS, PaidRequestOutcomeUnknownError, RequestTimeoutError, SubmissionNotStartedError, evoHeaders, fetchWithTimeout, newRunId, parseRetryAfter, readJsonBody, responseRequestId, timeoutFromEnv, } from './http-policy.js';
7
7
  // --- Error class for HTTP-level failures ---
8
8
  export class ApiHttpError extends Error {
9
9
  status;
10
10
  retryAfterMs;
11
11
  requestId;
12
12
  info;
13
- constructor(status, message, retryAfterMs, requestId, info) {
13
+ submissionState;
14
+ constructor(status, message, retryAfterMs, requestId, info, submissionState) {
14
15
  super(message);
15
16
  this.status = status;
16
17
  this.retryAfterMs = retryAfterMs;
17
18
  this.requestId = requestId;
18
19
  this.info = info;
20
+ this.submissionState = submissionState;
19
21
  this.name = 'ApiHttpError';
20
22
  }
21
23
  }
@@ -63,40 +65,65 @@ export async function withRetry(fn, retries, baseDelayMs) {
63
65
  }
64
66
  // --- Core request (no retry) ---
65
67
  async function rawRequest(config, options) {
66
- const url = `${config.baseUrl}${options.path}`;
67
- const headers = {
68
- ...gatewayAuthHeaders(),
69
- 'Accept': 'application/json',
70
- ...evoHeaders(options.tool ?? 'unknown'),
71
- };
72
- if (options.body)
73
- headers['Content-Type'] = 'application/json';
74
- if (options.idempotencyKey) {
75
- headers['Idempotency-Key'] = options.idempotencyKey;
76
- headers['X-Evo-Run-Id'] = options.idempotencyKey;
68
+ const isPaid = options.method === 'POST' && !!options.idempotencyKey;
69
+ let headers;
70
+ let body;
71
+ let timeout;
72
+ try {
73
+ headers = { ...gatewayAuthHeaders(), Accept: 'application/json', ...evoHeaders(options.tool ?? 'unknown') };
74
+ if (options.body)
75
+ headers['Content-Type'] = 'application/json';
76
+ if (options.idempotencyKey) {
77
+ headers['Idempotency-Key'] = options.idempotencyKey;
78
+ headers['X-Evo-Run-Id'] = options.idempotencyKey;
79
+ }
80
+ body = options.body ? JSON.stringify(options.body) : undefined;
81
+ timeout = options.timeoutMs ?? timeoutFromEnv(isPaid ? 'EVOLINK_MCP_WRITE_TIMEOUT_MS' : 'EVOLINK_MCP_READ_TIMEOUT_MS', isPaid ? DEFAULT_SUBMIT_TIMEOUT_MS : DEFAULT_READ_TIMEOUT_MS);
82
+ }
83
+ catch (error) {
84
+ if (isPaid)
85
+ throw new SubmissionNotStartedError(error);
86
+ throw error;
77
87
  }
78
- const isRead = options.method === 'GET' || !options.idempotencyKey;
79
- let response;
88
+ // Reading and verifying the body belong to the submission boundary too.
80
89
  try {
81
- response = await fetchWithTimeout(url, {
82
- method: options.method,
83
- headers,
84
- body: options.body ? JSON.stringify(options.body) : undefined,
85
- }, options.timeoutMs ?? timeoutFromEnv(isRead ? 'EVOLINK_MCP_READ_TIMEOUT_MS' : 'EVOLINK_MCP_WRITE_TIMEOUT_MS', isRead ? DEFAULT_READ_TIMEOUT_MS : DEFAULT_SUBMIT_TIMEOUT_MS));
90
+ const started = Date.now();
91
+ const response = await fetchWithTimeout(`${config.baseUrl}${options.path}`, {
92
+ method: options.method, headers, body,
93
+ }, timeout);
94
+ const data = await readJsonBody(response, Math.max(1, timeout - (Date.now() - started)));
95
+ const requestId = responseRequestId(response.headers);
96
+ if (!response.ok) {
97
+ const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'));
98
+ const info = classifyGatewayError(response.status, data, retryAfterMs, requestId);
99
+ throw new ApiHttpError(response.status, formatGatewayError(info), retryAfterMs, info.request_id, info, isPaid ? (verifiedPrechargeRejection(response.status, info.code) ? 'rejected' : 'outcome_unknown') : undefined);
100
+ }
101
+ if (isPaid && (!data || typeof data !== 'object' || Array.isArray(data)
102
+ || typeof data.id !== 'string'
103
+ || !/^[A-Za-z0-9._:-]{1,128}$/.test(data.id))) {
104
+ throw new PaidRequestOutcomeUnknownError(new Error('Unverified submission response'), options.idempotencyKey);
105
+ }
106
+ return { data: data, requestId, headers: response.headers };
86
107
  }
87
108
  catch (error) {
88
- if (!isRead)
109
+ if (isPaid && !(error instanceof ApiHttpError) && !(error instanceof PaidRequestOutcomeUnknownError)) {
89
110
  throw new PaidRequestOutcomeUnknownError(error, options.idempotencyKey);
111
+ }
90
112
  throw error;
91
113
  }
92
- const data = await readJsonBody(response);
93
- const requestId = responseRequestId(response.headers);
94
- if (!response.ok) {
95
- const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'));
96
- const info = classifyGatewayError(response.status, data, retryAfterMs, requestId);
97
- throw new ApiHttpError(response.status, formatGatewayError(info), retryAfterMs, info.request_id, info);
98
- }
99
- return { data: data, requestId, headers: response.headers };
114
+ }
115
+ /** These codes are emitted by gateway admission checks before dispatch, not inferred from an HTTP status. */
116
+ function verifiedPrechargeRejection(status, code) {
117
+ if (status < 400 || !code)
118
+ return false;
119
+ return new Set([
120
+ 'insufficient_quota', 'insufficient_user_quota', 'quota_not_enough', 'account_balance_insufficient',
121
+ 'insufficient_token_quota', 'key_quota_exhausted', 'token_daily_quota_exceeded', 'key_daily_quota_exhausted',
122
+ 'key_disabled', 'key_expired', 'key_model_not_allowed', 'mcp_paused', 'mcp_key_expired',
123
+ 'connection_not_found', 'connection_revoked', 'session_inactive', 'session_expired', 'mcp_scope_missing',
124
+ 'mcp_service_unauthorized', 'mcp_connection_required', 'mcp_route_not_allowed', 'mcp_token_invalid', 'user_disabled',
125
+ 'agent_session_unavailable', 'mcp_connection_create_failed', 'mcp_channel_disabled',
126
+ ]).has(code.toLowerCase());
100
127
  }
101
128
  /**
102
129
  * Submit one paid intent. At most one transport retry, always with the same
@@ -128,6 +155,11 @@ export async function getAvailableModelIds(config) {
128
155
  }
129
156
  return data.data.map(model => model.id);
130
157
  }
158
+ /** Read-only account Quote. It reuses the caller's API key or MCP OAuth token. */
159
+ export async function requestAccountQuote(config, body) {
160
+ const result = await rawRequest(config, { method: 'POST', path: '/v1/agent-estimates', body, tool: 'estimate_cost' });
161
+ return result.data;
162
+ }
131
163
  /** @deprecated kept for callers outside the tools; use submitTask. */
132
164
  export async function apiRequest(config, options) {
133
165
  if (options.method !== 'POST' || !options.body) {
@@ -1,5 +1,6 @@
1
1
  // Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
2
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';
3
4
  import { currentCredentialMode } from '../request-context.js';
4
5
  import { API_KEYS_URL, MCP_CONSOLE_URL, MCP_KEY_NAME, TOP_UP_URL, siteUrl } from './http-policy.js';
5
6
  import { trackedLink } from './utm.js';
@@ -9,7 +10,7 @@ const ACCOUNT_CODES = new Set(['insufficient_quota', 'insufficient_user_quota',
9
10
  const KEY_QUOTA_CODES = new Set(['insufficient_token_quota', 'key_quota_exhausted']);
10
11
  const KEY_DAILY_CODES = new Set(['token_daily_quota_exceeded', 'key_daily_quota_exhausted']);
11
12
  const CONTENT_CODES = new Set(['content_policy_violation', 'content_filter', 'sensitive_content', 'moderation_blocked', 'input_moderation_failed']);
12
- const UNAVAILABLE_CODES = new Set(['no_available_channel', 'model_unavailable', 'channel_selection_failed', 'service_unavailable']);
13
+ const UNAVAILABLE_CODES = new Set(['no_available_channel', 'model_unavailable', 'channel_selection_failed']);
13
14
  /** Hosted service channel (key custody A): the connection itself is gone and needs a new sign-in. */
14
15
  const CONNECTION_ENDED_CODES = new Set(['connection_not_found', 'connection_revoked', 'session_inactive', 'session_expired', 'mcp_scope_missing']);
15
16
  /** The hosted service, not the user's connection, was refused or sent a request the channel does not serve. */
@@ -79,7 +80,9 @@ function categorize(status, code, mode, mcpLimits) {
79
80
  return 'outcome_unknown';
80
81
  if (CONTENT_CODES.has(lower))
81
82
  return 'content_policy';
82
- if (UNAVAILABLE_CODES.has(lower) || lower.startsWith('channel:'))
83
+ if (lower === 'service_unavailable')
84
+ return 'service_unavailable';
85
+ if (UNAVAILABLE_CODES.has(lower))
83
86
  return 'model_unavailable';
84
87
  if (CONNECTION_ENDED_CODES.has(lower))
85
88
  return 'connection_ended';
@@ -106,7 +109,7 @@ function categorize(status, code, mode, mcpLimits) {
106
109
  case 404: return 'not_found';
107
110
  case 413: return 'request_too_large';
108
111
  case 429: return 'rate_limited';
109
- case 503: return 'model_unavailable';
112
+ case 503: return 'service_unavailable';
110
113
  }
111
114
  if (status >= 500)
112
115
  return 'server_error';
@@ -117,6 +120,7 @@ const RETRYABLE = new Set([
117
120
  'mcp_daily_limit_reached',
118
121
  'rate_limited',
119
122
  'model_unavailable',
123
+ 'service_unavailable',
120
124
  'outcome_unknown',
121
125
  'server_error',
122
126
  'session_check_unavailable',
@@ -241,15 +245,17 @@ function nextStep(category, info, mode) {
241
245
  case 'rate_limited':
242
246
  return `Too many requests. Wait ${info.retry_after_seconds ?? 30} seconds before retrying; do not loop paid submissions.`;
243
247
  case 'invalid_request':
244
- return 'Fix the parameter named in the message and retry. get_model lists every parameter with its allowed values.';
248
+ return 'Check the supplied parameters before retrying. get_model lists every parameter with its allowed values.';
245
249
  case 'not_found':
246
250
  return 'Nothing matches this ID. Check it, or use list_tasks to find recent tasks.';
247
251
  case 'content_policy':
248
- return 'The prompt or input was blocked by content review. Rephrase it (no real people, brands, explicit or violent content) and retry.';
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.';
249
255
  case 'model_unavailable':
250
256
  return 'The model is temporarily unavailable. Retry in a minute, or pick another model with search_models.';
251
257
  case 'idempotency_conflict':
252
- return 'This client_request_id was already used for a different request. Use a new client_request_id for a new generation.';
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.';
253
259
  case 'outcome_unknown':
254
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.';
255
261
  case 'request_too_large':
@@ -275,17 +281,65 @@ function nextStep(category, info, mode) {
275
281
  /** Classifies one non-2xx gateway or files-api response. */
276
282
  export function classifyGatewayError(status, body, retryAfterMs, headerRequestId) {
277
283
  const error = envelope(body);
278
- const code = text(error.code);
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', 'unsupported_parameters', 'estimate_unsupported', 'pricing_policy_not_found', 'pricing_unavailable', 'model_access_denied', 'ip_restricted']);
287
+ const code = rawCode && knownCodes.has(rawCode) ? rawCode : undefined;
279
288
  const mode = currentCredentialMode();
280
289
  const mcpScope = text(error.limit_scope)?.toLowerCase() === 'mcp';
281
290
  const category = categorize(status, code ?? '', mode, mcpScope || mode === 'signed_in');
282
- const requestId = text(error.request_id) ?? headerRequestId;
283
- const rawMessage = text(error.message) ?? `HTTP ${status}`;
284
- const message = rawMessage.replace(/\s*\(request id: [^)]*\)\s*$/i, '').slice(0, 600);
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 (code === 'unsupported_parameters' || code === 'estimate_unsupported') {
307
+ message = 'Account media quotes are not enabled at this gateway. Preserve the generation input and budget; retry when backend quoting is available.';
308
+ }
309
+ if (code === 'pricing_policy_not_found')
310
+ message = 'This model has no published policy available for an account quote.';
311
+ if (code === 'pricing_unavailable')
312
+ message = 'The account quote is temporarily unavailable. Preserve the input and budget and retry later.';
313
+ if (status === 415 && category === 'invalid_request')
314
+ message = 'The request uses an unsupported file type or media format.';
285
315
  const details = {};
286
316
  for (const field of DETAIL_FIELDS) {
287
- if (error[field] !== undefined && error[field] !== null && error[field] !== '')
288
- details[field] = error[field];
317
+ const value = error[field];
318
+ if (field.endsWith('_credits') || field === 'expired_at') {
319
+ const n = publicNumber(value);
320
+ if (n !== undefined && (field !== 'expired_at' || n <= 253402300799))
321
+ details[field] = n;
322
+ }
323
+ else if (field === 'allowed_models' && Array.isArray(value)) {
324
+ details[field] = value.slice(0, 20).map(publicIdentifier).filter(Boolean);
325
+ }
326
+ else {
327
+ const label = publicLabel(value);
328
+ if (label)
329
+ details[field] = label;
330
+ }
331
+ }
332
+ const param = typeof error.param === 'string' && /^[A-Za-z_][A-Za-z0-9_.\[\]]{0,100}$/.test(error.param) ? error.param : undefined;
333
+ if (category === 'invalid_request' && param) {
334
+ message += ` Parameter: ${param}.`;
335
+ for (const field of ['min', 'max']) {
336
+ const n = publicNumber(error[field]);
337
+ if (n !== undefined)
338
+ details[field] = n;
339
+ }
340
+ if (Array.isArray(error.allowed_values))
341
+ details.allowed_values = error.allowed_values.slice(0, 30)
342
+ .filter(value => publicNumber(value) !== undefined || publicLabel(value) !== undefined);
289
343
  }
290
344
  let actionUrl;
291
345
  if (category === 'account_balance_insufficient') {
@@ -303,6 +357,7 @@ export function classifyGatewayError(status, body, retryAfterMs, headerRequestId
303
357
  category,
304
358
  ...(headline ? { headline } : {}),
305
359
  code,
360
+ ...(param ? { param } : {}),
306
361
  message,
307
362
  next_step: '',
308
363
  retryable: RETRYABLE.has(category),
@@ -332,7 +387,7 @@ export function formatApiError(status, body) {
332
387
  }
333
388
  const TASK_ERROR_MAP = {
334
389
  content_policy_violation: {
335
- suggestion: 'Revise the prompt: avoid real person photos, celebrity names, copyrighted content, NSFW or violence. An illustration style often passes.',
390
+ suggestion: 'Review the applicable content policy and revise the input. Do not bypass content review.',
336
391
  retryable: false,
337
392
  },
338
393
  invalid_parameters: {
@@ -340,15 +395,15 @@ const TASK_ERROR_MAP = {
340
395
  retryable: false,
341
396
  },
342
397
  image_dimension_mismatch: {
343
- suggestion: 'The input image does not match the requested aspect ratio. Resize it (for example 1280x720 for 16:9) or change the ratio.',
398
+ suggestion: 'Check the input dimensions and aspect ratio against this model’s get_model rules.',
344
399
  retryable: false,
345
400
  },
346
401
  image_processing_error: {
347
- suggestion: 'The input image could not be processed. Use JPG, PNG or WebP under 10 MB at a publicly reachable URL (upload_file gives one).',
402
+ suggestion: 'The input image could not be processed. Check accessibility, format and size against this model’s get_model rules.',
348
403
  retryable: false,
349
404
  },
350
405
  request_cancelled: {
351
- suggestion: 'The task was cancelled. Submit a new request if it was not intended.',
406
+ suggestion: 'The task was cancelled. Check this task’s billing state before deciding whether to request another generation.',
352
407
  retryable: false,
353
408
  },
354
409
  resource_not_found: {
@@ -356,32 +411,32 @@ const TASK_ERROR_MAP = {
356
411
  retryable: false,
357
412
  },
358
413
  generation_timeout: {
359
- suggestion: 'Generation timed out, probably under high load. Retry, or simplify the prompt or lower the resolution.',
414
+ suggestion: 'The generation timed out. Check the original task and its billing state before considering another generation.',
360
415
  retryable: true,
361
416
  },
362
417
  quota_exceeded: {
363
- suggestion: `The account was over quota or rate limited when the task ran. Wait, then retry; top up at ${TOP_UP_URL} if the balance is low.`,
418
+ 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.`,
364
419
  retryable: true,
365
420
  },
366
421
  resource_exhausted: {
367
- suggestion: 'Provider capacity was temporarily exhausted. Wait 30–60 seconds and retry.',
422
+ suggestion: 'Generation capacity was temporarily exhausted. Wait before considering another generation.',
368
423
  retryable: true,
369
424
  },
370
425
  generation_failed_no_content: {
371
- suggestion: 'The model produced no output, often because of protected content or watermark removal requests. Change the prompt or input and retry.',
372
- retryable: true,
426
+ suggestion: 'The model returned no output. The cause is not established; retain the task ID and contact EvoLink support if needed.',
427
+ retryable: false,
373
428
  },
374
429
  service_error: {
375
- suggestion: 'Temporary service error. Retry after a minute.',
430
+ suggestion: 'The generation service reported an error. Retain the task ID and check its billing state.',
376
431
  retryable: true,
377
432
  },
378
433
  service_unavailable: {
379
- suggestion: 'The service was temporarily unavailable. Retry after 1–2 minutes.',
434
+ suggestion: 'The generation service was temporarily unavailable. Retain the task ID and check its billing state.',
380
435
  retryable: true,
381
436
  },
382
437
  unknown_error: {
383
- suggestion: 'Unknown error. Retry after a minute; if it keeps failing, give the task ID to EvoLink support.',
384
- retryable: true,
438
+ suggestion: 'The cause is unknown. Give the task ID to EvoLink support; do not generate again automatically.',
439
+ retryable: false,
385
440
  },
386
441
  };
387
442
  export function getTaskErrorInfo(code) {
@@ -391,14 +446,14 @@ export function getTaskErrorInfo(code) {
391
446
  ? { ...info, suggestion: info.suggestion.replace(TOP_UP_URL, trackedLink(TOP_UP_URL, 'top_up')) }
392
447
  : info;
393
448
  }
394
- export function formatTaskError(error) {
395
- const code = error.code ?? 'unknown_error';
449
+ export function publicTaskError(error = {}) {
450
+ const code = Object.prototype.hasOwnProperty.call(TASK_ERROR_MAP, error.code ?? '')
451
+ ? error.code : 'unknown_error';
396
452
  const info = getTaskErrorInfo(code);
397
- const lines = [
398
- `Error code: ${code}`,
399
- `Message: ${error.message ?? 'No details provided'}`,
400
- `Retryable: ${info.retryable ? 'Yes — you can retry this request' : 'No — modify your input before retrying'}`,
401
- `Suggestion: ${info.suggestion}`,
402
- ];
403
- return lines.join('\n');
453
+ return { code, message: code === 'unknown_error' ? 'Generation failed; the cause is unknown.'
454
+ : `Generation did not complete (${code}).`, ...info };
455
+ }
456
+ export function formatTaskError(error) {
457
+ const info = publicTaskError(error);
458
+ return `Error code: ${info.code}\nMessage: ${info.message}\nSuggestion: ${info.suggestion}`;
404
459
  }
@@ -107,6 +107,11 @@ export async function fileStreamUploadFrom(source, size, mime, originalName, opt
107
107
  yield suffix;
108
108
  }
109
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
+ }
110
115
  headers['Content-Type'] = `multipart/form-data; boundary=${boundary}`;
111
116
  if (size !== undefined)
112
117
  headers['Content-Length'] = String(prefix.length + size + suffix.length);
@@ -120,6 +125,33 @@ export async function fileStreamUploadFrom(source, size, mime, originalName, opt
120
125
  const response = await fetchWithTimeout(`${filesApiBaseUrl()}/api/v1/files/upload/stream`, init, options.timeoutMs ?? timeoutFromEnv('EVOLINK_MCP_WRITE_TIMEOUT_MS', DEFAULT_WRITE_TIMEOUT_MS));
121
126
  return parseResponse(response);
122
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
+ }
123
155
  export async function fileStreamUpload(filePath, fileSize, mime, originalName, uploadPath, fileName, auth) {
124
156
  return fileStreamUploadFrom(createReadStream(filePath), fileSize, mime, originalName, { uploadPath, fileName, auth });
125
157
  }
@@ -31,6 +31,14 @@ export class RequestTimeoutError extends Error {
31
31
  this.name = 'RequestTimeoutError';
32
32
  }
33
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
+ }
34
42
  export class PaidRequestOutcomeUnknownError extends Error {
35
43
  cause;
36
44
  idempotencyKey;
@@ -59,11 +67,21 @@ export function evoHeaders(tool) {
59
67
  /** Turns a console path such as /dashboard/credits into a full link; full https links pass through. */
60
68
  export function siteUrl(pathOrUrl, fallback) {
61
69
  const value = (pathOrUrl ?? '').trim();
62
- if (value.startsWith('https://'))
63
- return value;
64
- if (value.startsWith('/') && !value.startsWith('//'))
65
- return `${EVOLINK_SITE}${value}`;
66
- return fallback;
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
+ }
67
85
  }
68
86
  export function timeoutFromEnv(name, fallback) {
69
87
  const raw = process.env[name];
@@ -123,14 +141,46 @@ export async function fetchWithTimeout(url, init, timeoutMs, fetchImpl) {
123
141
  signal.removeEventListener('abort', abort);
124
142
  }
125
143
  }
126
- export async function readJsonBody(response) {
127
- const text = await response.text();
128
- if (!text)
129
- return {};
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
+ };
130
162
  try {
131
- return JSON.parse(text);
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
+ }
132
179
  }
133
- catch {
134
- return { message: text.slice(0, 2_000) };
180
+ finally {
181
+ clearTimeout(timer);
182
+ if (abort)
183
+ signal?.removeEventListener('abort', abort);
184
+ reader?.releaseLock();
135
185
  }
136
186
  }
@@ -5,7 +5,7 @@ import { currentRequestCredentials } from '../request-context.js';
5
5
  import { getAvailableModelIds } from './api-client.js';
6
6
  import { currentModels } from './catalog-client.js';
7
7
  import { closestMatches } from './param-validator.js';
8
- import { getPricing } from './pricing-client.js';
8
+ import { getPricingRules } from './pricing-rules-client.js';
9
9
  function isMediaKind(value) {
10
10
  return value === 'image' || value === 'video' || value === 'audio';
11
11
  }
@@ -35,15 +35,21 @@ export async function loadCatalog(config, pricingOptions = {}) {
35
35
  entries.set(model.model_id, { id: model.model_id, kind, aliases: model.aliases, title: model.display_name,
36
36
  ...(spec ? { spec: { ...spec, model: model.model_id } } : {}) });
37
37
  }
38
+ if (pricingOptions.skipPricing)
39
+ return { entries: [...entries.values()] };
38
40
  let pricingWarning;
39
41
  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.';
42
+ const { body } = await getPricingRules({ view: 'full' }, { fresh: pricingOptions.fresh });
43
+ const rules = 'models' in body ? body.models : [body.model];
43
44
  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()] };
45
+ const rule = rules.find(model => model.model_id.toLowerCase() === entry.id.toLowerCase());
46
+ if (!rule)
47
+ continue;
48
+ entry.priced = { id: entry.id, kind: entry.kind, pricingIncomplete: rule.pricing_status !== 'available',
49
+ prices: rule.components.map(c => ({ sku_id: c.sku_id, name: c.id,
50
+ unit: c.unit.includes('token') ? c.unit : c.unit.includes('second') ? 'second' : c.unit.includes('image') ? 'image' : c.unit,
51
+ min_usd: Number(c.rate.usd), max_usd: Number(c.rate.usd), min_charge_usd: Number(c.minimum_charge.usd),
52
+ role: c.unit.includes('token') ? 'token' : c.role.includes('output') || c.role === 'request' || c.role === 'output' ? 'output' : 'add_on' })) };
47
53
  }
48
54
  }
49
55
  catch (error) {