@evolinkai/cli 0.8.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 +19 -0
- package/package.json +1 -1
- package/skills/evolink-cli/SKILL.md +1 -1
- package/src/api.mjs +6 -2
- package/src/errors.mjs +21 -13
- package/src/files.mjs +14 -2
- package/src/media.mjs +2 -2
- package/src/oauth.mjs +11 -3
- package/src/platform/core/src/config.js +7 -4
- package/src/platform/core/src/platform-client.js +9 -3
- package/src/platform/core/src/services/api-client.js +56 -29
- package/src/platform/core/src/services/error-handler.js +82 -34
- package/src/platform/core/src/services/file-client.js +32 -0
- package/src/platform/core/src/services/http-policy.js +62 -12
- package/src/platform/core/src/services/public-error.js +63 -0
- package/src/platform/core/src/tools/generate.js +4 -1
- package/src/platform/core/src/tools/shared.js +39 -19
- package/src/platform/core/src/tools/task-billing.js +31 -0
- package/src/platform/core/src/tools/task-format.js +31 -12
- package/src/platform/core/src/version.js +1 -1
- package/src/platform/source.json +28 -24
package/README.md
CHANGED
|
@@ -101,6 +101,20 @@ evolink uploads get UPLOAD_ID --json
|
|
|
101
101
|
evolink download TASK_ID --output /absolute/result.mp4 --index 1 --json
|
|
102
102
|
```
|
|
103
103
|
|
|
104
|
+
Uploads save a stable request ID before sending bytes. On connection loss, keep
|
|
105
|
+
that ID and run `evolink uploads get UPLOAD_ID --json`. With a compatible file
|
|
106
|
+
service this reads an account-owned receipt retained for up to 72 hours; it never
|
|
107
|
+
repeats the upload. Older services return an unknown outcome rather than a false
|
|
108
|
+
failure. Logout revokes future use of the scoped upload grant; an upload already
|
|
109
|
+
accepted before logout may still finish. Recovery retains the original login
|
|
110
|
+
binding and never copies OAuth credentials into MCP settings.
|
|
111
|
+
|
|
112
|
+
Passport can advertise `evolink_cli_mcp_supported: true`. New browser grants then
|
|
113
|
+
use the public official `evolink-cli` identity with PKCE, `mcp offline_access`, and
|
|
114
|
+
the configured MCP resource. Existing dynamic-client sessions refresh with their
|
|
115
|
+
original client ID. Earlier Passport deployments continue to use dynamic
|
|
116
|
+
registration. This does not change shared CLI/MCP account-Key limits or permissions.
|
|
117
|
+
|
|
104
118
|
Task-list filters are case-sensitive:
|
|
105
119
|
|
|
106
120
|
| Option | Allowed values | When omitted |
|
|
@@ -195,3 +209,8 @@ Run `gemini mcp list` from the intended project directory. If EvoLink is `Disabl
|
|
|
195
209
|
Headless mode exposes only tools permitted by its policy. In Gemini CLI 0.63.0, a scoped MCP rule uses `mcpName`, not `serverName`; allow only the tools needed for the chosen workflow. For example, a quote-only policy can allow `search_models`, `get_model`, `estimate_cost`, `check_balance` and `get_task` on `evolink`. Generation still requires the user's quote approval and the host's normal tool permission. Do not silently add a generation allow rule or treat a successful process exit without EvoLink tool calls as acceptance.
|
|
196
210
|
|
|
197
211
|
See [Gemini trusted folders](https://geminicli.com/docs/cli/trusted-folders/) and [Gemini MCP configuration and OAuth](https://geminicli.com/docs/tools/mcp-server/). A cloud terminal test does not prove desktop inline previews, browser handoff on another machine or permission defaults in every host.
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
Generation errors preserve the saved quote and request ID when acceptance or charging is uncertain. `charged: no` alone does not authorize a new request: `submission_state` must also establish `not_submitted` or `rejected`. Recover uncertain submissions with the original quote, and query a known task. A new generation needs a fresh estimate and user approval.
|
|
215
|
+
|
|
216
|
+
A failed/cancelled task does not establish a refund. `tasks get` can successfully return that task, while `tasks wait` exits nonzero with the same task and billing details. `billing.refund_status` reports account-balance evidence: `unknown`, `pending`, `failed`, `completed`, or `not_required`. A completed refund includes recorded credits and time; key-limit restoration remains unknown. Old gateways without billing fields retain unknown status, rather than claiming zero charge or a completed refund.
|
package/package.json
CHANGED
|
@@ -45,7 +45,7 @@ For image edits, reference-based video, speech or music, read [media workflows](
|
|
|
45
45
|
|
|
46
46
|
- Discover with `evolink models search --type image|video|audio --query "keywords" --json`; read supported parameters and prices with `models show MODEL --json`. Respect the user's chosen model and budget. Search order does not establish quality.
|
|
47
47
|
- When comparing reference support, retrieving schemas or searching model documentation, read [Discovery and delivery extensions](references/capabilities.md). Use `models recommend`, `models schema` and `docs search` only when the installed CLI supports them. Keep the user's chosen model; recommendations explain alternatives, not automatic approval.
|
|
48
|
-
- For a local reference, run `evolink upload /absolute/path --json` and use its `file_url` in the model input. A chat attachment must have a readable local file or public URL. `uploads get ID` reads the saved receipt. If it returns `outcome_unknown` and `result_verified: false`, no result was
|
|
48
|
+
- For a local reference, run `evolink upload /absolute/path --json` and use its `file_url` in the model input. A chat attachment must have a readable local file or public URL. Keep the original `upload_id` if a response is lost. `uploads get ID` reads the saved receipt and, when supported by the file service, recovers a completed upload without resending bytes. If it returns `outcome_unknown` and `result_verified: false`, no result was verified; check the user's files before uploading again. A missing receipt from an older service does not prove the file failed to arrive. Legacy MCP upload slots require the older CLI version.
|
|
49
49
|
- Prepare a JSON input file using the model's documented parameters. Run `evolink estimate --model MODEL --input-file /absolute/input.json --json`, adding `--max-cost-usd` only for a user-specified cap. `--media-seconds` is an estimation hint, not a model `duration` parameter or a billing guarantee.
|
|
50
50
|
- Show the user the model, input/reference, number/duration, output settings, estimated total and material uncertainties. For token billing or unknown duration, show the rates and state that the total is unknown. A partial estimate is not an upper bound. Spending caps currently protect the submission estimate, not final settlement.
|
|
51
51
|
|
package/src/api.mjs
CHANGED
|
@@ -46,10 +46,14 @@ export class Api {
|
|
|
46
46
|
}
|
|
47
47
|
throw new CliError('login_required', 'The login expired. Run auth login.');
|
|
48
48
|
}
|
|
49
|
-
async uploadFile(source, size, mime, name, uploadPath) {
|
|
49
|
+
async uploadFile(source, size, mime, name, uploadPath, uploadId) {
|
|
50
50
|
const access = await this.credentials.access();
|
|
51
|
-
try { return await this.platform.upload(source, size, mime, name, this.context(access, 'upload_file'), uploadPath); }
|
|
51
|
+
try { return await this.platform.upload(source, size, mime, name, this.context(access, 'upload_file'), uploadPath, uploadId); }
|
|
52
52
|
catch (error) { throw new CliError(this.signal?.aborted ? 'interrupted' : error.info?.category || 'upload_unknown',
|
|
53
53
|
safeMessage(error.info?.message || 'The upload did not return a verified file result.'), undefined, this.signal?.aborted ? 130 : 1); }
|
|
54
54
|
}
|
|
55
|
+
async uploadReceipt(id) {
|
|
56
|
+
const access = await this.credentials.access();
|
|
57
|
+
return this.platform.uploadReceipt(id, this.context(access, 'get_upload'));
|
|
58
|
+
}
|
|
55
59
|
}
|
package/src/errors.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { publicIdentifier, publicText } from './platform/core/src/services/public-error.js';
|
|
1
2
|
export class CliError extends Error {
|
|
2
3
|
constructor(code, message, details, exitCode = 1) {
|
|
3
4
|
super(message);
|
|
@@ -34,12 +35,7 @@ export async function localFile(action, context) {
|
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
export function safeMessage(message) {
|
|
37
|
-
return String(message)
|
|
38
|
-
.replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')
|
|
39
|
-
.replace(/\b(?:sk-|evup_)[a-zA-Z0-9_-]+/g, '[redacted]')
|
|
40
|
-
.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '[redacted]')
|
|
41
|
-
.replace(/([?&](?:token|access_token|refresh_token|api_key|key|client_secret|code|code_verifier)=)[^\s&#"'<>]+/gi, '$1[redacted]')
|
|
42
|
-
.slice(0, 2000);
|
|
38
|
+
return publicText(String(message));
|
|
43
39
|
}
|
|
44
40
|
|
|
45
41
|
export function errorView(error) {
|
|
@@ -50,11 +46,23 @@ export function errorView(error) {
|
|
|
50
46
|
return { code: error.code, message: safeMessage(error.message), ...(error.details ? { details: safeDetails(error.details) } : {}) };
|
|
51
47
|
}
|
|
52
48
|
|
|
53
|
-
function safeDetails(value) {
|
|
54
|
-
if (
|
|
55
|
-
if (
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
49
|
+
function safeDetails(value, depth = 0, seen = new WeakSet(), key = '') {
|
|
50
|
+
if (depth > 8) return '[truncated]';
|
|
51
|
+
if (typeof value === 'string') {
|
|
52
|
+
if (['client_request_id', 'task_id', 'quote_id', 'request_id'].includes(key)) return publicIdentifier(value);
|
|
53
|
+
// Preserve original media links in a failed task with partial results; they are delivery data.
|
|
54
|
+
if (['url', 'uri', 'image_url', 'video_url', 'audio_url'].includes(key)) {
|
|
55
|
+
try { const url = new URL(value); if (['https:', 'http:'].includes(url.protocol) && !url.username && !url.password) return value; } catch {}
|
|
56
|
+
}
|
|
57
|
+
return safeMessage(value);
|
|
58
|
+
}
|
|
59
|
+
if (value && typeof value === 'object') {
|
|
60
|
+
if (seen.has(value)) return '[truncated]';
|
|
61
|
+
seen.add(value);
|
|
62
|
+
if (Array.isArray(value)) return value.slice(0, 100).map(v => safeDetails(v, depth + 1, seen, key));
|
|
63
|
+
return Object.fromEntries(Object.entries(value).slice(0, 100)
|
|
64
|
+
.filter(([k]) => !k.startsWith('_') && !/^(access_token|refresh_token|client_secret|code_verifier|authorization|upload_url|api_key|apiKey|x-api-key|x-goog-api-key|token|secret|password)$/i.test(k))
|
|
65
|
+
.map(([k, v]) => [safeMessage(k), safeDetails(v, depth + 1, seen, k)]));
|
|
66
|
+
}
|
|
67
|
+
return typeof value === 'number' && !Number.isFinite(value) ? undefined : value;
|
|
60
68
|
}
|
package/src/files.mjs
CHANGED
|
@@ -56,7 +56,7 @@ async function directUpload(file, size, mime, { client, state, server, upload_pa
|
|
|
56
56
|
await state.write('uploads', upload_id, journal);
|
|
57
57
|
const source = createReadStream(file);
|
|
58
58
|
try {
|
|
59
|
-
const result = await client.uploadFile(source, size, mime, path.basename(file), upload_path);
|
|
59
|
+
const result = await client.uploadFile(source, size, mime, path.basename(file), upload_path, upload_id);
|
|
60
60
|
const data = result?.data;
|
|
61
61
|
requireThat(result?.success === true && typeof data?.file_id === 'string' && typeof data?.file_url === 'string',
|
|
62
62
|
'upload_unknown', 'The file service returned no verified upload result.');
|
|
@@ -84,8 +84,20 @@ export async function getUpload(id, { client, state, server }) {
|
|
|
84
84
|
requireThat(journal.api_origin === client.apiUrl.origin && journal.binding === (await client.credentials.access()).binding,
|
|
85
85
|
'upload_session_changed', 'This receipt belongs to a different platform or login.');
|
|
86
86
|
if (journal.state === 'done') return journal.result;
|
|
87
|
+
let receipt;
|
|
88
|
+
try { receipt = await client.uploadReceipt?.(id); }
|
|
89
|
+
catch { throw new CliError('upload_unknown', 'The original upload receipt is unavailable. Keep this upload_id and retry this read later; no bytes were resent.',
|
|
90
|
+
{ upload_id: id, state: 'outcome_unknown', next_step: `evolink uploads get ${id}` }); }
|
|
91
|
+
if (receipt?.state === 'done' && receipt.result_verified === true) {
|
|
92
|
+
const data = receipt.file;
|
|
93
|
+
journal.state = 'done';
|
|
94
|
+
journal.result = { ok: true, upload_id: id, state: 'done', file_id: data.file_id, file_url: data.file_url,
|
|
95
|
+
file_name: data.original_name ?? data.file_name, size_bytes: data.file_size, mime_type: data.mime_type, expires_at: data.expires_at };
|
|
96
|
+
await state.write('uploads', id, journal);
|
|
97
|
+
return journal.result;
|
|
98
|
+
}
|
|
87
99
|
return { ok: true, upload_id: id, state: 'outcome_unknown', result_verified: false,
|
|
88
|
-
text: 'No completed receipt
|
|
100
|
+
text: 'No verified completed receipt is available. The upload may still have arrived. Check your files before starting another upload; this command only reads the original receipt and never resends bytes.' };
|
|
89
101
|
}
|
|
90
102
|
|
|
91
103
|
export async function download(taskId, output, { client, mcp = client, server, index = 1, signal, maxBytes = 1024 ** 3, fetchFn, task: suppliedTask, beforeCommit }) {
|
package/src/media.mjs
CHANGED
|
@@ -100,9 +100,9 @@ export class Media {
|
|
|
100
100
|
result = await this.client.call(`generate_${kind}`, { ...quote.args, client_request_id: quote.client_request_id });
|
|
101
101
|
requireThat(typeof result.task_id === 'string' && result.task_id.length > 0, 'outcome_unknown', 'The submission returned no task ID. Recover with the original quote.');
|
|
102
102
|
} catch (e) {
|
|
103
|
-
quote.state = e.details?.charged === 'no' ? 'refused' : 'outcome_unknown';
|
|
103
|
+
quote.state = e.details?.charged === 'no' && ['not_submitted', 'rejected'].includes(e.details?.submission_state) ? 'refused' : 'outcome_unknown';
|
|
104
104
|
await this.state.write('quotes', id, quote);
|
|
105
|
-
throw new CliError(e.code || 'outcome_unknown', e.message, { ...(e.details || {}), quote_id: id, client_request_id: quote.client_request_id,
|
|
105
|
+
throw new CliError(e.code || 'outcome_unknown', e.message, { ...(e.details || {}), ...(quote.state === 'outcome_unknown' ? { charged: 'unknown', submission_state: 'outcome_unknown' } : {}), quote_id: id, client_request_id: quote.client_request_id,
|
|
106
106
|
recovery: `evolink tasks resume --quote ${id}` }, e.exitCode);
|
|
107
107
|
}
|
|
108
108
|
quote.state = 'submitted';
|
package/src/oauth.mjs
CHANGED
|
@@ -10,7 +10,7 @@ export async function metadata(server, fetchFn) {
|
|
|
10
10
|
const data = await response.json();
|
|
11
11
|
requireThat(data.issuer === issuer && data.code_challenge_methods_supported?.includes('S256'),
|
|
12
12
|
'invalid_auth_metadata', 'Passport did not provide the expected issuer and PKCE method.');
|
|
13
|
-
for (const key of ['authorization_endpoint', 'token_endpoint', '
|
|
13
|
+
for (const key of ['authorization_endpoint', 'token_endpoint', 'revocation_endpoint', ...(data.registration_endpoint ? ['registration_endpoint'] : [])]) {
|
|
14
14
|
let endpoint;
|
|
15
15
|
try { endpoint = new URL(data[key]); } catch { throw new CliError('invalid_auth_metadata', 'Passport did not provide valid login endpoints.'); }
|
|
16
16
|
requireThat(endpoint.origin === issuer && !endpoint.username && !endpoint.password && !endpoint.hash,
|
|
@@ -19,11 +19,19 @@ export async function metadata(server, fetchFn) {
|
|
|
19
19
|
return data;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
async function client(provider, data, fetchFn) {
|
|
22
|
+
async function client(provider, data, fetchFn, newLogin = false) {
|
|
23
23
|
let value = await provider.clientInformation();
|
|
24
24
|
if (value) requireThat(value.issuer === data.issuer && typeof value.client_id === 'string' && !value.client_secret,
|
|
25
25
|
'invalid_client', 'The saved public OAuth client belongs to a different service.');
|
|
26
|
+
// A rolled-back Passport may no longer support media grants for this public
|
|
27
|
+
// identity. Only a new login can change clients; an existing refresh cannot.
|
|
28
|
+
if (newLogin && value?.client_id === 'evolink-cli' && data.evolink_cli_mcp_supported !== true) value = undefined;
|
|
29
|
+
if ((!value || newLogin) && data.evolink_cli_mcp_supported === true) {
|
|
30
|
+
value = { client_id: 'evolink-cli', issuer: data.issuer, token_endpoint_auth_method: 'none' };
|
|
31
|
+
await provider.saveClientInformation(value);
|
|
32
|
+
}
|
|
26
33
|
if (!value) {
|
|
34
|
+
requireThat(data.registration_endpoint, 'registration_unavailable', 'Passport does not support CLI client registration. Update the login service or retry later.');
|
|
27
35
|
const response = await fetchFn(data.registration_endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
28
36
|
body: JSON.stringify(provider.clientMetadata) });
|
|
29
37
|
requireThat(response.ok, 'registration_failed', 'Passport could not register this CLI login.');
|
|
@@ -68,7 +76,7 @@ export async function refresh(provider, fetchFn) {
|
|
|
68
76
|
|
|
69
77
|
export async function authorize(provider, fetchFn, authorizationCode) {
|
|
70
78
|
const data = await metadata(provider.server, fetchFn);
|
|
71
|
-
const info = await client(provider, data, fetchFn);
|
|
79
|
+
const info = await client(provider, data, fetchFn, !authorizationCode);
|
|
72
80
|
if (authorizationCode) return token(provider, data, info, { grant_type: 'authorization_code', code: authorizationCode,
|
|
73
81
|
redirect_uri: String(provider.redirectUrl), code_verifier: await provider.codeVerifier() }, fetchFn);
|
|
74
82
|
const verifier = randomBytes(32).toString('base64url');
|
|
@@ -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
|
|
68
|
+
throw new CredentialError(scoped.unavailableReason ?? 'No EvoLink credential is available for this request.');
|
|
66
69
|
}
|
|
67
70
|
if (!processCredentialsAllowed()) {
|
|
68
|
-
throw new
|
|
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
|
|
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
|
|
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
|
}
|
|
@@ -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
|
-
|
|
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
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
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
|
-
|
|
79
|
-
let response;
|
|
88
|
+
// Reading and verifying the body belong to the submission boundary too.
|
|
80
89
|
try {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
headers,
|
|
84
|
-
|
|
85
|
-
|
|
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 (!
|
|
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
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
|
@@ -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'
|
|
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 (
|
|
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 '
|
|
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 '
|
|
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.
|
|
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.
|
|
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,58 @@ 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
|
|
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;
|
|
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 =
|
|
283
|
-
|
|
284
|
-
|
|
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.';
|
|
285
308
|
const details = {};
|
|
286
309
|
for (const field of DETAIL_FIELDS) {
|
|
287
|
-
|
|
288
|
-
|
|
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);
|
|
289
336
|
}
|
|
290
337
|
let actionUrl;
|
|
291
338
|
if (category === 'account_balance_insufficient') {
|
|
@@ -303,6 +350,7 @@ export function classifyGatewayError(status, body, retryAfterMs, headerRequestId
|
|
|
303
350
|
category,
|
|
304
351
|
...(headline ? { headline } : {}),
|
|
305
352
|
code,
|
|
353
|
+
...(param ? { param } : {}),
|
|
306
354
|
message,
|
|
307
355
|
next_step: '',
|
|
308
356
|
retryable: RETRYABLE.has(category),
|
|
@@ -332,7 +380,7 @@ export function formatApiError(status, body) {
|
|
|
332
380
|
}
|
|
333
381
|
const TASK_ERROR_MAP = {
|
|
334
382
|
content_policy_violation: {
|
|
335
|
-
suggestion: '
|
|
383
|
+
suggestion: 'Review the applicable content policy and revise the input. Do not bypass content review.',
|
|
336
384
|
retryable: false,
|
|
337
385
|
},
|
|
338
386
|
invalid_parameters: {
|
|
@@ -340,15 +388,15 @@ const TASK_ERROR_MAP = {
|
|
|
340
388
|
retryable: false,
|
|
341
389
|
},
|
|
342
390
|
image_dimension_mismatch: {
|
|
343
|
-
suggestion: '
|
|
391
|
+
suggestion: 'Check the input dimensions and aspect ratio against this model’s get_model rules.',
|
|
344
392
|
retryable: false,
|
|
345
393
|
},
|
|
346
394
|
image_processing_error: {
|
|
347
|
-
suggestion: 'The input image could not be processed.
|
|
395
|
+
suggestion: 'The input image could not be processed. Check accessibility, format and size against this model’s get_model rules.',
|
|
348
396
|
retryable: false,
|
|
349
397
|
},
|
|
350
398
|
request_cancelled: {
|
|
351
|
-
suggestion: 'The task was cancelled.
|
|
399
|
+
suggestion: 'The task was cancelled. Check this task’s billing state before deciding whether to request another generation.',
|
|
352
400
|
retryable: false,
|
|
353
401
|
},
|
|
354
402
|
resource_not_found: {
|
|
@@ -356,32 +404,32 @@ const TASK_ERROR_MAP = {
|
|
|
356
404
|
retryable: false,
|
|
357
405
|
},
|
|
358
406
|
generation_timeout: {
|
|
359
|
-
suggestion: '
|
|
407
|
+
suggestion: 'The generation timed out. Check the original task and its billing state before considering another generation.',
|
|
360
408
|
retryable: true,
|
|
361
409
|
},
|
|
362
410
|
quota_exceeded: {
|
|
363
|
-
suggestion: `The
|
|
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.`,
|
|
364
412
|
retryable: true,
|
|
365
413
|
},
|
|
366
414
|
resource_exhausted: {
|
|
367
|
-
suggestion: '
|
|
415
|
+
suggestion: 'Generation capacity was temporarily exhausted. Wait before considering another generation.',
|
|
368
416
|
retryable: true,
|
|
369
417
|
},
|
|
370
418
|
generation_failed_no_content: {
|
|
371
|
-
suggestion: 'The model
|
|
372
|
-
retryable:
|
|
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,
|
|
373
421
|
},
|
|
374
422
|
service_error: {
|
|
375
|
-
suggestion: '
|
|
423
|
+
suggestion: 'The generation service reported an error. Retain the task ID and check its billing state.',
|
|
376
424
|
retryable: true,
|
|
377
425
|
},
|
|
378
426
|
service_unavailable: {
|
|
379
|
-
suggestion: 'The service was temporarily unavailable.
|
|
427
|
+
suggestion: 'The generation service was temporarily unavailable. Retain the task ID and check its billing state.',
|
|
380
428
|
retryable: true,
|
|
381
429
|
},
|
|
382
430
|
unknown_error: {
|
|
383
|
-
suggestion: '
|
|
384
|
-
retryable:
|
|
431
|
+
suggestion: 'The cause is unknown. Give the task ID to EvoLink support; do not generate again automatically.',
|
|
432
|
+
retryable: false,
|
|
385
433
|
},
|
|
386
434
|
};
|
|
387
435
|
export function getTaskErrorInfo(code) {
|
|
@@ -391,14 +439,14 @@ export function getTaskErrorInfo(code) {
|
|
|
391
439
|
? { ...info, suggestion: info.suggestion.replace(TOP_UP_URL, trackedLink(TOP_UP_URL, 'top_up')) }
|
|
392
440
|
: info;
|
|
393
441
|
}
|
|
394
|
-
export function
|
|
395
|
-
const code = error.code ?? '
|
|
442
|
+
export function publicTaskError(error = {}) {
|
|
443
|
+
const code = Object.prototype.hasOwnProperty.call(TASK_ERROR_MAP, error.code ?? '')
|
|
444
|
+
? error.code : 'unknown_error';
|
|
396
445
|
const info = getTaskErrorInfo(code);
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
return lines.join('\n');
|
|
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}`;
|
|
404
452
|
}
|
|
@@ -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
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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
|
-
|
|
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
|
-
|
|
134
|
-
|
|
180
|
+
finally {
|
|
181
|
+
clearTimeout(timer);
|
|
182
|
+
if (abort)
|
|
183
|
+
signal?.removeEventListener('abort', abort);
|
|
184
|
+
reader?.releaseLock();
|
|
135
185
|
}
|
|
136
186
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
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
|
+
/** Only bounded public primitives may cross an error boundary. Result URLs use a separate delivery contract. */
|
|
4
|
+
export function publicIdentifier(value) {
|
|
5
|
+
return typeof value === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(value)
|
|
6
|
+
&& !/^(sk-|evup_|eyJ)/i.test(value) ? value : undefined;
|
|
7
|
+
}
|
|
8
|
+
export function publicText(value) {
|
|
9
|
+
const ids = [];
|
|
10
|
+
const protectedText = value.slice(0, 2000).replace(/client_request_id "([A-Za-z0-9._-]{16,96})"/g, (match, id) => {
|
|
11
|
+
if (!publicIdentifier(id))
|
|
12
|
+
return match;
|
|
13
|
+
ids.push(id);
|
|
14
|
+
return `client_request_id "PUBLICCORRELATION${ids.length - 1}"`;
|
|
15
|
+
});
|
|
16
|
+
return protectedText
|
|
17
|
+
.replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')
|
|
18
|
+
.replace(/\b(?:sk-|evup_)[a-zA-Z0-9_-]+/g, '[redacted]')
|
|
19
|
+
.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '[redacted]')
|
|
20
|
+
.replace(/https?:\/\/[^\s"'<>]+|\b(?:[a-z0-9-]+\.)+[a-z]{2,}(?::\d+)?(?:\/[^\s]*)?(?![A-Za-z0-9_.-])/gi, value => {
|
|
21
|
+
if (/^(input|params|parameters|task|usage|billing|quote|estimate)\.[A-Za-z_][A-Za-z0-9_.]*$/.test(value))
|
|
22
|
+
return value;
|
|
23
|
+
const suffix = /[.,;:!?)]+$/.exec(value)?.[0] ?? '';
|
|
24
|
+
const candidate = suffix ? value.slice(0, -suffix.length) : value;
|
|
25
|
+
try {
|
|
26
|
+
const url = new URL(candidate);
|
|
27
|
+
if (url.origin === 'https://evolink.ai' && !url.username && !url.password && !url.hash
|
|
28
|
+
&& ['/dashboard/credits', '/dashboard/keys', '/dashboard/mcp'].includes(url.pathname)
|
|
29
|
+
&& [...url.searchParams].every(([key, v]) => key.startsWith('utm_') && /^[a-z0-9_-]{1,80}$/i.test(v) || key === 'tab' && v === 'mcp'))
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
catch { }
|
|
33
|
+
return '[service address]';
|
|
34
|
+
})
|
|
35
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ' ')
|
|
36
|
+
.replace(/PUBLICCORRELATION(\d+)/g, (match, n) => ids[Number(n)] ?? match);
|
|
37
|
+
}
|
|
38
|
+
export function publicNumber(value) {
|
|
39
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1e12 ? value : undefined;
|
|
40
|
+
}
|
|
41
|
+
/** Reject prose in identifiers/names rather than letting remote text become an instruction. */
|
|
42
|
+
export function publicLabel(value) {
|
|
43
|
+
if (typeof value !== 'string' || !/^[\p{L}\p{N} _()/-]{1,80}$/u.test(value))
|
|
44
|
+
return undefined;
|
|
45
|
+
return publicText(value) === value ? value : undefined;
|
|
46
|
+
}
|
|
47
|
+
export function publicErrorDetails(value, depth = 0, seen = new WeakSet(), key = '') {
|
|
48
|
+
if (depth > 8)
|
|
49
|
+
return '[truncated]';
|
|
50
|
+
if (typeof value === 'string')
|
|
51
|
+
return ['client_request_id', 'task_id', 'quote_id', 'request_id'].includes(key) ? publicIdentifier(value) : publicText(value);
|
|
52
|
+
if (value && typeof value === 'object') {
|
|
53
|
+
if (seen.has(value))
|
|
54
|
+
return '[truncated]';
|
|
55
|
+
seen.add(value);
|
|
56
|
+
if (Array.isArray(value))
|
|
57
|
+
return value.slice(0, 100).map(v => publicErrorDetails(v, depth + 1, seen, key));
|
|
58
|
+
return Object.fromEntries(Object.entries(value).slice(0, 100)
|
|
59
|
+
.filter(([key]) => !/^(authorization|access_token|refresh_token|api_key|secret|password|client_secret)$/i.test(key))
|
|
60
|
+
.map(([key, nested]) => [publicText(key), publicErrorDetails(nested, depth + 1, seen, key)]));
|
|
61
|
+
}
|
|
62
|
+
return typeof value === 'number' && !Number.isFinite(value) ? undefined : value;
|
|
63
|
+
}
|
|
@@ -119,6 +119,7 @@ function registerGenerate(server, config, kind) {
|
|
|
119
119
|
input.prompt = args.prompt;
|
|
120
120
|
}
|
|
121
121
|
let clientRequestId;
|
|
122
|
+
let acceptedTaskId;
|
|
122
123
|
try {
|
|
123
124
|
const { catalog, entry } = await resolveModel(args.model, config, { fresh: true, allowStale: false });
|
|
124
125
|
if (!entry) {
|
|
@@ -174,6 +175,7 @@ function registerGenerate(server, config, kind) {
|
|
|
174
175
|
tool: name,
|
|
175
176
|
idempotencyKey: clientRequestId,
|
|
176
177
|
});
|
|
178
|
+
acceptedTaskId = submitted.id;
|
|
177
179
|
let task = submitted;
|
|
178
180
|
const waitUntil = started + WAIT_MS[kind];
|
|
179
181
|
if (!TERMINAL_STATUSES.has(task.status) && WAIT_MS[kind] > 0 && Date.now() + 3_000 < waitUntil) {
|
|
@@ -228,7 +230,8 @@ function registerGenerate(server, config, kind) {
|
|
|
228
230
|
}
|
|
229
231
|
catch (error) {
|
|
230
232
|
// clientRequestId is set right before the submit, so it also tells whether a request may have gone out.
|
|
231
|
-
return errorResult(error, { paid: clientRequestId !== undefined, clientRequestId
|
|
233
|
+
return errorResult(error, { paid: clientRequestId !== undefined, clientRequestId, taskId: acceptedTaskId,
|
|
234
|
+
phase: acceptedTaskId ? 'accepted' : clientRequestId ? 'submit_started' : 'before_submit' });
|
|
232
235
|
}
|
|
233
236
|
});
|
|
234
237
|
}
|
|
@@ -1,9 +1,11 @@
|
|
|
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 { CredentialError } from '../config.js';
|
|
4
|
+
import { publicIdentifier, publicErrorDetails, publicText } from '../services/public-error.js';
|
|
3
5
|
import { processCredentialsAllowed } from '../request-context.js';
|
|
4
6
|
import { ApiHttpError } from '../services/api-client.js';
|
|
5
7
|
import { CREDITS_PER_USD, formatCredits, formatUsd } from '../services/error-handler.js';
|
|
6
|
-
import { API_KEYS_URL, PaidRequestOutcomeUnknownError, RequestTimeoutError } from '../services/http-policy.js';
|
|
8
|
+
import { API_KEYS_URL, PaidRequestOutcomeUnknownError, RequestTimeoutError, SubmissionNotStartedError } from '../services/http-policy.js';
|
|
7
9
|
import { trackedLink } from '../services/utm.js';
|
|
8
10
|
/** Free lookups: clients can run them without asking. */
|
|
9
11
|
export const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
@@ -19,7 +21,7 @@ export function ok(text, structured, resources = []) {
|
|
|
19
21
|
return { content: [{ type: 'text', text }, ...resources], structuredContent: { ok: true, ...structured } };
|
|
20
22
|
}
|
|
21
23
|
export function failure(text, structured) {
|
|
22
|
-
return { content: [{ type: 'text', text }], structuredContent: { ok: false, ...structured }, isError: true };
|
|
24
|
+
return { content: [{ type: 'text', text: publicText(text) }], structuredContent: { ok: false, ...(structured.charged === 'no' ? { submission_state: 'not_submitted' } : {}), ...publicErrorDetails(structured) }, isError: true };
|
|
23
25
|
}
|
|
24
26
|
export function money(credits) {
|
|
25
27
|
if (typeof credits !== 'number' || !Number.isFinite(credits))
|
|
@@ -42,10 +44,12 @@ export function usdOf(credits) {
|
|
|
42
44
|
return Number((credits / CREDITS_PER_USD).toFixed(6));
|
|
43
45
|
}
|
|
44
46
|
function infoFor(error) {
|
|
47
|
+
if (error instanceof SubmissionNotStartedError)
|
|
48
|
+
return infoFor(error.cause);
|
|
45
49
|
if (error instanceof ApiHttpError && error.info)
|
|
46
50
|
return error.info;
|
|
47
51
|
if (error instanceof ApiHttpError) {
|
|
48
|
-
return { status: error.status, category: 'server_error', message: error.
|
|
52
|
+
return { status: error.status, category: 'server_error', message: 'The operation returned an unverified error.', next_step: 'Retry in a minute.', retryable: true, request_id: error.requestId };
|
|
49
53
|
}
|
|
50
54
|
if (error instanceof PaidRequestOutcomeUnknownError) {
|
|
51
55
|
return {
|
|
@@ -59,8 +63,13 @@ function infoFor(error) {
|
|
|
59
63
|
if (error instanceof RequestTimeoutError || error instanceof TypeError) {
|
|
60
64
|
return { status: 0, category: 'server_error', message: 'EvoLink did not respond in time.', next_step: 'Retry in a minute.', retryable: true };
|
|
61
65
|
}
|
|
62
|
-
|
|
63
|
-
|
|
66
|
+
if (!(error instanceof CredentialError))
|
|
67
|
+
return {
|
|
68
|
+
status: 0, category: 'server_error', message: 'EvoLink could not complete this operation.',
|
|
69
|
+
next_step: 'Retry free queries. For a generation, recover the original task or client_request_id before creating a new paid request.', retryable: false,
|
|
70
|
+
};
|
|
71
|
+
const message = 'No EvoLink credential is available for this request.';
|
|
72
|
+
// Credential problems surface as typed errors from getApiKey(): no key in this scope, or a
|
|
64
73
|
// signed-in connection that cannot use the hosted service channel.
|
|
65
74
|
return {
|
|
66
75
|
status: 0,
|
|
@@ -75,35 +84,46 @@ function infoFor(error) {
|
|
|
75
84
|
/** Converts a thrown error into a tool error with a category and a concrete next step. */
|
|
76
85
|
export function errorResult(error, context = {}) {
|
|
77
86
|
const info = infoFor(error);
|
|
87
|
+
const requestId = publicIdentifier(info.request_id);
|
|
88
|
+
const clientRequestId = publicIdentifier(context.clientRequestId);
|
|
89
|
+
const taskId = publicIdentifier(context.taskId);
|
|
78
90
|
const label = `${info.category}${info.code ? `, ${info.code}` : ''}${info.status ? `, HTTP ${info.status}` : ''}`;
|
|
79
|
-
// A headline names the limit in plain words first, so every client shows the user which one stopped the call.
|
|
80
91
|
const lines = info.headline ? [info.headline] : [`Error (${label}): ${info.message}`];
|
|
81
|
-
lines.push(`Next step: ${info.next_step}`);
|
|
82
92
|
let charged;
|
|
93
|
+
let submissionState;
|
|
83
94
|
if (context.paid) {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
95
|
+
// An accepted task is stronger evidence than a later credential/read failure.
|
|
96
|
+
const accepted = context.phase === 'accepted' || !!taskId;
|
|
97
|
+
const beforeSubmit = !accepted && (context.phase === 'before_submit' || error instanceof SubmissionNotStartedError || error instanceof CredentialError);
|
|
98
|
+
const rejected = !accepted && error instanceof ApiHttpError && error.submissionState === 'rejected';
|
|
99
|
+
submissionState = accepted ? 'accepted' : beforeSubmit ? 'not_submitted' : rejected ? 'rejected' : 'outcome_unknown';
|
|
100
|
+
charged = beforeSubmit || rejected ? 'no' : 'unknown';
|
|
101
|
+
if (charged === 'unknown') {
|
|
102
|
+
info.next_step = taskId
|
|
103
|
+
? `Query the original task ${taskId}. Do not submit another generation to recover this result.`
|
|
104
|
+
: clientRequestId
|
|
105
|
+
? `Check list_tasks for the original request. To recover this exact submission, pass client_request_id "${clientRequestId}" with identical input; do not create a new quote or request ID.`
|
|
106
|
+
: 'Check list_tasks for the original request. Recover only with the same client_request_id and identical input; do not create a new quote or request ID.';
|
|
107
|
+
lines.push('Whether a charge was made is unknown. A new generation is separately paid and requires a fresh estimate and explicit user approval.');
|
|
93
108
|
}
|
|
109
|
+
else
|
|
110
|
+
lines.push(beforeSubmit ? 'Nothing was submitted or charged.' : 'Nothing was submitted or charged. Gateway admission rejected the generation before dispatch.');
|
|
94
111
|
}
|
|
112
|
+
lines.push(`Next step: ${info.next_step}`);
|
|
95
113
|
// No HTTP status: the request timed out or the connection dropped, so the upload's outcome is unknown.
|
|
96
114
|
if (context.upload && info.category === 'server_error' && !info.status) {
|
|
97
115
|
lines.push('The upload may not have finished. Calling upload_file again is safe.');
|
|
98
116
|
}
|
|
99
117
|
if (info.headline)
|
|
100
118
|
lines.push(`Error: ${label}`);
|
|
101
|
-
if (
|
|
102
|
-
lines.push(`Request ID: ${
|
|
119
|
+
if (requestId)
|
|
120
|
+
lines.push(`Request ID: ${requestId}`);
|
|
103
121
|
return failure(lines.join('\n'), {
|
|
104
122
|
error: info,
|
|
105
123
|
...(charged ? { charged } : {}),
|
|
106
|
-
...(
|
|
124
|
+
...(submissionState ? { submission_state: submissionState } : {}),
|
|
125
|
+
...(clientRequestId && context.paid ? { client_request_id: clientRequestId } : {}),
|
|
126
|
+
...(taskId ? { task_id: taskId } : {}),
|
|
107
127
|
});
|
|
108
128
|
}
|
|
109
129
|
/** Sends a progress notification when the client asked for them; failures are ignored. */
|
|
@@ -0,0 +1,31 @@
|
|
|
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 { publicNumber } from '../services/public-error.js';
|
|
4
|
+
/** Ledger facts are distinct from the task outcome and from approximate usage costs. */
|
|
5
|
+
export function taskBilling(task) {
|
|
6
|
+
const raw = task.billing;
|
|
7
|
+
const billing = { charge_status: 'unknown', refund_status: 'unknown', limit_restoration: 'unknown' };
|
|
8
|
+
if (!raw || raw.refund_scope !== 'account_balance')
|
|
9
|
+
return billing;
|
|
10
|
+
billing.refund_scope = 'account_balance';
|
|
11
|
+
if (['unknown', 'reserved', 'charged', 'released'].includes(raw.charge_status ?? ''))
|
|
12
|
+
billing.charge_status = raw.charge_status;
|
|
13
|
+
if (['unknown', 'not_required', 'pending', 'failed'].includes(raw.refund_status ?? ''))
|
|
14
|
+
billing.refund_status = raw.refund_status;
|
|
15
|
+
for (const field of ['reserved_credits', 'charged_credits']) {
|
|
16
|
+
const n = publicNumber(raw[field]);
|
|
17
|
+
if (n !== undefined)
|
|
18
|
+
billing[field] = n;
|
|
19
|
+
}
|
|
20
|
+
const refunded = publicNumber(raw.refunded_credits);
|
|
21
|
+
const timestamp = typeof raw.refunded_at === 'string' && /^\d{4}-\d{2}-\d{2}T[0-9:.]+Z$/.test(raw.refunded_at)
|
|
22
|
+
&& Number.isFinite(Date.parse(raw.refunded_at)) ? raw.refunded_at : undefined;
|
|
23
|
+
// Require the authoritative release, amount and timestamp together. Status alone is not proof.
|
|
24
|
+
if (raw.refund_status === 'completed' && raw.charge_status === 'released' && timestamp
|
|
25
|
+
&& refunded !== undefined && refunded > 0 && refunded === billing.reserved_credits) {
|
|
26
|
+
billing.refund_status = 'completed';
|
|
27
|
+
billing.refunded_credits = refunded;
|
|
28
|
+
billing.refunded_at = timestamp;
|
|
29
|
+
}
|
|
30
|
+
return billing;
|
|
31
|
+
}
|
|
@@ -1,7 +1,9 @@
|
|
|
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
3
|
import { queryTask } from '../services/api-client.js';
|
|
4
|
-
import {
|
|
4
|
+
import { publicIdentifier } from '../services/public-error.js';
|
|
5
|
+
import { publicTaskError } from '../services/error-handler.js';
|
|
6
|
+
import { taskBilling } from './task-billing.js';
|
|
5
7
|
import { money, sleep, usdOf } from './shared.js';
|
|
6
8
|
/** Result links from the gateway stay downloadable for this long. */
|
|
7
9
|
export const RESULT_LINK_HOURS = 24;
|
|
@@ -150,6 +152,7 @@ export function describeTask(task) {
|
|
|
150
152
|
progress: task.progress ?? 0,
|
|
151
153
|
model: task.model,
|
|
152
154
|
type: task.type,
|
|
155
|
+
billing: taskBilling(task),
|
|
153
156
|
};
|
|
154
157
|
const outputs = taskOutputs(task);
|
|
155
158
|
if (outputs.length) {
|
|
@@ -180,14 +183,29 @@ export function describeTask(task) {
|
|
|
180
183
|
structured.took_seconds = task.duration;
|
|
181
184
|
}
|
|
182
185
|
if (status === 'failed' || status === 'cancelled') {
|
|
183
|
-
const
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
lines.push(`Error: ${code}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
186
|
+
const info = publicTaskError(task.error ?? { code: status === 'cancelled' ? 'request_cancelled' : 'unknown_error' });
|
|
187
|
+
const billing = taskBilling(task);
|
|
188
|
+
structured.billing = billing;
|
|
189
|
+
lines.push(`Error: ${info.code} — ${info.message}`);
|
|
190
|
+
if (billing.refund_status === 'completed') {
|
|
191
|
+
lines.push(`Account balance refund completed: ${money(billing.refunded_credits)}. Key limit restoration is unknown.`);
|
|
192
|
+
structured.refunded = true;
|
|
193
|
+
}
|
|
194
|
+
else if (billing.refund_status === 'pending') {
|
|
195
|
+
lines.push('Account balance refund is pending; it has not been confirmed.');
|
|
196
|
+
}
|
|
197
|
+
else if (billing.refund_status === 'failed') {
|
|
198
|
+
lines.push('Account balance refund processing failed; completion has not been confirmed. Contact EvoLink support with this task ID.');
|
|
199
|
+
}
|
|
200
|
+
else if (billing.refund_status === 'not_required') {
|
|
201
|
+
lines.push('The billing record reports no account balance refund required. Check the recorded charge before requesting another generation.');
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
lines.push('Charge and refund completion cannot be verified from the available billing evidence. Query this task again or contact EvoLink support.');
|
|
205
|
+
}
|
|
206
|
+
const next = `${info.suggestion} Query get_task again to verify billing. Do not generate again automatically. Another generation is a separately paid task: obtain a fresh estimate and explicit user approval first.`;
|
|
207
|
+
lines.push(`Next step: ${next}`);
|
|
208
|
+
structured.error = { ...info, suggestion: next };
|
|
191
209
|
}
|
|
192
210
|
else if (status === 'completed') {
|
|
193
211
|
if (links.length > 0) {
|
|
@@ -207,9 +225,10 @@ export function describeTask(task) {
|
|
|
207
225
|
}
|
|
208
226
|
lines.push(`Next step: call get_task with task_id "${task.id}" again (it can wait up to 45 s). Do not call generate again to check progress: that starts and charges a new task.`);
|
|
209
227
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
228
|
+
const requestId = publicIdentifier(task.request_id);
|
|
229
|
+
if (requestId) {
|
|
230
|
+
lines.push(`Request ID: ${requestId}`);
|
|
231
|
+
structured.request_id = requestId;
|
|
213
232
|
}
|
|
214
233
|
return { lines, structured, resources: resultResources(task.id, links) };
|
|
215
234
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
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
3
|
/** Version reported in serverInfo and in the X-Evo-Client-Version header. */
|
|
4
|
-
export const MCP_VERSION = '1.6.
|
|
4
|
+
export const MCP_VERSION = '1.6.1';
|
package/src/platform/source.json
CHANGED
|
@@ -2,22 +2,22 @@
|
|
|
2
2
|
"schema_version": 1,
|
|
3
3
|
"repository": "Evolink-AI/evolink-mcp",
|
|
4
4
|
"baseline": "acc9fd43b945e3917b47809fc94f85ba26c7c8db",
|
|
5
|
-
"source_sha256": "
|
|
5
|
+
"source_sha256": "5453ba93642db77cd6199e20dbad50487ef9c5fe1ba7284fe6c9b1c5e4bab15e",
|
|
6
6
|
"files": {
|
|
7
7
|
"packages/core/src/branding.ts": "534b944a1370f210a3858c1a85b1a23071aca8e26b7a3e70e4d859ba5b152ff7",
|
|
8
|
-
"packages/core/src/config.ts": "
|
|
8
|
+
"packages/core/src/config.ts": "208496230e22f43817cfb9b3805cde279fcce61a82227dfbd9f63485a33d33c7",
|
|
9
9
|
"packages/core/src/data/model-constraints.ts": "c6a20af6ef181e5b620aa31944d1e8453b72f1794bda4c65397390184636542c",
|
|
10
10
|
"packages/core/src/data/model-params.generated.ts": "9641f2c80475259964104be11f1de86f64c23ccfa6defabb7614ff88ed93d819",
|
|
11
11
|
"packages/core/src/data/model-params.ts": "d387d10b7d888059df9c1bd2177e336a497981b63ecbac57009f399f4e1fd858",
|
|
12
|
-
"packages/core/src/platform-client.ts": "
|
|
12
|
+
"packages/core/src/platform-client.ts": "d272d1fbd7939acd69482207f1a75550e4ff8f584deee8f6d0c8ace86e453b6d",
|
|
13
13
|
"packages/core/src/platform-operations.ts": "7f6d3512ef284a953125e57fa46e3021018e7f5f60c5381fd64511a9b70f082c",
|
|
14
14
|
"packages/core/src/request-context.ts": "c78d28379609779305aa2ebbf3c9cc503a98ed7f144eed48103ab518c9ef5539",
|
|
15
|
-
"packages/core/src/server.ts": "
|
|
16
|
-
"packages/core/src/services/api-client.ts": "
|
|
15
|
+
"packages/core/src/server.ts": "e13c0f9abd3eb7bed4c0c7df734649b7ae18ce870fa01f1cfa6b8c1ed8bf78e6",
|
|
16
|
+
"packages/core/src/services/api-client.ts": "77cc562d8bf2e221aff300064085cfa849d9aabc7a0f8c5d1400206dfee13900",
|
|
17
17
|
"packages/core/src/services/catalog-client.ts": "c2bcfb0f2780112bcddf6a42537cf9f6264717d0b3685c896790339b0f9bb7df",
|
|
18
|
-
"packages/core/src/services/error-handler.ts": "
|
|
19
|
-
"packages/core/src/services/file-client.ts": "
|
|
20
|
-
"packages/core/src/services/http-policy.ts": "
|
|
18
|
+
"packages/core/src/services/error-handler.ts": "c8f7a0857233b16b32c6ba7dea53883e2d5f369b2bafb1001e4811ec6286b7d2",
|
|
19
|
+
"packages/core/src/services/file-client.ts": "9bd94da9a0719fba0050be261fb5210397be4e8b9e6ebc8a2e916fcc185fd2d2",
|
|
20
|
+
"packages/core/src/services/http-policy.ts": "f8cc029627655718d52b30dadaaa503fa6d4597846a13c802b7558d9797ea6bd",
|
|
21
21
|
"packages/core/src/services/media-preview.ts": "89410d8eb9a02e6fb9d9bc0de8a69b48bec7a06039e54569b9fea7e35527b6c4",
|
|
22
22
|
"packages/core/src/services/model-capabilities.ts": "b41c8b6dd34432cd2e44529e7f40aa1dd7c3b5d0d20e5964b78468517e1979df",
|
|
23
23
|
"packages/core/src/services/model-catalog.ts": "742b3ef24ab324b7d8e9fa6c7a6287b975ed7a8b6518b18625099e0976043291",
|
|
@@ -25,56 +25,60 @@
|
|
|
25
25
|
"packages/core/src/services/param-validator.ts": "506e6d6f6a1ad170024d6a24ffcd2434c73e7ac855a89bbba9fdbb81653416fb",
|
|
26
26
|
"packages/core/src/services/preview-download.ts": "719e100e05f7632f633551773159ba7202f755c6d6ff5ecf364b40eeb26bee7b",
|
|
27
27
|
"packages/core/src/services/pricing-client.ts": "904f7006149e1e573d23ee8d5ac23d0121502edea59660847b59bb3a85e19c04",
|
|
28
|
+
"packages/core/src/services/public-error.ts": "01cf744413fd5ba8206e63fb184356f557a5a76d36506f52fc2540f2480217d9",
|
|
28
29
|
"packages/core/src/services/upload-policy.ts": "2dc36716a3b9e78b078c618b029499bf6e27448dd44900b6f917dda5f8046ce3",
|
|
29
|
-
"packages/core/src/services/upload-slots.ts": "
|
|
30
|
+
"packages/core/src/services/upload-slots.ts": "80da2511394daf61e3b8ed3b9fbed06c28fec7d4d5b1c3d68585bd89fa816096",
|
|
30
31
|
"packages/core/src/services/utm.ts": "adb224e91531b0db809b5de086ddc97bb5a383184458554dcdf784a65cd941a5",
|
|
31
32
|
"packages/core/src/tool-guidance.ts": "2c554abc0937fa29fe76008fc390e1039100af620ac4c1a3dd9185c2e92d903f",
|
|
32
33
|
"packages/core/src/tools/check-balance.ts": "f27b269a3c3c838a54fe54005eb72f637ddfdc2982d932901282bbf072d1efca",
|
|
33
34
|
"packages/core/src/tools/discovery.ts": "50adaf61d2e159a78348661b1b49b0332d47079275f943da67b5f132f8997218",
|
|
34
35
|
"packages/core/src/tools/estimate-cost.ts": "d0c41bce5003ce873000cca7ea976a49fb753edf3737f6544481bd0e0f08d2c3",
|
|
35
|
-
"packages/core/src/tools/generate.ts": "
|
|
36
|
+
"packages/core/src/tools/generate.ts": "dd3978321924988011ccff19b64a2f1cad19ece1d7d109987cdd397f56587f76",
|
|
36
37
|
"packages/core/src/tools/get-model.ts": "276be6bb4b1a655fec69aef7347ed24cdab93f16458ffc2af7d7d866cd54b84c",
|
|
37
38
|
"packages/core/src/tools/get-task.ts": "937a5ad4454956dd000abfd11149523d135527018d4d643ede600950d69e6205",
|
|
38
39
|
"packages/core/src/tools/list-tasks.ts": "22e5ac19bbe210fb11ea39afe12fa7f92fb40ffc0560c7bee3d1f9354fc78395",
|
|
39
|
-
"packages/core/src/tools/prepare-upload.ts": "
|
|
40
|
+
"packages/core/src/tools/prepare-upload.ts": "c58cfb04725cc660e34f68391727e99f726e355f9329d91ced56878212294d40",
|
|
40
41
|
"packages/core/src/tools/search-models.ts": "3b950140240ac6c5f0dfdc0264cb4b66d0583e05e220c67245b6e8a7616fc55e",
|
|
41
|
-
"packages/core/src/tools/shared.ts": "
|
|
42
|
-
"packages/core/src/tools/task-
|
|
42
|
+
"packages/core/src/tools/shared.ts": "4edde666dc31af730460cbecf5520cc56626bc2b17f951f849130f3d7d4ccbef",
|
|
43
|
+
"packages/core/src/tools/task-billing.ts": "cfb18355e44caa41ea278b4156bd15e6c3ebca13411c7cf043d7225c5532dcce",
|
|
44
|
+
"packages/core/src/tools/task-format.ts": "d9d367086db95034a04e6f1639fc1bdbced719b046233b0da905d06fd421f595",
|
|
43
45
|
"packages/core/src/tools/task-usage.ts": "ba05d054e1d60d67f6ab75cc6d9169f453c87e0e89c17a2c1be5fc429e8f9f47",
|
|
44
46
|
"packages/core/src/tools/upload-file.ts": "da6f239d1b1e6a13a7b418d24e738ebabf9823b2656111eeaa70eb247421ad40",
|
|
45
|
-
"packages/core/src/version.ts": "
|
|
47
|
+
"packages/core/src/version.ts": "f614986abbb91e2925f5817cad0ce27b3d02dec51498d73d4cca45644c74bdc7"
|
|
46
48
|
},
|
|
47
49
|
"artifacts": {
|
|
48
|
-
"core/src/config.js": "
|
|
50
|
+
"core/src/config.js": "e5f001e6bb30fa3ca49ca1383b3deb83ea495d20079adefad6d0451f5bbee0e3",
|
|
49
51
|
"core/src/data/model-constraints.js": "78029eb010d93e87ba4262b69e80bcdd87b979d38ce620c29bab70f9c967df7b",
|
|
50
52
|
"core/src/data/model-params.generated.js": "9f6ee98f59b9571797ab8e3d5ed874724fe386ec7616ae338596db15de8f3f78",
|
|
51
53
|
"core/src/data/model-params.js": "1c746a0547674ca5fb5f2a8bf9f6ca5496e6897193651917c84023088fc749ec",
|
|
52
|
-
"core/src/platform-client.js": "
|
|
54
|
+
"core/src/platform-client.js": "7268a23e0c42ac454bc78bb4a768166670ad3996c13fa88ede03007dbee755e7",
|
|
53
55
|
"core/src/platform-operations.js": "5e9752fb6660a846d35a5a39818090ee8ec09239c81e4039ebd135dbb6985738",
|
|
54
56
|
"core/src/request-context.js": "ed22b79db1fc8b20c57f0a58e938ff4a833bb6a75a16d2246f732a41256c21e8",
|
|
55
|
-
"core/src/services/api-client.js": "
|
|
57
|
+
"core/src/services/api-client.js": "6fa90c70db20e7effdbe5dd492af3b21a30cdb7c2b709feb764db5dd4e8ab0e9",
|
|
56
58
|
"core/src/services/catalog-client.js": "f438fdb13fa9e9ddbf539b265bfcbb77c4d5024835130cbade3b83e9952893cf",
|
|
57
|
-
"core/src/services/error-handler.js": "
|
|
58
|
-
"core/src/services/file-client.js": "
|
|
59
|
-
"core/src/services/http-policy.js": "
|
|
59
|
+
"core/src/services/error-handler.js": "eed1413ac1aaeee6eb1fd8180f37d471268bd7a5a82dacba423356e2fefe8839",
|
|
60
|
+
"core/src/services/file-client.js": "d11798bfddc6637727a874532ad218b5deac58d6bca8f20abcd2c30b132210e4",
|
|
61
|
+
"core/src/services/http-policy.js": "322892ddb21f15cb3111a36b006b3ab62bea7a9d13b05d970ded62bae3ca32cd",
|
|
60
62
|
"core/src/services/model-capabilities.js": "2ad86bc08c82cce82964b18d6187632fc738f8cd17d03de1ef04f27b1e35cfe1",
|
|
61
63
|
"core/src/services/model-catalog.js": "0bda8fafa579fd33c7450807597e0798fd510450d9c7aee9211fb34e1748de72",
|
|
62
64
|
"core/src/services/model-recommendations.js": "f330f941d26aa9fc127c2f7479cb2be026d6111a3f3066e89442ff29ec33803a",
|
|
63
65
|
"core/src/services/param-validator.js": "9e3fba916a39140614851689fcf47f1aa644a30b6192b6126af4d78695f88b10",
|
|
64
66
|
"core/src/services/pricing-client.js": "2f0f74f7769442e4edf8c3f37a66bb1c6c099253189e9b2079ad265d1327225d",
|
|
67
|
+
"core/src/services/public-error.js": "3982fd6ecf2600f708aa9d9e86efd72885dd4e2f701dd7880b9fa447e8367e08",
|
|
65
68
|
"core/src/services/utm.js": "8aa328ddb92c3ef65568fab60226cb5fa2e940449d7ac3d6c2e35b6f9bcf835d",
|
|
66
69
|
"core/src/tool-guidance.js": "fc0d4bd4ce6bc60ba9d3f01efab386698c744b9dd9386d148abc3ebe68cfa7b7",
|
|
67
70
|
"core/src/tools/check-balance.js": "75baa61e57e289fd61a45251665df599967ba0beb4b33cc3976280a9d89421bf",
|
|
68
71
|
"core/src/tools/discovery.js": "6095a2f699fbf465bcae3387b137901ecdbbbb00bbfa6f4b3250a7c293c45b70",
|
|
69
72
|
"core/src/tools/estimate-cost.js": "d0f5a82b2c9d7770500870cf1a7bc7b41fd1677d08d1f8b72d8a03936c8b0a76",
|
|
70
|
-
"core/src/tools/generate.js": "
|
|
73
|
+
"core/src/tools/generate.js": "e2997695d1ae7887f8f7b31dc2b888545dff507ad070a320325892bdcb89b339",
|
|
71
74
|
"core/src/tools/get-model.js": "e7d8d8165277fab474547527ad7f08cee3a6bb2b47162235357456534faebadb",
|
|
72
75
|
"core/src/tools/get-task.js": "1ef62167c629c7ad859d1d31cd8779eb98e3a22c8bb754b2c355e58515b308f0",
|
|
73
76
|
"core/src/tools/list-tasks.js": "e795aeebed047d3ba72c87d699f3bb1306bc626d04c69db2a2667607abce586e",
|
|
74
77
|
"core/src/tools/search-models.js": "9850b7d2d74a1d69229400d465b21ecb9ede79c75dddeb41787668f418c5bd06",
|
|
75
|
-
"core/src/tools/shared.js": "
|
|
76
|
-
"core/src/tools/task-
|
|
78
|
+
"core/src/tools/shared.js": "77d54bced4e05b3712a2bb44b6075d792d6dde18212aa0e615bf83af1b36bf79",
|
|
79
|
+
"core/src/tools/task-billing.js": "f49b252afcaf4a6275f5db6ebc8e6380387b2406bd5fc91e7367e3523025af8b",
|
|
80
|
+
"core/src/tools/task-format.js": "2daefc0f34ff14f0be38eb65b6e91dacd0c3f111a474e424a25906c9d8122338",
|
|
77
81
|
"core/src/tools/task-usage.js": "3aae5d7807efc2c762bf604cf9ecfecf8f9008185bcef584e6d4243404418dc5",
|
|
78
|
-
"core/src/version.js": "
|
|
82
|
+
"core/src/version.js": "d0d9da469fddf7d1fa19b1ade8fc23b048caff2e7510b445c9772b5390159b2a"
|
|
79
83
|
}
|
|
80
84
|
}
|