@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,57 @@
|
|
|
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 { READ_ONLY, errorResult, ok, progressReporter } from './shared.js';
|
|
5
|
+
import { RESULT_DELIVERY_GUIDANCE, TERMINAL_STATUSES, describeTask, waitForTask } from './task-format.js';
|
|
6
|
+
export const TASK_ID = /^[A-Za-z0-9._:-]{4,128}$/;
|
|
7
|
+
/** Codex and Cursor drop a tool call after about 60 s; the reply also needs time to travel. */
|
|
8
|
+
export const MAX_WAIT_SECONDS = 45;
|
|
9
|
+
const REPLY_MARGIN_MS = 2_000;
|
|
10
|
+
const PROGRESS_EVERY_SECONDS = 10;
|
|
11
|
+
export function registerGetTask(server, config) {
|
|
12
|
+
server.registerTool('get_task', {
|
|
13
|
+
title: 'Get task status and results',
|
|
14
|
+
description: [
|
|
15
|
+
'Check one generation task and, while it is still running, wait up to wait_seconds (max 45) for it to finish. Free.',
|
|
16
|
+
'Returns the status, progress, result links (they expire after 24 hours, so give them to the user right away), the final charge, or the error with a next step.',
|
|
17
|
+
'If the task is still running when this returns, call get_task again.',
|
|
18
|
+
'Never call generate_image, generate_video or generate_audio again to check progress: that creates and charges a new task.',
|
|
19
|
+
RESULT_DELIVERY_GUIDANCE,
|
|
20
|
+
].join(' '),
|
|
21
|
+
inputSchema: {
|
|
22
|
+
task_id: z.string().regex(TASK_ID).describe('task_id returned by generate_image, generate_video or generate_audio'),
|
|
23
|
+
wait_seconds: z.number().int().min(0).max(MAX_WAIT_SECONDS).default(30)
|
|
24
|
+
.describe('How long this call may wait for the task to finish (0–45 s, default 30). Use 0 for a quick check.'),
|
|
25
|
+
},
|
|
26
|
+
annotations: { title: 'Get task status and results', ...READ_ONLY },
|
|
27
|
+
}, async ({ task_id, wait_seconds }, extra) => {
|
|
28
|
+
const started = Date.now();
|
|
29
|
+
const waitSeconds = Math.min(wait_seconds ?? 30, MAX_WAIT_SECONDS);
|
|
30
|
+
const report = progressReporter(extra, waitSeconds);
|
|
31
|
+
let lastReport = -PROGRESS_EVERY_SECONDS;
|
|
32
|
+
try {
|
|
33
|
+
const task = await waitForTask(config, task_id, {
|
|
34
|
+
deadline: started + waitSeconds * 1000 - REPLY_MARGIN_MS,
|
|
35
|
+
tool: 'get_task',
|
|
36
|
+
signal: extra.signal,
|
|
37
|
+
onPoll: async (current) => {
|
|
38
|
+
const elapsed = (Date.now() - started) / 1000;
|
|
39
|
+
if (elapsed - lastReport < PROGRESS_EVERY_SECONDS)
|
|
40
|
+
return;
|
|
41
|
+
lastReport = elapsed;
|
|
42
|
+
await report(elapsed, `${current.status}, ${current.progress ?? 0}%`);
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
const view = describeTask(task);
|
|
46
|
+
if (!TERMINAL_STATUSES.has(task.status) && waitSeconds > 0) {
|
|
47
|
+
const waited = Math.round((Date.now() - started) / 1000);
|
|
48
|
+
view.lines.splice(1, 0, `Still running after waiting ${waited} s.`);
|
|
49
|
+
view.structured.waited_seconds = waited;
|
|
50
|
+
}
|
|
51
|
+
return ok(view.lines.join('\n'), view.structured, view.resources);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
return errorResult(error);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
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 { listTasks, queryTasks } from '../services/api-client.js';
|
|
5
|
+
import { READ_ONLY, errorResult, failure, money, ok, usdOf } from './shared.js';
|
|
6
|
+
import { TASK_ID } from './get-task.js';
|
|
7
|
+
import { RESULT_DELIVERY_GUIDANCE, RESULT_DELIVERY_INSTRUCTIONS, RESULT_LINK_HOURS, resultDeliveryMarkdown, resultLinks, resultResources, taskOutputs } from './task-format.js';
|
|
8
|
+
const MAX_IDS = 50;
|
|
9
|
+
/** ISO 8601, unix seconds, or relative such as 30m, 2h, 1d. */
|
|
10
|
+
export function parseSince(value, now = Date.now()) {
|
|
11
|
+
const trimmed = value.trim();
|
|
12
|
+
const relative = /^(\d+)\s*(m|min|mins|minutes?|h|hours?|d|days?)$/i.exec(trimmed);
|
|
13
|
+
if (relative) {
|
|
14
|
+
const amount = Number(relative[1]);
|
|
15
|
+
const unit = relative[2][0].toLowerCase();
|
|
16
|
+
const factor = unit === 'm' ? 60_000 : unit === 'h' ? 3_600_000 : 86_400_000;
|
|
17
|
+
const result = now - amount * factor;
|
|
18
|
+
return Number.isSafeInteger(result) && result >= 0 ? result : undefined;
|
|
19
|
+
}
|
|
20
|
+
if (/^\d{9,11}$/.test(trimmed))
|
|
21
|
+
return Number(trimmed) * 1000;
|
|
22
|
+
const parsed = Date.parse(trimmed);
|
|
23
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
24
|
+
}
|
|
25
|
+
function rowFromTask(task) {
|
|
26
|
+
const row = { task_id: task.id, status: task.status, model: task.model, type: task.type, progress: task.progress };
|
|
27
|
+
if (task.created)
|
|
28
|
+
row.created_at = new Date(task.created * 1000).toISOString();
|
|
29
|
+
const links = resultLinks(task);
|
|
30
|
+
if (links.length > 0)
|
|
31
|
+
row.results = links;
|
|
32
|
+
const outputs = taskOutputs(task);
|
|
33
|
+
if (outputs.length)
|
|
34
|
+
row.outputs = outputs;
|
|
35
|
+
if (task.status === 'completed' && links.length > 0)
|
|
36
|
+
row.delivery_markdown = resultDeliveryMarkdown(task.id, links);
|
|
37
|
+
const used = task.usage?.credits_used ?? task.usage?.cost?.credits;
|
|
38
|
+
if (task.status === 'completed' && typeof used === 'number') {
|
|
39
|
+
row.charged_credits = used;
|
|
40
|
+
row.charged_usd = task.usage?.cost?.usd ?? usdOf(used);
|
|
41
|
+
}
|
|
42
|
+
if (task.error?.code)
|
|
43
|
+
row.error_code = task.error.code;
|
|
44
|
+
return row;
|
|
45
|
+
}
|
|
46
|
+
function rowLine(row) {
|
|
47
|
+
const parts = [`- ${row.task_id}`, row.status === 'completed' || row.status === 'failed' ? row.status : `${row.status} ${row.progress ?? 0}%`, row.model];
|
|
48
|
+
if (row.created_at)
|
|
49
|
+
parts.push(row.created_at);
|
|
50
|
+
if (row.charged_credits !== undefined)
|
|
51
|
+
parts.push(`charged ${money(row.charged_credits)}`);
|
|
52
|
+
if (row.error_code)
|
|
53
|
+
parts.push(`error ${row.error_code}`);
|
|
54
|
+
const lines = [parts.join(' · ')];
|
|
55
|
+
for (const link of row.results ?? [])
|
|
56
|
+
lines.push(` ${link.kind}: ${link.url}`);
|
|
57
|
+
return lines.join('\n');
|
|
58
|
+
}
|
|
59
|
+
export function registerListTasks(server, config) {
|
|
60
|
+
server.registerTool('list_tasks', {
|
|
61
|
+
title: 'List generation tasks',
|
|
62
|
+
description: [
|
|
63
|
+
'Read several tasks at once by task_ids (up to 50, with result links), or page through tasks by status, type and model. Free.',
|
|
64
|
+
'since and until filter only the selected page by creation time. total is the server count before these time filters; an empty page does not prove a submission was absent.',
|
|
65
|
+
'Use it to recover tasks after a lost connection or a timed-out submit before submitting anything again.',
|
|
66
|
+
'Recent tasks cover the whole EvoLink account, newest first.',
|
|
67
|
+
RESULT_DELIVERY_GUIDANCE,
|
|
68
|
+
].join(' '),
|
|
69
|
+
inputSchema: {
|
|
70
|
+
task_ids: z.array(z.string().regex(TASK_ID)).min(1).max(MAX_IDS).optional()
|
|
71
|
+
.describe('Task IDs to read in one call (max 50).'),
|
|
72
|
+
status: z.enum(['processing', 'completed', 'failed', 'cancelled']).optional()
|
|
73
|
+
.describe('Without task_ids: only tasks in this state ("processing" includes queued tasks).'),
|
|
74
|
+
type: z.enum(['image', 'video', 'audio']).optional()
|
|
75
|
+
.describe('Without task_ids: only this kind of task.'),
|
|
76
|
+
model: z.string().min(1).max(128).optional().describe('Without task_ids: exact model ID.'),
|
|
77
|
+
page: z.number().int().min(1).max(100_000).optional().describe('Without task_ids: page number (default 1).'),
|
|
78
|
+
since: z.string().min(1).max(40).optional()
|
|
79
|
+
.describe('Without task_ids: only tasks created after this time, as ISO 8601 (2026-10-05T08:00:00Z) or relative (30m, 2h, 1d).'),
|
|
80
|
+
until: z.string().min(1).max(40).optional().describe('Without task_ids: creation time upper bound, inclusive. Same formats as since.'),
|
|
81
|
+
limit: z.number().int().min(1).max(MAX_IDS).default(20)
|
|
82
|
+
.describe('Without task_ids: how many recent tasks to return (1–50, default 20).'),
|
|
83
|
+
},
|
|
84
|
+
annotations: { title: 'List generation tasks', ...READ_ONLY },
|
|
85
|
+
}, async ({ task_ids, status, type, model, page: pageNumber, since, until, limit }) => {
|
|
86
|
+
try {
|
|
87
|
+
if (task_ids && [status, type, model, pageNumber, since, until].some(value => value !== undefined)) {
|
|
88
|
+
return failure('Choose task_ids or list filters, not both.', { error: { category: 'invalid_request' } });
|
|
89
|
+
}
|
|
90
|
+
if (task_ids && task_ids.length > 0) {
|
|
91
|
+
const unique = [...new Set(task_ids)];
|
|
92
|
+
const tasks = await queryTasks(config, unique);
|
|
93
|
+
const rows = tasks.map(rowFromTask);
|
|
94
|
+
const found = new Set(rows.map(row => row.task_id));
|
|
95
|
+
const missing = unique.filter(id => !found.has(id));
|
|
96
|
+
const lines = [`${rows.length} of ${unique.length} tasks found.`, ...rows.map(rowLine)];
|
|
97
|
+
if (missing.length > 0)
|
|
98
|
+
lines.push(`Not found (wrong ID, expired, or another account): ${missing.join(', ')}`);
|
|
99
|
+
if (rows.some(row => row.results))
|
|
100
|
+
lines.push(`Result links expire after ${RESULT_LINK_HOURS} hours.`);
|
|
101
|
+
if (rows.some(row => row.results))
|
|
102
|
+
lines.push(`Next step: ${RESULT_DELIVERY_INSTRUCTIONS}`);
|
|
103
|
+
return ok(lines.join('\n'), { tasks: rows, missing }, rows.flatMap(row => resultResources(row.task_id, row.results ?? [])));
|
|
104
|
+
}
|
|
105
|
+
const now = Date.now();
|
|
106
|
+
let sinceMs;
|
|
107
|
+
if (since) {
|
|
108
|
+
sinceMs = parseSince(since, now);
|
|
109
|
+
if (sinceMs === undefined) {
|
|
110
|
+
return failure(`since "${since}" is not a time. Use ISO 8601 (2026-10-05T08:00:00Z) or a relative value such as 30m, 2h or 1d.`, {
|
|
111
|
+
error: { category: 'invalid_request', param: 'since' },
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const untilMs = until === undefined ? undefined : parseSince(until, now);
|
|
116
|
+
if ((until !== undefined && untilMs === undefined) || (sinceMs !== undefined && untilMs !== undefined && sinceMs > untilMs)) {
|
|
117
|
+
return failure('until must be a valid time at or after since.', { error: { category: 'invalid_request', param: 'until' } });
|
|
118
|
+
}
|
|
119
|
+
const pageSize = limit ?? 20;
|
|
120
|
+
const page = await listTasks(config, { status, type, model, page: pageNumber, pageSize });
|
|
121
|
+
let items = page.data;
|
|
122
|
+
if (sinceMs !== undefined)
|
|
123
|
+
items = items.filter(item => item.created_at * 1000 >= sinceMs);
|
|
124
|
+
if (untilMs !== undefined)
|
|
125
|
+
items = items.filter(item => item.created_at * 1000 <= untilMs);
|
|
126
|
+
// The list endpoint omits result links; read finished tasks in one batch to include them.
|
|
127
|
+
const finished = items.filter(item => item.status === 'completed' && item.has_results).map(item => item.id).slice(0, MAX_IDS);
|
|
128
|
+
const details = new Map();
|
|
129
|
+
if (finished.length > 0) {
|
|
130
|
+
for (const task of await queryTasks(config, finished))
|
|
131
|
+
details.set(task.id, task);
|
|
132
|
+
}
|
|
133
|
+
const rows = items.map(item => {
|
|
134
|
+
const detailed = details.get(item.id);
|
|
135
|
+
if (detailed)
|
|
136
|
+
return rowFromTask(detailed);
|
|
137
|
+
const row = {
|
|
138
|
+
task_id: item.id,
|
|
139
|
+
status: item.status,
|
|
140
|
+
model: item.model,
|
|
141
|
+
type: item.type,
|
|
142
|
+
progress: item.progress,
|
|
143
|
+
created_at: new Date(item.created_at * 1000).toISOString(),
|
|
144
|
+
};
|
|
145
|
+
if (typeof item.credits_used === 'number' && item.status === 'completed') {
|
|
146
|
+
row.charged_credits = item.credits_used;
|
|
147
|
+
row.charged_usd = usdOf(item.credits_used);
|
|
148
|
+
}
|
|
149
|
+
if (item.has_error)
|
|
150
|
+
row.error_code = 'failed';
|
|
151
|
+
return row;
|
|
152
|
+
});
|
|
153
|
+
const filters = [status && `status ${status}`, type && `type ${type}`, model && `model ${model}`, since && `since ${since}`, until && `until ${until}`].filter(Boolean).join(', ');
|
|
154
|
+
const lines = [`${rows.length} recent task${rows.length === 1 ? '' : 's'} on this account${filters ? ` (${filters})` : ''}, newest first:`];
|
|
155
|
+
lines.push(...(rows.length > 0 ? rows.map(rowLine) : ['(none)']));
|
|
156
|
+
const nextPage = page.page * page.page_size < page.total ? page.page + 1 : null;
|
|
157
|
+
lines.push(`Page ${page.page}; ${page.total} tasks before page-local time filtering.${nextPage ? ` Continue with page ${nextPage}.` : ''}`);
|
|
158
|
+
if (rows.some(row => row.results))
|
|
159
|
+
lines.push(`Result links expire after ${RESULT_LINK_HOURS} hours.`);
|
|
160
|
+
if (rows.some(row => row.results))
|
|
161
|
+
lines.push(`Next step: ${RESULT_DELIVERY_INSTRUCTIONS}`);
|
|
162
|
+
return ok(lines.join('\n'), { tasks: rows, total: page.total, page: page.page, page_size: page.page_size,
|
|
163
|
+
next_page: nextPage, time_filter_scope: 'selected_page', total_scope: 'server_filters_before_time_filter',
|
|
164
|
+
}, rows.flatMap(row => resultResources(row.task_id, row.results ?? [])));
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
return errorResult(error);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
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 { loadCatalog } from '../services/model-catalog.js';
|
|
5
|
+
import { formatPrice, startingPrice } from '../services/pricing-client.js';
|
|
6
|
+
import { trackedLink } from '../services/utm.js';
|
|
7
|
+
import { MODEL_SELECTION_GUIDANCE, modelPreference } from '../services/model-recommendations.js';
|
|
8
|
+
import { referenceInputs } from '../services/model-capabilities.js';
|
|
9
|
+
import { READ_ONLY, errorResult, ok } from './shared.js';
|
|
10
|
+
export function modelTitle(entry) {
|
|
11
|
+
const title = entry.spec?.title?.replace(/\s+(interface|api)$/i, '').trim();
|
|
12
|
+
return title || entry.title || entry.priced?.description?.slice(0, 120) || undefined;
|
|
13
|
+
}
|
|
14
|
+
/** Every term must appear somewhere; matches in the model ID count most. */
|
|
15
|
+
export function scoreModel(entry, terms) {
|
|
16
|
+
if (terms.length === 0)
|
|
17
|
+
return 0;
|
|
18
|
+
const id = entry.id.toLowerCase();
|
|
19
|
+
const normalizedId = [id, ...(entry.aliases ?? [])].map(value => value.toLowerCase().replace(/[.\-_\s]/g, ''));
|
|
20
|
+
const haystack = [id, modelTitle(entry), entry.priced?.description, entry.priced?.vendor, entry.kind]
|
|
21
|
+
.filter(Boolean)
|
|
22
|
+
.join(' ')
|
|
23
|
+
.toLowerCase();
|
|
24
|
+
let total = 0;
|
|
25
|
+
for (const term of terms) {
|
|
26
|
+
const normalized = term.replace(/[.\-_]/g, '');
|
|
27
|
+
if (id === term)
|
|
28
|
+
total += 10;
|
|
29
|
+
else if (id.startsWith(term))
|
|
30
|
+
total += 6;
|
|
31
|
+
else if (id.includes(term))
|
|
32
|
+
total += 4;
|
|
33
|
+
else if (normalized && normalizedId.some(value => value.includes(normalized)))
|
|
34
|
+
total += 3;
|
|
35
|
+
else if (haystack.includes(term))
|
|
36
|
+
total += 1;
|
|
37
|
+
else
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
return total;
|
|
41
|
+
}
|
|
42
|
+
export function registerSearchModels(server, config) {
|
|
43
|
+
server.registerTool('search_models', {
|
|
44
|
+
title: 'Search models',
|
|
45
|
+
description: [
|
|
46
|
+
'Find EvoLink image, video and audio models by type and keywords. Free.',
|
|
47
|
+
'Returns model IDs with a starting price; call get_model for a model\'s parameters and full pricing before generating.',
|
|
48
|
+
'Prices are in USD (68 credits ≈ $1).',
|
|
49
|
+
MODEL_SELECTION_GUIDANCE,
|
|
50
|
+
].join(' '),
|
|
51
|
+
inputSchema: {
|
|
52
|
+
type: z.enum(['image', 'video', 'audio', 'all']).default('all').describe('Kind of output to look for.'),
|
|
53
|
+
query: z.string().max(100).optional().describe('Keywords, e.g. "seedance", "image-to-video", "kling", "music".'),
|
|
54
|
+
limit: z.number().int().min(1).max(50).default(20).describe('Maximum number of models to return (1–50, default 20).'),
|
|
55
|
+
page: z.number().int().min(1).max(100_000).default(1).describe('Page number for this search (default 1); live availability may change between pages.'),
|
|
56
|
+
},
|
|
57
|
+
annotations: { title: 'Search models', ...READ_ONLY },
|
|
58
|
+
}, async ({ type, query, limit, page }) => {
|
|
59
|
+
try {
|
|
60
|
+
const catalog = await loadCatalog(config);
|
|
61
|
+
const terms = (query ?? '').toLowerCase().split(/[\s,]+/).filter(Boolean);
|
|
62
|
+
const matches = catalog.entries
|
|
63
|
+
.filter(entry => type === 'all' || entry.kind === type)
|
|
64
|
+
.map(entry => ({ entry, score: scoreModel(entry, terms), start: entry.priced ? startingPrice(entry.priced) : undefined, preference: modelPreference(entry) }))
|
|
65
|
+
.filter((item) => item.score !== undefined)
|
|
66
|
+
.sort((a, b) => b.score - a.score || Number(!!b.start) - Number(!!a.start)
|
|
67
|
+
|| (a.preference?.priority ?? Infinity) - (b.preference?.priority ?? Infinity)
|
|
68
|
+
|| a.entry.id.localeCompare(b.entry.id));
|
|
69
|
+
const shown = matches.slice((page - 1) * limit, page * limit);
|
|
70
|
+
const models = shown.map(({ entry, start, preference }) => ({
|
|
71
|
+
id: entry.id,
|
|
72
|
+
aliases: entry.aliases,
|
|
73
|
+
type: entry.kind,
|
|
74
|
+
title: modelTitle(entry),
|
|
75
|
+
from_usd: start?.min_usd,
|
|
76
|
+
from_unit: start?.unit,
|
|
77
|
+
parameters_documented: !!entry.spec,
|
|
78
|
+
reference_inputs: referenceInputs(entry.spec),
|
|
79
|
+
docs: entry.spec ? trackedLink(entry.spec.docs, 'model_docs') : undefined,
|
|
80
|
+
...(preference ? { recommendation: { basis: preference.basis, family: preference.family, use_case: preference.use_case } } : {}),
|
|
81
|
+
}));
|
|
82
|
+
const lines = [
|
|
83
|
+
`${matches.length} model${matches.length === 1 ? '' : 's'} match${terms.length ? ` "${query}"` : ''}${type !== 'all' ? ` (${type})` : ''}${matches.length > shown.length ? `; showing ${shown.length}` : ''}:`,
|
|
84
|
+
...shown.map(({ entry, start, preference }) => {
|
|
85
|
+
const parts = [`- ${entry.id} [${entry.kind}]`];
|
|
86
|
+
const title = modelTitle(entry);
|
|
87
|
+
if (title)
|
|
88
|
+
parts.push(title);
|
|
89
|
+
parts.push(start ? `from ${formatPrice(start)}` : 'pricing data unavailable in this catalog');
|
|
90
|
+
if (!entry.spec)
|
|
91
|
+
parts.push('parameters not documented');
|
|
92
|
+
if (preference)
|
|
93
|
+
parts.push(`platform preference for ${preference.use_case}`);
|
|
94
|
+
return parts.join(' · ');
|
|
95
|
+
}),
|
|
96
|
+
];
|
|
97
|
+
if (matches.length === 0)
|
|
98
|
+
lines.push('No model matched. Try fewer or broader keywords, or type "all".');
|
|
99
|
+
else
|
|
100
|
+
lines.push('', 'Next: compare suitable models with get_model. Keyword relevance comes first; platform preferences break ties after price availability. Search order is not a quality or popularity ranking, and a unit starting price is not the task total.');
|
|
101
|
+
if (catalog.pricingWarning)
|
|
102
|
+
lines.push(`Note: ${catalog.pricingWarning}`);
|
|
103
|
+
return ok(lines.join('\n'), {
|
|
104
|
+
models,
|
|
105
|
+
total_matches: matches.length,
|
|
106
|
+
page, page_size: limit, next_page: page * limit < matches.length ? page + 1 : null,
|
|
107
|
+
availability_source: 'live_catalog_and_health', ordering: 'keyword_relevance_then_price_availability_then_platform_preference_then_id',
|
|
108
|
+
...(catalog.pricingWarning ? { pricing_warning: catalog.pricingWarning } : {}),
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
return errorResult(error);
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
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 { processCredentialsAllowed } from '../request-context.js';
|
|
4
|
+
import { ApiHttpError } from '../services/api-client.js';
|
|
5
|
+
import { CREDITS_PER_USD, formatCredits, formatUsd } from '../services/error-handler.js';
|
|
6
|
+
import { API_KEYS_URL, PaidRequestOutcomeUnknownError, RequestTimeoutError } from '../services/http-policy.js';
|
|
7
|
+
import { trackedLink } from '../services/utm.js';
|
|
8
|
+
/** Free lookups: clients can run them without asking. */
|
|
9
|
+
export const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
10
|
+
/** Spends the user's balance and cannot be undone: clients ask before running it. */
|
|
11
|
+
export const PAID = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false };
|
|
12
|
+
/** Changes stored state without spending money (uploads). */
|
|
13
|
+
export const WRITES = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
|
|
14
|
+
/** The media_seconds argument of estimate_cost and the generate tools. */
|
|
15
|
+
export const MEDIA_SECONDS_MAX = 3_600;
|
|
16
|
+
export const MEDIA_SECONDS_DESCRIPTION = 'Only for models billed per second that have no duration parameter (get_model explains which length is billed): usually the input video or audio length; for generated audio with unknown duration, only an expected output length for an illustrative estimate. It is not sent to the model, and EvoLink charges by the measured duration. It cannot establish max_cost_usd for unknown output duration or for per-second video requests with video_urls, video_url or source_task_id, whose billing is not fully covered by published prices.';
|
|
17
|
+
/** Text and structured content carry the same facts: some clients show the model only one of them. */
|
|
18
|
+
export function ok(text, structured, resources = []) {
|
|
19
|
+
return { content: [{ type: 'text', text }, ...resources], structuredContent: { ok: true, ...structured } };
|
|
20
|
+
}
|
|
21
|
+
export function failure(text, structured) {
|
|
22
|
+
return { content: [{ type: 'text', text }], structuredContent: { ok: false, ...structured }, isError: true };
|
|
23
|
+
}
|
|
24
|
+
export function money(credits) {
|
|
25
|
+
if (typeof credits !== 'number' || !Number.isFinite(credits))
|
|
26
|
+
return undefined;
|
|
27
|
+
return `${formatCredits(credits)} credits (≈$${formatUsd(credits / CREDITS_PER_USD)})`;
|
|
28
|
+
}
|
|
29
|
+
/** The calling key's daily limit, when the gateway reports one (none means no daily limit is set). */
|
|
30
|
+
export function dailyLimitOf(token) {
|
|
31
|
+
const limit = token.daily_limit_credits;
|
|
32
|
+
if (typeof limit !== 'number' || !Number.isFinite(limit) || limit <= 0)
|
|
33
|
+
return undefined;
|
|
34
|
+
const raw = token.daily_used_credits;
|
|
35
|
+
const used = typeof raw === 'number' && Number.isFinite(raw) ? Math.max(0, raw) : 0;
|
|
36
|
+
const zone = typeof token.reset_timezone === 'string' && token.reset_timezone.trim() ? token.reset_timezone.trim() : undefined;
|
|
37
|
+
return { used, limit, left: Math.max(0, limit - used), zone };
|
|
38
|
+
}
|
|
39
|
+
export function usdOf(credits) {
|
|
40
|
+
if (typeof credits !== 'number' || !Number.isFinite(credits))
|
|
41
|
+
return undefined;
|
|
42
|
+
return Number((credits / CREDITS_PER_USD).toFixed(6));
|
|
43
|
+
}
|
|
44
|
+
function infoFor(error) {
|
|
45
|
+
if (error instanceof ApiHttpError && error.info)
|
|
46
|
+
return error.info;
|
|
47
|
+
if (error instanceof ApiHttpError) {
|
|
48
|
+
return { status: error.status, category: 'server_error', message: error.message, next_step: 'Retry in a minute.', retryable: true, request_id: error.requestId };
|
|
49
|
+
}
|
|
50
|
+
if (error instanceof PaidRequestOutcomeUnknownError) {
|
|
51
|
+
return {
|
|
52
|
+
status: 0,
|
|
53
|
+
category: 'outcome_unknown',
|
|
54
|
+
message: 'The submission timed out or the connection dropped, so it is unknown whether a task was created.',
|
|
55
|
+
next_step: 'Do not submit again with a new client_request_id. Look for the task with list_tasks (status processing), or retry with the same client_request_id.',
|
|
56
|
+
retryable: true,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
if (error instanceof RequestTimeoutError || error instanceof TypeError) {
|
|
60
|
+
return { status: 0, category: 'server_error', message: 'EvoLink did not respond in time.', next_step: 'Retry in a minute.', retryable: true };
|
|
61
|
+
}
|
|
62
|
+
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
63
|
+
// Credential problems surface as plain errors from getApiKey(): no key in this scope, or a
|
|
64
|
+
// signed-in connection that cannot use the hosted service channel.
|
|
65
|
+
return {
|
|
66
|
+
status: 0,
|
|
67
|
+
category: 'unauthorized',
|
|
68
|
+
message,
|
|
69
|
+
next_step: processCredentialsAllowed()
|
|
70
|
+
? `Set EVOLINK_API_KEY (create a key at ${trackedLink(API_KEYS_URL, 'api_keys')}), or configure EVOLINK_CREDENTIAL_HELPER with an API-key helper. The browser CLI uses \`evolink auth login\` independently.`
|
|
71
|
+
: 'Ask the user to reconnect EvoLink in this client. If it keeps failing, retry in a few minutes.',
|
|
72
|
+
retryable: false,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/** Converts a thrown error into a tool error with a category and a concrete next step. */
|
|
76
|
+
export function errorResult(error, context = {}) {
|
|
77
|
+
const info = infoFor(error);
|
|
78
|
+
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
|
+
const lines = info.headline ? [info.headline] : [`Error (${label}): ${info.message}`];
|
|
81
|
+
lines.push(`Next step: ${info.next_step}`);
|
|
82
|
+
let charged;
|
|
83
|
+
if (context.paid) {
|
|
84
|
+
if (info.category === 'outcome_unknown' || info.category === 'server_error') {
|
|
85
|
+
charged = 'unknown';
|
|
86
|
+
lines.push(context.clientRequestId
|
|
87
|
+
? `It is unclear whether a task was created. To retry this exact request safely, pass client_request_id "${context.clientRequestId}".`
|
|
88
|
+
: 'It is unclear whether a task was created; check list_tasks before submitting again.');
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
charged = 'no';
|
|
92
|
+
lines.push('Nothing was submitted or charged.');
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// No HTTP status: the request timed out or the connection dropped, so the upload's outcome is unknown.
|
|
96
|
+
if (context.upload && info.category === 'server_error' && !info.status) {
|
|
97
|
+
lines.push('The upload may not have finished. Calling upload_file again is safe.');
|
|
98
|
+
}
|
|
99
|
+
if (info.headline)
|
|
100
|
+
lines.push(`Error: ${label}`);
|
|
101
|
+
if (info.request_id)
|
|
102
|
+
lines.push(`Request ID: ${info.request_id}`);
|
|
103
|
+
return failure(lines.join('\n'), {
|
|
104
|
+
error: info,
|
|
105
|
+
...(charged ? { charged } : {}),
|
|
106
|
+
...(context.clientRequestId && charged === 'unknown' ? { client_request_id: context.clientRequestId } : {}),
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
/** Sends a progress notification when the client asked for them; failures are ignored. */
|
|
110
|
+
export function progressReporter(extra, totalSeconds) {
|
|
111
|
+
const token = extra?._meta?.progressToken;
|
|
112
|
+
let last = -1;
|
|
113
|
+
return async (elapsedSeconds, message) => {
|
|
114
|
+
if (token === undefined || !extra)
|
|
115
|
+
return;
|
|
116
|
+
const progress = Math.max(last + 1, Math.round(elapsedSeconds));
|
|
117
|
+
last = progress;
|
|
118
|
+
await extra.sendNotification({
|
|
119
|
+
method: 'notifications/progress',
|
|
120
|
+
params: { progressToken: token, progress, total: Math.max(totalSeconds, progress), message },
|
|
121
|
+
}).catch(() => undefined);
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
export function sleep(ms, signal) {
|
|
125
|
+
return new Promise(resolve => {
|
|
126
|
+
if (signal?.aborted) {
|
|
127
|
+
resolve();
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
const timer = setTimeout(done, ms);
|
|
131
|
+
function done() {
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
signal?.removeEventListener('abort', done);
|
|
134
|
+
resolve();
|
|
135
|
+
}
|
|
136
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
137
|
+
});
|
|
138
|
+
}
|