@evolinkai/cli 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -6
- package/package.json +27 -8
- package/skills/evolink-cli/SKILL.md +5 -5
- package/skills/evolink-cli/references/capabilities.md +1 -1
- package/src/api.mjs +59 -0
- package/src/auth.mjs +6 -7
- package/src/cli.mjs +34 -30
- package/src/doctor.mjs +9 -6
- package/src/errors.mjs +21 -13
- package/src/files.mjs +61 -6
- package/src/help.mjs +8 -8
- package/src/media.mjs +11 -9
- package/src/network.mjs +12 -1
- package/src/oauth.mjs +90 -0
- package/src/platform/LICENSE +178 -0
- package/src/platform/NOTICE +6 -0
- package/src/platform/core/src/config.js +95 -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 +56 -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 +232 -0
- package/src/platform/core/src/services/catalog-client.js +45 -0
- package/src/platform/core/src/services/error-handler.js +452 -0
- package/src/platform/core/src/services/file-client.js +165 -0
- package/src/platform/core/src/services/http-policy.js +186 -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/public-error.js +63 -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 +237 -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 +158 -0
- package/src/platform/core/src/tools/task-billing.js +31 -0
- package/src/platform/core/src/tools/task-format.js +264 -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 +84 -0
- package/src/setup.mjs +9 -5
- package/src/mcp.mjs +0 -43
|
@@ -0,0 +1,146 @@
|
|
|
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 { modelParamsMeta } from '../data/model-params.js';
|
|
5
|
+
import { resolveModel, suggestModels } from '../services/model-catalog.js';
|
|
6
|
+
import { billedByMediaLength, formatPrice } from '../services/pricing-client.js';
|
|
7
|
+
import { formatUsd } from '../services/error-handler.js';
|
|
8
|
+
import { trackedLink } from '../services/utm.js';
|
|
9
|
+
import { READ_ONLY, errorResult, failure, ok } from './shared.js';
|
|
10
|
+
import { modelTitle } from './search-models.js';
|
|
11
|
+
import { referenceInputs } from '../services/model-capabilities.js';
|
|
12
|
+
function value(v) {
|
|
13
|
+
return JSON.stringify(v);
|
|
14
|
+
}
|
|
15
|
+
export function describeParam(name, spec, indent = '') {
|
|
16
|
+
const facts = [spec.type, spec.required ? 'required' : undefined].filter(Boolean);
|
|
17
|
+
const details = [];
|
|
18
|
+
if (spec.enum?.length)
|
|
19
|
+
details.push(`one of ${spec.enum.map(value).join(', ')}`);
|
|
20
|
+
if (spec.default !== undefined)
|
|
21
|
+
details.push(`default ${value(spec.default)}`);
|
|
22
|
+
if (spec.minimum !== undefined || spec.maximum !== undefined)
|
|
23
|
+
details.push(`range ${spec.minimum ?? '…'}–${spec.maximum ?? '…'}`);
|
|
24
|
+
if (spec.minItems !== undefined || spec.maxItems !== undefined)
|
|
25
|
+
details.push(`${spec.minItems ?? 0}–${spec.maxItems ?? '…'} items`);
|
|
26
|
+
if (spec.maxLength !== undefined)
|
|
27
|
+
details.push(`up to ${spec.maxLength} characters`);
|
|
28
|
+
if (spec.items?.enum?.length)
|
|
29
|
+
details.push(`each one of ${spec.items.enum.map(value).join(', ')}`);
|
|
30
|
+
if (spec.anyOf?.length)
|
|
31
|
+
details.push(`one of ${spec.anyOf.map(option => option.enum ? option.enum.join(', ') : `${option.minimum ?? '…'}–${option.maximum ?? '…'}`).join(' or ')}`);
|
|
32
|
+
const head = `${indent}- ${name}${facts.length ? ` (${facts.join(', ')})` : ''}${details.length ? `: ${details.join('; ')}` : ''}`;
|
|
33
|
+
const lines = [spec.description ? `${head} — ${spec.description}` : head];
|
|
34
|
+
for (const [child, childSpec] of Object.entries(spec.properties ?? spec.items?.properties ?? {})) {
|
|
35
|
+
lines.push(...describeParam(child, childSpec, `${indent} `));
|
|
36
|
+
}
|
|
37
|
+
return lines;
|
|
38
|
+
}
|
|
39
|
+
function priceLine(price) {
|
|
40
|
+
const minimum = price.min_charge_usd !== undefined ? ` (minimum $${formatUsd(price.min_charge_usd)} per task)` : '';
|
|
41
|
+
const factors = price.multipliers ? ` (resolution factors ${Object.entries(price.multipliers).map(([k, v]) => `${k} ×${v}`).join(', ')})` : '';
|
|
42
|
+
return `${price.name}: ${formatPrice(price)}${minimum}${factors}`;
|
|
43
|
+
}
|
|
44
|
+
export function registerGetModel(server, config) {
|
|
45
|
+
server.registerTool('get_model', {
|
|
46
|
+
title: 'Get model parameters and pricing',
|
|
47
|
+
description: [
|
|
48
|
+
'Show what one model accepts and what it costs: every input parameter (required, allowed values, ranges, defaults), the published prices and an example input. Free.',
|
|
49
|
+
'Read this before calling generate_image, generate_video or generate_audio, and quote the price to the user.',
|
|
50
|
+
].join(' '),
|
|
51
|
+
inputSchema: {
|
|
52
|
+
model: z.string().min(1).max(128).describe('Model ID from search_models, e.g. "seedance-2.0-text-to-video".'),
|
|
53
|
+
},
|
|
54
|
+
annotations: { title: 'Get model parameters and pricing', ...READ_ONLY },
|
|
55
|
+
}, async ({ model }) => {
|
|
56
|
+
try {
|
|
57
|
+
const { catalog, entry } = await resolveModel(model, config);
|
|
58
|
+
if (!entry) {
|
|
59
|
+
const suggestions = suggestModels(catalog, model);
|
|
60
|
+
return failure(`Unknown model "${model}".${suggestions.length ? ` Did you mean: ${suggestions.join(', ')}?` : ''} Use search_models to find model IDs.`, { error: { category: 'not_found', param: 'model' }, suggestions });
|
|
61
|
+
}
|
|
62
|
+
const { spec, priced } = entry;
|
|
63
|
+
const title = modelTitle(entry);
|
|
64
|
+
const lines = [`${entry.id} (${entry.kind})${title ? ` — ${title}` : ''}`, `Generate with: generate_${entry.kind}`];
|
|
65
|
+
const structured = {
|
|
66
|
+
model: entry.id,
|
|
67
|
+
type: entry.kind,
|
|
68
|
+
tool: `generate_${entry.kind}`,
|
|
69
|
+
};
|
|
70
|
+
if (spec) {
|
|
71
|
+
const docs = trackedLink(spec.docs, 'model_docs');
|
|
72
|
+
lines.push(`Docs: ${docs}`, '', 'Input parameters (pass them in input):');
|
|
73
|
+
const names = Object.keys(spec.params).sort((a, b) => Number(!!spec.params[b].required) - Number(!!spec.params[a].required));
|
|
74
|
+
for (const name of names)
|
|
75
|
+
lines.push(...describeParam(name, spec.params[name]));
|
|
76
|
+
if (spec.example)
|
|
77
|
+
lines.push('', `Example input: ${JSON.stringify(spec.example)}`);
|
|
78
|
+
if (spec.constraints?.mutuallyExclusive)
|
|
79
|
+
lines.push(...spec.constraints.mutuallyExclusive.map(group => `Input constraint: ${group.join(' and ')} are mutually exclusive.`));
|
|
80
|
+
const sizeRule = spec.constraints?.imageSize;
|
|
81
|
+
if (sizeRule)
|
|
82
|
+
lines.push(sizeRule.allowPixels
|
|
83
|
+
? `Pixel size constraint: edges ${sizeRule.minEdge}–${sizeRule.maxEdge}, divisible by ${sizeRule.step}; ${sizeRule.minPixels}–${sizeRule.maxPixels} total pixels; aspect ratio at most ${sizeRule.maxRatio}:1.`
|
|
84
|
+
: `Size constraint: only auto or the documented ratios; explicit pixels are not supported. Ratio resolution: ${sizeRule.ratioResolution}.`);
|
|
85
|
+
Object.assign(structured, {
|
|
86
|
+
endpoint: spec.path,
|
|
87
|
+
docs,
|
|
88
|
+
required: spec.required,
|
|
89
|
+
parameters: spec.params,
|
|
90
|
+
constraints: spec.constraints,
|
|
91
|
+
example_input: spec.example,
|
|
92
|
+
parameters_source: modelParamsMeta(),
|
|
93
|
+
input_schema: spec.inputSchema?.schema,
|
|
94
|
+
response_schema: spec.responseSchema?.schema,
|
|
95
|
+
schema_info: {
|
|
96
|
+
dialect: spec.inputSchema?.dialect,
|
|
97
|
+
unresolved_input_refs: spec.inputSchema?.unresolved_refs,
|
|
98
|
+
unresolved_response_refs: spec.responseSchema?.unresolved_refs,
|
|
99
|
+
response_scope: 'generation_submission_response_not_final_task_result',
|
|
100
|
+
omitted_fields: { input: ['model', 'callback_url'], response: ['task_info.can_cancel'] },
|
|
101
|
+
additional_runtime_constraints: spec.constraints,
|
|
102
|
+
source: modelParamsMeta(),
|
|
103
|
+
validation_scope: 'documented_schema_plus_runtime_constraints',
|
|
104
|
+
runtime_constraints_source: 'reviewed_gateway_supplements',
|
|
105
|
+
},
|
|
106
|
+
reference_inputs: referenceInputs(spec),
|
|
107
|
+
});
|
|
108
|
+
lines.push('Schemas are versioned official OpenAPI references. response_schema describes submission, not necessarily the final task output. Apply the additional runtime constraints above.');
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
lines.push('', 'Parameters for this model are not documented here; the gateway checks the input when you submit.');
|
|
112
|
+
}
|
|
113
|
+
lines.push('', 'Pricing (USD; 68 credits ≈ $1):');
|
|
114
|
+
if (priced && priced.prices.length > 0) {
|
|
115
|
+
const groups = [['output', 'Main charge'], ['add_on', 'Extra charges'], ['token', 'Usage-based']];
|
|
116
|
+
for (const [role, label] of groups) {
|
|
117
|
+
const prices = priced.prices.filter(price => price.role === role);
|
|
118
|
+
if (prices.length === 0)
|
|
119
|
+
continue;
|
|
120
|
+
lines.push(`${label}:`);
|
|
121
|
+
for (const price of prices)
|
|
122
|
+
lines.push(`- ${priceLine(price)}`);
|
|
123
|
+
}
|
|
124
|
+
if (billedByMediaLength(priced, spec)) {
|
|
125
|
+
lines.push(spec?.constraints?.outputDuration === 'unknown'
|
|
126
|
+
? 'This model bills the generated audio duration, which is unknown before it runs. There is no input.duration. media_seconds can illustrate the cost of an expected output length, but cannot establish a spending cap.'
|
|
127
|
+
: 'This model has no duration parameter: EvoLink measures the billed seconds when the task runs (usually the length of the input video or audio). For an estimate before generating, pass that length as media_seconds to estimate_cost.');
|
|
128
|
+
structured.billed_by_media_length = true;
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
lines.push('Use estimate_cost with your input for a total before generating.');
|
|
132
|
+
}
|
|
133
|
+
structured.prices = priced.prices;
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
lines.push(catalog.pricingWarning ?? 'Pricing data is unavailable in this catalog.');
|
|
137
|
+
}
|
|
138
|
+
if (catalog.pricingWarning)
|
|
139
|
+
structured.pricing_warning = catalog.pricingWarning;
|
|
140
|
+
return ok(lines.join('\n'), structured);
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
return errorResult(error);
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
}
|
|
@@ -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,158 @@
|
|
|
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 { CredentialError } from '../config.js';
|
|
4
|
+
import { publicIdentifier, publicErrorDetails, publicText } from '../services/public-error.js';
|
|
5
|
+
import { processCredentialsAllowed } from '../request-context.js';
|
|
6
|
+
import { ApiHttpError } from '../services/api-client.js';
|
|
7
|
+
import { CREDITS_PER_USD, formatCredits, formatUsd } from '../services/error-handler.js';
|
|
8
|
+
import { API_KEYS_URL, PaidRequestOutcomeUnknownError, RequestTimeoutError, SubmissionNotStartedError } from '../services/http-policy.js';
|
|
9
|
+
import { trackedLink } from '../services/utm.js';
|
|
10
|
+
/** Free lookups: clients can run them without asking. */
|
|
11
|
+
export const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
12
|
+
/** Spends the user's balance and cannot be undone: clients ask before running it. */
|
|
13
|
+
export const PAID = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false };
|
|
14
|
+
/** Changes stored state without spending money (uploads). */
|
|
15
|
+
export const WRITES = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
|
|
16
|
+
/** The media_seconds argument of estimate_cost and the generate tools. */
|
|
17
|
+
export const MEDIA_SECONDS_MAX = 3_600;
|
|
18
|
+
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.';
|
|
19
|
+
/** Text and structured content carry the same facts: some clients show the model only one of them. */
|
|
20
|
+
export function ok(text, structured, resources = []) {
|
|
21
|
+
return { content: [{ type: 'text', text }, ...resources], structuredContent: { ok: true, ...structured } };
|
|
22
|
+
}
|
|
23
|
+
export function failure(text, structured) {
|
|
24
|
+
return { content: [{ type: 'text', text: publicText(text) }], structuredContent: { ok: false, ...(structured.charged === 'no' ? { submission_state: 'not_submitted' } : {}), ...publicErrorDetails(structured) }, isError: true };
|
|
25
|
+
}
|
|
26
|
+
export function money(credits) {
|
|
27
|
+
if (typeof credits !== 'number' || !Number.isFinite(credits))
|
|
28
|
+
return undefined;
|
|
29
|
+
return `${formatCredits(credits)} credits (≈$${formatUsd(credits / CREDITS_PER_USD)})`;
|
|
30
|
+
}
|
|
31
|
+
/** The calling key's daily limit, when the gateway reports one (none means no daily limit is set). */
|
|
32
|
+
export function dailyLimitOf(token) {
|
|
33
|
+
const limit = token.daily_limit_credits;
|
|
34
|
+
if (typeof limit !== 'number' || !Number.isFinite(limit) || limit <= 0)
|
|
35
|
+
return undefined;
|
|
36
|
+
const raw = token.daily_used_credits;
|
|
37
|
+
const used = typeof raw === 'number' && Number.isFinite(raw) ? Math.max(0, raw) : 0;
|
|
38
|
+
const zone = typeof token.reset_timezone === 'string' && token.reset_timezone.trim() ? token.reset_timezone.trim() : undefined;
|
|
39
|
+
return { used, limit, left: Math.max(0, limit - used), zone };
|
|
40
|
+
}
|
|
41
|
+
export function usdOf(credits) {
|
|
42
|
+
if (typeof credits !== 'number' || !Number.isFinite(credits))
|
|
43
|
+
return undefined;
|
|
44
|
+
return Number((credits / CREDITS_PER_USD).toFixed(6));
|
|
45
|
+
}
|
|
46
|
+
function infoFor(error) {
|
|
47
|
+
if (error instanceof SubmissionNotStartedError)
|
|
48
|
+
return infoFor(error.cause);
|
|
49
|
+
if (error instanceof ApiHttpError && error.info)
|
|
50
|
+
return error.info;
|
|
51
|
+
if (error instanceof ApiHttpError) {
|
|
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 };
|
|
53
|
+
}
|
|
54
|
+
if (error instanceof PaidRequestOutcomeUnknownError) {
|
|
55
|
+
return {
|
|
56
|
+
status: 0,
|
|
57
|
+
category: 'outcome_unknown',
|
|
58
|
+
message: 'The submission timed out or the connection dropped, so it is unknown whether a task was created.',
|
|
59
|
+
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.',
|
|
60
|
+
retryable: true,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
if (error instanceof RequestTimeoutError || error instanceof TypeError) {
|
|
64
|
+
return { status: 0, category: 'server_error', message: 'EvoLink did not respond in time.', next_step: 'Retry in a minute.', retryable: true };
|
|
65
|
+
}
|
|
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
|
|
73
|
+
// signed-in connection that cannot use the hosted service channel.
|
|
74
|
+
return {
|
|
75
|
+
status: 0,
|
|
76
|
+
category: 'unauthorized',
|
|
77
|
+
message,
|
|
78
|
+
next_step: processCredentialsAllowed()
|
|
79
|
+
? `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.`
|
|
80
|
+
: 'Ask the user to reconnect EvoLink in this client. If it keeps failing, retry in a few minutes.',
|
|
81
|
+
retryable: false,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/** Converts a thrown error into a tool error with a category and a concrete next step. */
|
|
85
|
+
export function errorResult(error, context = {}) {
|
|
86
|
+
const info = infoFor(error);
|
|
87
|
+
const requestId = publicIdentifier(info.request_id);
|
|
88
|
+
const clientRequestId = publicIdentifier(context.clientRequestId);
|
|
89
|
+
const taskId = publicIdentifier(context.taskId);
|
|
90
|
+
const label = `${info.category}${info.code ? `, ${info.code}` : ''}${info.status ? `, HTTP ${info.status}` : ''}`;
|
|
91
|
+
const lines = info.headline ? [info.headline] : [`Error (${label}): ${info.message}`];
|
|
92
|
+
let charged;
|
|
93
|
+
let submissionState;
|
|
94
|
+
if (context.paid) {
|
|
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.');
|
|
108
|
+
}
|
|
109
|
+
else
|
|
110
|
+
lines.push(beforeSubmit ? 'Nothing was submitted or charged.' : 'Nothing was submitted or charged. Gateway admission rejected the generation before dispatch.');
|
|
111
|
+
}
|
|
112
|
+
lines.push(`Next step: ${info.next_step}`);
|
|
113
|
+
// No HTTP status: the request timed out or the connection dropped, so the upload's outcome is unknown.
|
|
114
|
+
if (context.upload && info.category === 'server_error' && !info.status) {
|
|
115
|
+
lines.push('The upload may not have finished. Calling upload_file again is safe.');
|
|
116
|
+
}
|
|
117
|
+
if (info.headline)
|
|
118
|
+
lines.push(`Error: ${label}`);
|
|
119
|
+
if (requestId)
|
|
120
|
+
lines.push(`Request ID: ${requestId}`);
|
|
121
|
+
return failure(lines.join('\n'), {
|
|
122
|
+
error: info,
|
|
123
|
+
...(charged ? { charged } : {}),
|
|
124
|
+
...(submissionState ? { submission_state: submissionState } : {}),
|
|
125
|
+
...(clientRequestId && context.paid ? { client_request_id: clientRequestId } : {}),
|
|
126
|
+
...(taskId ? { task_id: taskId } : {}),
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
/** Sends a progress notification when the client asked for them; failures are ignored. */
|
|
130
|
+
export function progressReporter(extra, totalSeconds) {
|
|
131
|
+
const token = extra?._meta?.progressToken;
|
|
132
|
+
let last = -1;
|
|
133
|
+
return async (elapsedSeconds, message) => {
|
|
134
|
+
if (token === undefined || !extra)
|
|
135
|
+
return;
|
|
136
|
+
const progress = Math.max(last + 1, Math.round(elapsedSeconds));
|
|
137
|
+
last = progress;
|
|
138
|
+
await extra.sendNotification({
|
|
139
|
+
method: 'notifications/progress',
|
|
140
|
+
params: { progressToken: token, progress, total: Math.max(totalSeconds, progress), message },
|
|
141
|
+
}).catch(() => undefined);
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
export function sleep(ms, signal) {
|
|
145
|
+
return new Promise(resolve => {
|
|
146
|
+
if (signal?.aborted) {
|
|
147
|
+
resolve();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const timer = setTimeout(done, ms);
|
|
151
|
+
function done() {
|
|
152
|
+
clearTimeout(timer);
|
|
153
|
+
signal?.removeEventListener('abort', done);
|
|
154
|
+
resolve();
|
|
155
|
+
}
|
|
156
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
157
|
+
});
|
|
158
|
+
}
|