@evolinkai/cli 0.6.0 → 0.8.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.
- package/README.md +65 -5
- package/package.json +27 -8
- package/skills/evolink-cli/SKILL.md +11 -4
- package/skills/evolink-cli/references/capabilities.md +38 -0
- package/skills/evolink-cli/references/usage-and-budget.md +17 -0
- package/src/api.mjs +55 -0
- package/src/auth.mjs +6 -7
- package/src/cli.mjs +96 -29
- package/src/doctor.mjs +9 -6
- package/src/files.mjs +143 -7
- package/src/help.mjs +68 -0
- package/src/media.mjs +9 -7
- package/src/network.mjs +12 -1
- package/src/oauth.mjs +82 -0
- package/src/platform/LICENSE +178 -0
- package/src/platform/NOTICE +6 -0
- package/src/platform/core/src/config.js +92 -0
- package/src/platform/core/src/data/model-constraints.js +37 -0
- package/src/platform/core/src/data/model-params.generated.js +4 -0
- package/src/platform/core/src/data/model-params.js +28 -0
- package/src/platform/core/src/platform-client.js +50 -0
- package/src/platform/core/src/platform-operations.js +22 -0
- package/src/platform/core/src/request-context.js +53 -0
- package/src/platform/core/src/services/api-client.js +205 -0
- package/src/platform/core/src/services/catalog-client.js +45 -0
- package/src/platform/core/src/services/error-handler.js +404 -0
- package/src/platform/core/src/services/file-client.js +133 -0
- package/src/platform/core/src/services/http-policy.js +136 -0
- package/src/platform/core/src/services/model-capabilities.js +24 -0
- package/src/platform/core/src/services/model-catalog.js +68 -0
- package/src/platform/core/src/services/model-recommendations.js +35 -0
- package/src/platform/core/src/services/param-validator.js +201 -0
- package/src/platform/core/src/services/pricing-client.js +451 -0
- package/src/platform/core/src/services/utm.js +65 -0
- package/src/platform/core/src/tool-guidance.js +50 -0
- package/src/platform/core/src/tools/check-balance.js +90 -0
- package/src/platform/core/src/tools/discovery.js +86 -0
- package/src/platform/core/src/tools/estimate-cost.js +136 -0
- package/src/platform/core/src/tools/generate.js +234 -0
- package/src/platform/core/src/tools/get-model.js +146 -0
- package/src/platform/core/src/tools/get-task.js +57 -0
- package/src/platform/core/src/tools/list-tasks.js +170 -0
- package/src/platform/core/src/tools/search-models.js +115 -0
- package/src/platform/core/src/tools/shared.js +138 -0
- package/src/platform/core/src/tools/task-format.js +245 -0
- package/src/platform/core/src/tools/task-usage.js +108 -0
- package/src/platform/core/src/version.js +4 -0
- package/src/platform/source.json +80 -0
- package/src/setup.mjs +9 -5
- package/src/mcp.mjs +0 -36
|
@@ -0,0 +1,28 @@
|
|
|
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 { MODEL_PARAMS_JSON } from './model-params.generated.js';
|
|
4
|
+
import { withModelConstraints } from './model-constraints.js';
|
|
5
|
+
let index;
|
|
6
|
+
function load() {
|
|
7
|
+
if (!index) {
|
|
8
|
+
index = JSON.parse(MODEL_PARAMS_JSON);
|
|
9
|
+
for (const model of Object.values(index.models))
|
|
10
|
+
withModelConstraints(model);
|
|
11
|
+
}
|
|
12
|
+
return index;
|
|
13
|
+
}
|
|
14
|
+
export function modelParamsMeta() {
|
|
15
|
+
return load().meta;
|
|
16
|
+
}
|
|
17
|
+
export function allModelParams() {
|
|
18
|
+
return Object.values(load().models);
|
|
19
|
+
}
|
|
20
|
+
/** Exact model ID first, then a case-insensitive match. */
|
|
21
|
+
export function findModelParams(model) {
|
|
22
|
+
const models = load().models;
|
|
23
|
+
const trimmed = model.trim();
|
|
24
|
+
if (models[trimmed])
|
|
25
|
+
return models[trimmed];
|
|
26
|
+
const lower = trimmed.toLowerCase();
|
|
27
|
+
return Object.values(models).find(entry => entry.model.toLowerCase() === lower);
|
|
28
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
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 { z } from 'zod';
|
|
4
|
+
import { registerPlatformOperations } from './platform-operations.js';
|
|
5
|
+
import { runWithRequestCredentials } from './request-context.js';
|
|
6
|
+
import { requestUploadToken } from './services/api-client.js';
|
|
7
|
+
import { fileStreamUploadFrom } from './services/file-client.js';
|
|
8
|
+
import { errorResult, failure } from './tools/shared.js';
|
|
9
|
+
/** Local execution of the shared operations. Network traffic is REST only. */
|
|
10
|
+
export class PlatformClient {
|
|
11
|
+
config;
|
|
12
|
+
operations = new Map();
|
|
13
|
+
constructor(config) {
|
|
14
|
+
this.config = config;
|
|
15
|
+
const registry = { registerTool: (name, definition, handler) => {
|
|
16
|
+
this.operations.set(name, { schema: z.object(definition.inputSchema).strict(), handler });
|
|
17
|
+
return {};
|
|
18
|
+
} };
|
|
19
|
+
registerPlatformOperations(registry, config);
|
|
20
|
+
}
|
|
21
|
+
supports(name, inputs = []) {
|
|
22
|
+
const operation = this.operations.get(name);
|
|
23
|
+
return Boolean(operation && inputs.every(input => Object.hasOwn(operation.schema.shape, input)));
|
|
24
|
+
}
|
|
25
|
+
async call(name, args, credentials) {
|
|
26
|
+
const operation = this.operations.get(name);
|
|
27
|
+
if (!operation)
|
|
28
|
+
return failure('Unknown platform operation.', { error: { category: 'invalid_request' }, charged: 'no' });
|
|
29
|
+
const parsed = operation.schema.safeParse(args);
|
|
30
|
+
if (!parsed.success)
|
|
31
|
+
return failure('The operation arguments are invalid; nothing was submitted or charged.', {
|
|
32
|
+
error: { category: 'invalid_request' }, problems: parsed.error.issues.map(issue => ({ param: issue.path.join('.'), problem: issue.message })), charged: 'no',
|
|
33
|
+
});
|
|
34
|
+
return runWithRequestCredentials(credentials, async () => {
|
|
35
|
+
try {
|
|
36
|
+
return await operation.handler(parsed.data, { signal: credentials.http?.signal ?? new AbortController().signal });
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
return errorResult(error);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
async upload(source, size, mime, name, credentials, uploadPath) {
|
|
44
|
+
return runWithRequestCredentials(credentials, async () => {
|
|
45
|
+
const token = await requestUploadToken(this.config, 'upload_file');
|
|
46
|
+
return fileStreamUploadFrom(source, size, mime, name, { uploadPath, auth: { bearer: token.token },
|
|
47
|
+
signal: credentials.http?.signal, timeoutMs: 900_000 });
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
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 { registerDiscovery } from './tools/discovery.js';
|
|
4
|
+
import { registerTaskUsage } from './tools/task-usage.js';
|
|
5
|
+
import { registerCheckBalance } from './tools/check-balance.js';
|
|
6
|
+
import { registerEstimateCost } from './tools/estimate-cost.js';
|
|
7
|
+
import { registerGenerateTools } from './tools/generate.js';
|
|
8
|
+
import { registerGetModel } from './tools/get-model.js';
|
|
9
|
+
import { registerGetTask } from './tools/get-task.js';
|
|
10
|
+
import { registerListTasks } from './tools/list-tasks.js';
|
|
11
|
+
import { registerSearchModels } from './tools/search-models.js';
|
|
12
|
+
export function registerPlatformOperations(registry, config) {
|
|
13
|
+
registerSearchModels(registry, config);
|
|
14
|
+
registerDiscovery(registry, config);
|
|
15
|
+
registerGetModel(registry, config);
|
|
16
|
+
registerEstimateCost(registry, config);
|
|
17
|
+
registerGenerateTools(registry, config);
|
|
18
|
+
registerGetTask(registry, config);
|
|
19
|
+
registerListTasks(registry, config);
|
|
20
|
+
registerTaskUsage(registry, config);
|
|
21
|
+
registerCheckBalance(registry, config);
|
|
22
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
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 { AsyncLocalStorage } from 'node:async_hooks';
|
|
4
|
+
const storage = new AsyncLocalStorage();
|
|
5
|
+
let processCredentialsDisabled = false;
|
|
6
|
+
let processClientName;
|
|
7
|
+
let processLinkCampaign = 'mcp_local';
|
|
8
|
+
export function runWithRequestCredentials(credentials, fn) {
|
|
9
|
+
return storage.run(credentials, fn);
|
|
10
|
+
}
|
|
11
|
+
export function currentRequestCredentials() {
|
|
12
|
+
return storage.getStore();
|
|
13
|
+
}
|
|
14
|
+
/** Hosted mode: never fall back to EVOLINK_API_KEY or the local credential helper. */
|
|
15
|
+
export function disableProcessCredentials() {
|
|
16
|
+
processCredentialsDisabled = true;
|
|
17
|
+
}
|
|
18
|
+
export function processCredentialsAllowed() {
|
|
19
|
+
return !processCredentialsDisabled;
|
|
20
|
+
}
|
|
21
|
+
export function currentCredentialMode() {
|
|
22
|
+
if (storage.getStore()?.serviceChannel)
|
|
23
|
+
return 'signed_in';
|
|
24
|
+
return processCredentialsDisabled ? 'api_key' : 'local';
|
|
25
|
+
}
|
|
26
|
+
/** stdio: remember the assistant name from the MCP initialize handshake. */
|
|
27
|
+
export function setProcessClientName(name) {
|
|
28
|
+
processClientName = sanitizeClientName(name);
|
|
29
|
+
}
|
|
30
|
+
/** The request's assistant name inside a hosted scope, otherwise the stdio client's. */
|
|
31
|
+
export function currentClientName() {
|
|
32
|
+
const scoped = storage.getStore();
|
|
33
|
+
if (scoped)
|
|
34
|
+
return sanitizeClientName(scoped.clientName);
|
|
35
|
+
return processClientName;
|
|
36
|
+
}
|
|
37
|
+
/** stdio entry points: which edition this process is, for site links outside a hosted request. */
|
|
38
|
+
export function setProcessLinkCampaign(campaign) {
|
|
39
|
+
processLinkCampaign = campaign;
|
|
40
|
+
}
|
|
41
|
+
/** What site links need to know about the caller: the hosted request's own values, otherwise the stdio client's. */
|
|
42
|
+
export function currentLinkContext() {
|
|
43
|
+
const scoped = storage.getStore();
|
|
44
|
+
if (scoped) {
|
|
45
|
+
return { clientId: scoped.clientId, clientName: sanitizeClientName(scoped.clientName), campaign: scoped.linkCampaign ?? processLinkCampaign };
|
|
46
|
+
}
|
|
47
|
+
return { clientName: processClientName, campaign: processLinkCampaign };
|
|
48
|
+
}
|
|
49
|
+
/** Printable ASCII only, at most 64 characters, so it is safe in a header and a log line. */
|
|
50
|
+
export function sanitizeClientName(value) {
|
|
51
|
+
const cleaned = (value ?? '').replace(/[^\x20-\x7e]/g, '').trim().slice(0, 64);
|
|
52
|
+
return cleaned || undefined;
|
|
53
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
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 { gatewayAuthHeaders } from '../config.js';
|
|
4
|
+
import { currentRequestCredentials } from '../request-context.js';
|
|
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';
|
|
7
|
+
// --- Error class for HTTP-level failures ---
|
|
8
|
+
export class ApiHttpError extends Error {
|
|
9
|
+
status;
|
|
10
|
+
retryAfterMs;
|
|
11
|
+
requestId;
|
|
12
|
+
info;
|
|
13
|
+
constructor(status, message, retryAfterMs, requestId, info) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.retryAfterMs = retryAfterMs;
|
|
17
|
+
this.requestId = requestId;
|
|
18
|
+
this.info = info;
|
|
19
|
+
this.name = 'ApiHttpError';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
// --- Retry logic ---
|
|
23
|
+
const RETRYABLE_STATUS_CODES = new Set([429, 502, 503]);
|
|
24
|
+
function sleep(ms) {
|
|
25
|
+
const signal = currentRequestCredentials()?.http?.signal;
|
|
26
|
+
return new Promise(resolve => {
|
|
27
|
+
const timer = setTimeout(done, ms);
|
|
28
|
+
function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); }
|
|
29
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
30
|
+
if (signal?.aborted)
|
|
31
|
+
done();
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
function isRetryable(error) {
|
|
35
|
+
// Key and balance rejections are always HTTP 402, so they are never retried here.
|
|
36
|
+
if (error instanceof ApiHttpError)
|
|
37
|
+
return RETRYABLE_STATUS_CODES.has(error.status);
|
|
38
|
+
if (error instanceof PaidRequestOutcomeUnknownError)
|
|
39
|
+
return true;
|
|
40
|
+
if (error instanceof RequestTimeoutError)
|
|
41
|
+
return true;
|
|
42
|
+
if (error instanceof TypeError)
|
|
43
|
+
return true; // network errors (DNS, reset, …)
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
export async function withRetry(fn, retries, baseDelayMs) {
|
|
47
|
+
let lastError;
|
|
48
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
49
|
+
try {
|
|
50
|
+
return await fn();
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
lastError = error;
|
|
54
|
+
if (attempt < retries && isRetryable(error) && !currentRequestCredentials()?.http?.signal?.aborted) {
|
|
55
|
+
const retryAfterMs = error instanceof ApiHttpError ? error.retryAfterMs : undefined;
|
|
56
|
+
await sleep(Math.min(retryAfterMs ?? baseDelayMs * (attempt + 1), MAX_RETRY_DELAY_MS));
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
throw lastError;
|
|
63
|
+
}
|
|
64
|
+
// --- Core request (no retry) ---
|
|
65
|
+
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;
|
|
77
|
+
}
|
|
78
|
+
const isRead = options.method === 'GET' || !options.idempotencyKey;
|
|
79
|
+
let response;
|
|
80
|
+
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));
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
if (!isRead)
|
|
89
|
+
throw new PaidRequestOutcomeUnknownError(error, options.idempotencyKey);
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
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 };
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Submit one paid intent. At most one transport retry, always with the same
|
|
103
|
+
* idempotency key, so the gateway ledger (Idempotency-Key) can return the
|
|
104
|
+
* original task instead of creating a second one.
|
|
105
|
+
*/
|
|
106
|
+
export async function submitTask(config, options) {
|
|
107
|
+
const idempotencyKey = options.idempotencyKey ?? newRunId();
|
|
108
|
+
const { data, requestId, headers } = await withRetry(() => rawRequest(config, {
|
|
109
|
+
method: 'POST',
|
|
110
|
+
path: options.path,
|
|
111
|
+
body: options.body,
|
|
112
|
+
tool: options.tool,
|
|
113
|
+
idempotencyKey,
|
|
114
|
+
}), 1, 500);
|
|
115
|
+
if (!data.request_id && requestId)
|
|
116
|
+
data.request_id = requestId;
|
|
117
|
+
if (headers.get('idempotency-replayed') === 'true')
|
|
118
|
+
data.idempotency_replayed = true;
|
|
119
|
+
return data;
|
|
120
|
+
}
|
|
121
|
+
/** Read-only, credential-specific availability; never cached across accounts. */
|
|
122
|
+
export async function getAvailableModelIds(config) {
|
|
123
|
+
const { data } = await withRetry(() => rawRequest(config, {
|
|
124
|
+
method: 'GET', path: '/v1/models', tool: 'model_catalog',
|
|
125
|
+
}), 2, 1500);
|
|
126
|
+
if (!Array.isArray(data.data) || data.data.some(model => typeof model.id !== 'string')) {
|
|
127
|
+
throw new Error('The available-model list could not be verified. Try again before generating.');
|
|
128
|
+
}
|
|
129
|
+
return data.data.map(model => model.id);
|
|
130
|
+
}
|
|
131
|
+
/** @deprecated kept for callers outside the tools; use submitTask. */
|
|
132
|
+
export async function apiRequest(config, options) {
|
|
133
|
+
if (options.method !== 'POST' || !options.body) {
|
|
134
|
+
throw new Error('apiRequest only accepts generation POST operations');
|
|
135
|
+
}
|
|
136
|
+
return submitTask(config, { path: options.path, body: options.body, tool: options.tool ?? 'unknown' });
|
|
137
|
+
}
|
|
138
|
+
/** One task (GET /v1/tasks/{id}). Unfinished tasks sync with the provider on every read, so callers pace themselves. */
|
|
139
|
+
export async function queryTask(config, taskId, tool = 'get_task') {
|
|
140
|
+
const { data, requestId } = await withRetry(() => rawRequest(config, { method: 'GET', path: `/v1/tasks/${encodeURIComponent(taskId)}`, tool }), 2, 1500);
|
|
141
|
+
if (!data.request_id && requestId)
|
|
142
|
+
data.request_id = requestId;
|
|
143
|
+
return data;
|
|
144
|
+
}
|
|
145
|
+
/** Up to 50 tasks in one call (POST /v1/tasks/batch); unknown or foreign IDs are simply absent. */
|
|
146
|
+
export async function queryTasks(config, taskIds, tool = 'list_tasks') {
|
|
147
|
+
const { data } = await withRetry(() => rawRequest(config, {
|
|
148
|
+
method: 'POST',
|
|
149
|
+
path: '/v1/tasks/batch',
|
|
150
|
+
body: { task_ids: taskIds },
|
|
151
|
+
tool,
|
|
152
|
+
}), 2, 1500);
|
|
153
|
+
return Array.isArray(data.data) ? data.data : [];
|
|
154
|
+
}
|
|
155
|
+
/** The account's recent tasks, newest first (GET /v1/tasks). Items carry no result links. */
|
|
156
|
+
export async function listTasks(config, query, tool = 'list_tasks', options = {}) {
|
|
157
|
+
const params = new URLSearchParams();
|
|
158
|
+
if (query.status)
|
|
159
|
+
params.set('status', query.status);
|
|
160
|
+
if (query.type)
|
|
161
|
+
params.set('type', query.type);
|
|
162
|
+
if (query.model)
|
|
163
|
+
params.set('model', query.model);
|
|
164
|
+
params.set('page', String(query.page ?? 1));
|
|
165
|
+
params.set('page_size', String(query.pageSize ?? 20));
|
|
166
|
+
const { data } = await withRetry(() => rawRequest(config, { method: 'GET', path: `/v1/tasks?${params}`, tool, timeoutMs: options.timeoutMs }), options.retries ?? 2, 1500);
|
|
167
|
+
if (!Array.isArray(data.data) || !Number.isSafeInteger(data.total) || data.total < 0) {
|
|
168
|
+
throw new ApiHttpError(502, 'The task list could not be verified. Retry this read; do not infer zero usage or submit another task.');
|
|
169
|
+
}
|
|
170
|
+
if ((data.page !== undefined && data.page !== (query.page ?? 1))
|
|
171
|
+
|| (data.page_size !== undefined && data.page_size !== (query.pageSize ?? 20))) {
|
|
172
|
+
throw new ApiHttpError(502, 'The task page did not match the requested pagination. Retry this read; no usage total can be verified.');
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
data: data.data,
|
|
176
|
+
total: data.total,
|
|
177
|
+
page: typeof data.page === 'number' ? data.page : query.page ?? 1,
|
|
178
|
+
page_size: typeof data.page_size === 'number' ? data.page_size : query.pageSize ?? 20,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* A short-lived upload token for a signed-in hosted connection (POST
|
|
183
|
+
* /v1/files/upload-token). The connection has no API key of its own, so
|
|
184
|
+
* files-api takes this token instead. Free; the gateway allows 30 a minute per
|
|
185
|
+
* account.
|
|
186
|
+
*/
|
|
187
|
+
export async function requestUploadToken(config, tool) {
|
|
188
|
+
const { data, requestId } = await withRetry(() => rawRequest(config, { method: 'POST', path: '/v1/files/upload-token', tool }), 1, 500);
|
|
189
|
+
const token = typeof data.upload_token === 'string' ? data.upload_token : '';
|
|
190
|
+
const expiresAt = typeof data.expires_at === 'number' ? data.expires_at : 0;
|
|
191
|
+
if (!token.startsWith('evup_') || expiresAt <= 0) {
|
|
192
|
+
const info = classifyGatewayError(500, { error: { message: 'EvoLink returned no upload token.' } }, undefined, requestId);
|
|
193
|
+
throw new ApiHttpError(500, formatGatewayError(info), undefined, requestId, info);
|
|
194
|
+
}
|
|
195
|
+
return { token, expiresAt };
|
|
196
|
+
}
|
|
197
|
+
/** Account balance and this key's usage (GET /v1/credits). */
|
|
198
|
+
export async function getCredits(config, tool = 'check_balance') {
|
|
199
|
+
const { data, requestId } = await withRetry(() => rawRequest(config, { method: 'GET', path: '/v1/credits', tool }), 2, 1000);
|
|
200
|
+
if (data.success === false || !data.data?.user || !data.data?.token) {
|
|
201
|
+
const info = classifyGatewayError(500, { error: { message: data.message || 'The balance could not be read.' } }, undefined, requestId);
|
|
202
|
+
throw new ApiHttpError(500, formatGatewayError(info), undefined, requestId, info);
|
|
203
|
+
}
|
|
204
|
+
return data.data;
|
|
205
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
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 { controlBaseURL } from './pricing-client.js';
|
|
4
|
+
import { DEFAULT_READ_TIMEOUT_MS, evoHeaders, fetchWithTimeout, readJsonBody, timeoutFromEnv } from './http-policy.js';
|
|
5
|
+
const catalogs = new Map();
|
|
6
|
+
const healths = new Map();
|
|
7
|
+
async function read(path) {
|
|
8
|
+
const response = await fetchWithTimeout(`${controlBaseURL()}${path}`, {
|
|
9
|
+
method: 'GET', headers: { Accept: 'application/json', ...evoHeaders('model_catalog') },
|
|
10
|
+
}, timeoutFromEnv('EVOLINK_MCP_READ_TIMEOUT_MS', DEFAULT_READ_TIMEOUT_MS));
|
|
11
|
+
const body = await readJsonBody(response);
|
|
12
|
+
if (!response.ok || !Array.isArray(body.models))
|
|
13
|
+
throw new Error('The current model catalog is unavailable; try again before selecting or submitting a model.');
|
|
14
|
+
return body;
|
|
15
|
+
}
|
|
16
|
+
export async function currentModels() {
|
|
17
|
+
const now = Date.now();
|
|
18
|
+
const key = controlBaseURL();
|
|
19
|
+
const catalog = catalogs.get(key), health = healths.get(key);
|
|
20
|
+
const [models, available] = await Promise.all([
|
|
21
|
+
(async () => {
|
|
22
|
+
if (catalog && now - catalog.fetchedAt < 5 * 60_000)
|
|
23
|
+
return catalog.models;
|
|
24
|
+
const body = await read('/v1/catalog/models');
|
|
25
|
+
const models = body.models.filter(model => typeof model.model_id === 'string'
|
|
26
|
+
&& Array.isArray(model.aliases) && Array.isArray(model.capabilities) && Array.isArray(model.protocols));
|
|
27
|
+
catalogs.set(key, { models, fetchedAt: now });
|
|
28
|
+
return models;
|
|
29
|
+
})(),
|
|
30
|
+
(async () => {
|
|
31
|
+
if (health && now - health.fetchedAt < 30_000)
|
|
32
|
+
return health.available;
|
|
33
|
+
const body = await read('/v1/catalog/health');
|
|
34
|
+
const available = new Set(body.models
|
|
35
|
+
.filter(model => typeof model.model_id === 'string' && model.status === 'available').map(model => model.model_id.toLowerCase()));
|
|
36
|
+
healths.set(key, { available, fetchedAt: now });
|
|
37
|
+
return available;
|
|
38
|
+
})(),
|
|
39
|
+
]);
|
|
40
|
+
return { models, available };
|
|
41
|
+
}
|
|
42
|
+
export function resetCatalogCacheForTests() {
|
|
43
|
+
catalogs.clear();
|
|
44
|
+
healths.clear();
|
|
45
|
+
}
|