@evolinkai/cli 0.5.1 → 0.6.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 +33 -1
- package/package.json +1 -1
- package/skills/evolink-cli/SKILL.md +19 -2
- package/skills/evolink-cli/references/media-workflows.md +25 -0
- package/src/auth.mjs +28 -9
- package/src/cli.mjs +38 -21
- package/src/doctor.mjs +66 -0
- package/src/errors.mjs +25 -1
- package/src/files.mjs +26 -7
- package/src/mcp.mjs +2 -1
- package/src/media-content.mjs +31 -0
- package/src/media.mjs +40 -10
- package/src/network.mjs +55 -17
- package/src/setup.mjs +69 -0
- package/src/skills.mjs +159 -22
- package/src/state.mjs +64 -25
- package/src/version.mjs +3 -0
package/src/mcp.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CLI_VERSION } from './version.mjs';
|
|
1
2
|
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
2
3
|
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
3
4
|
import { CliError, requireThat, safeMessage } from './errors.mjs';
|
|
@@ -7,7 +8,7 @@ export class Mcp {
|
|
|
7
8
|
async call(name, args = {}) {
|
|
8
9
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
9
10
|
const access = await this.credentials.access(attempt > 0);
|
|
10
|
-
const client = new Client({ name: 'EvoLink CLI', version:
|
|
11
|
+
const client = new Client({ name: 'EvoLink CLI', version: CLI_VERSION });
|
|
11
12
|
const headers = { Authorization: `Bearer ${access.access_token}` };
|
|
12
13
|
const transport = new StreamableHTTPClientTransport(this.credentials.server, { requestInit: { headers }, fetch: this.credentials.fetchFn });
|
|
13
14
|
// The hosted service is stateless and does not expose an SSE GET stream.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { requireThat } from './errors.mjs';
|
|
2
|
+
|
|
3
|
+
export function checkContentType(value, kind) {
|
|
4
|
+
const type = (value || '').split(';')[0].trim().toLowerCase();
|
|
5
|
+
const generic = !type || ['application/octet-stream', 'binary/octet-stream', 'application/ogg'].includes(type);
|
|
6
|
+
requireThat(generic || type.startsWith(`${kind}/`), 'invalid_download_content',
|
|
7
|
+
'The file service did not return the expected media. Keep the task ID and retry the download; do not regenerate.', { expected_kind: kind, content_type: type });
|
|
8
|
+
return type;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Inspect a bounded prefix, without decoding or modifying the original media.
|
|
12
|
+
export function checkMediaPrefix(bytes, kind, contentType) {
|
|
13
|
+
const ascii = (offset, length) => bytes.toString('ascii', offset, offset + length);
|
|
14
|
+
let kinds = [];
|
|
15
|
+
if (bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')) ||
|
|
16
|
+
(bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) ||
|
|
17
|
+
['GIF87a', 'GIF89a'].includes(ascii(0, 6)) || ascii(0, 2) === 'BM' ||
|
|
18
|
+
['49492a00', '4d4d002a', '00000100'].includes(bytes.subarray(0, 4).toString('hex'))) kinds = ['image'];
|
|
19
|
+
else if (ascii(0, 4) === 'RIFF' && ascii(8, 4) === 'WEBP') kinds = ['image'];
|
|
20
|
+
else if ((ascii(0, 4) === 'RIFF' && ascii(8, 4) === 'WAVE') ||
|
|
21
|
+
(ascii(0, 4) === 'FORM' && ['AIFF', 'AIFC'].includes(ascii(8, 4))) ||
|
|
22
|
+
ascii(0, 4) === 'fLaC' || ascii(0, 3) === 'ID3' ||
|
|
23
|
+
(bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0)) kinds = ['audio'];
|
|
24
|
+
else if (ascii(0, 4) === 'OggS' || bytes.subarray(0, 4).toString('hex') === '1a45dfa3') kinds = ['audio', 'video'];
|
|
25
|
+
else if (ascii(4, 4) === 'ftyp') {
|
|
26
|
+
kinds = ['avif', 'avis', 'heic', 'heix', 'heif', 'mif1', 'msf1'].includes(ascii(8, 4)) ? ['image'] : ['audio', 'video'];
|
|
27
|
+
} else if (bytes.subarray(0, 4).toString('hex') === '000001ba') kinds = ['video'];
|
|
28
|
+
else if (contentType === 'image/svg+xml' && /^(?:<\?xml[^>]*>\s*)?<svg\b/i.test(bytes.toString('utf8').replace(/^\uFEFF/, '').trimStart())) kinds = ['image'];
|
|
29
|
+
requireThat(kinds.includes(kind), 'invalid_download_content',
|
|
30
|
+
'The response has no matching media header. It may be an error page or an incomplete file. Keep the task ID and retry the download; do not regenerate.', { expected_kind: kind });
|
|
31
|
+
}
|
package/src/media.mjs
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { hash } from './state.mjs';
|
|
3
|
-
import { CliError, requireThat } from './errors.mjs';
|
|
3
|
+
import { CliError, requireThat, fileError } from './errors.mjs';
|
|
4
|
+
|
|
5
|
+
function quoteError(error, cap) {
|
|
6
|
+
const cause = fileError(error);
|
|
7
|
+
return new CliError(cause instanceof CliError ? cause.code : 'estimate_unavailable',
|
|
8
|
+
cause instanceof CliError ? cause.message : 'The quote could not be obtained. No generation was submitted.', {
|
|
9
|
+
...(cause instanceof CliError ? cause.details : {}), phase: 'estimate', submission_allowed: false,
|
|
10
|
+
...(cap !== undefined ? { max_cost_usd: cap } : {}),
|
|
11
|
+
next_step: 'Resolve the quote error and estimate again with the same budget. Do not use catalog starting prices as task quotes or remove the user budget.',
|
|
12
|
+
}, cause.exitCode);
|
|
13
|
+
}
|
|
4
14
|
|
|
5
15
|
export function priceFingerprint(quote) {
|
|
6
16
|
return hash({ model: quote.model, type: quote.type, input_valid: quote.input_valid, estimate: quote.estimate,
|
|
@@ -9,10 +19,17 @@ export function priceFingerprint(quote) {
|
|
|
9
19
|
|
|
10
20
|
export function checkEstimate(quote, cap) {
|
|
11
21
|
requireThat(quote.input_valid !== false, 'invalid_input', 'The model input is invalid.', { problems: quote.problems });
|
|
12
|
-
requireThat(quote.
|
|
13
|
-
|
|
22
|
+
requireThat(quote.enough_limit !== false, 'insufficient_limit', 'The EvoLink MCP or API key spending limit does not cover this estimate. Adjust that limit; this is not the account balance.', { limit_scope: quote.limit_scope });
|
|
23
|
+
requireThat(quote.enough_daily_limit !== false, 'insufficient_daily_limit', 'The daily spending limit does not cover this estimate. Wait for its reset or adjust that limit; this is not the account balance.');
|
|
24
|
+
requireThat(quote.enough_balance !== false, 'insufficient_balance', 'The EvoLink account balance does not cover this estimate.');
|
|
25
|
+
if (quote.estimate?.status === 'estimated') {
|
|
26
|
+
const { min_usd, max_usd } = quote.estimate;
|
|
27
|
+
requireThat(Number.isFinite(max_usd) && max_usd >= 0 && (min_usd === undefined || Number.isFinite(min_usd) && min_usd >= 0 && min_usd <= max_usd),
|
|
28
|
+
'estimate_unavailable', 'The service returned an invalid price range. Obtain a valid quote before submission.');
|
|
29
|
+
}
|
|
14
30
|
if (cap !== undefined) {
|
|
15
31
|
requireThat(Number.isFinite(cap) && cap > 0 && cap <= 10_000, 'invalid_cap', 'max-cost-usd must be greater than 0 and at most 10000.');
|
|
32
|
+
requireThat(quote.input_valid === true, 'uncheckable_input', 'The service could not validate the model input. The CLI cannot submit this request with a spending cap.', { problems: quote.problems });
|
|
16
33
|
requireThat(quote.estimate?.status === 'estimated' && Number.isFinite(quote.estimate.max_usd),
|
|
17
34
|
'uncheckable_cap', 'This request has no complete cost estimate. The CLI cannot submit it with a spending cap.', { estimate: quote.estimate });
|
|
18
35
|
requireThat(quote.estimate.max_usd <= cap, 'cost_exceeds_cap', 'The estimated cost exceeds max-cost-usd.', { estimate: quote.estimate, max_cost_usd: cap });
|
|
@@ -24,12 +41,15 @@ export class Media {
|
|
|
24
41
|
constructor({ mcp, state, server, now = Date.now }) { this.mcp = mcp; this.state = state; this.server = server.href; this.now = now; }
|
|
25
42
|
async estimate(args) {
|
|
26
43
|
const { max_cost_usd, ...input } = args;
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
44
|
+
let quote;
|
|
45
|
+
try {
|
|
46
|
+
quote = await this.mcp.call('estimate_cost', input);
|
|
47
|
+
checkEstimate(quote, max_cost_usd);
|
|
48
|
+
requireThat(['image', 'video', 'audio'].includes(quote.type), 'unsupported_model', 'This model is not a media generation model.');
|
|
49
|
+
} catch (error) { throw quoteError(error, max_cost_usd); }
|
|
30
50
|
// A complete quote also guards a pricing change between the refresh and POST.
|
|
31
51
|
const quotedMax = quote.estimate.max_usd;
|
|
32
|
-
const effectiveCap = max_cost_usd ?? (quote.estimate.status === 'estimated' && Number.isFinite(quotedMax) && quotedMax > 0 && quotedMax <= 10_000 ? quotedMax : undefined);
|
|
52
|
+
const effectiveCap = max_cost_usd ?? (quote.input_valid === true && quote.estimate.status === 'estimated' && Number.isFinite(quotedMax) && quotedMax > 0 && quotedMax <= 10_000 ? quotedMax : undefined);
|
|
33
53
|
const id = randomUUID();
|
|
34
54
|
const argsToSubmit = { ...input, model: quote.model, ...(effectiveCap !== undefined ? { max_cost_usd: effectiveCap } : {}) };
|
|
35
55
|
const stored = { id, server: this.server, binding: quote._binding, args: argsToSubmit,
|
|
@@ -53,13 +73,23 @@ export class Media {
|
|
|
53
73
|
const quote = await this.load(id);
|
|
54
74
|
requireThat(quote.type === kind, 'quote_type_mismatch', 'Use the media type shown in the saved quote.');
|
|
55
75
|
if (quote.task_id) return { ...await this.mcp.call('get_task', { task_id: quote.task_id, wait_seconds: 0 }), quote_id: id, recovered: true };
|
|
76
|
+
requireThat(quote.state !== 'refused', 'submission_refused',
|
|
77
|
+
'EvoLink refused this submission and reported no charge. Resolve the original error, estimate again with the same budget, and obtain approval for the new quote.',
|
|
78
|
+
{ quote_id: id, client_request_id: quote.client_request_id, charged: 'no', submission_allowed: false });
|
|
79
|
+
if (resume && quote.state === 'quoted') throw new CliError('submission_not_started',
|
|
80
|
+
'This quote has never been submitted. After user approval, use generate with this same quote; tasks resume only recovers an uncertain submission.',
|
|
81
|
+
{ quote_id: id, client_request_id: quote.client_request_id, submission_allowed: false,
|
|
82
|
+
next_step: `After user approval, run evolink generate ${kind} --quote ${id} --confirm.` });
|
|
56
83
|
requireThat(resume ? ['submitting', 'outcome_unknown'].includes(quote.state) : quote.state === 'quoted',
|
|
57
84
|
'submission_already_started', 'A submission already started. Use tasks resume with this quote; do not create a new request ID.', { quote_id: id, client_request_id: quote.client_request_id });
|
|
58
85
|
requireThat(this.now() <= quote.expires_at, 'quote_expired', 'The quote expired. Check recent tasks before preparing another submission.', { quote_id: id, client_request_id: quote.client_request_id });
|
|
59
86
|
const { max_cost_usd, ...checkArgs } = quote.args;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
87
|
+
let fresh;
|
|
88
|
+
try {
|
|
89
|
+
fresh = await this.mcp.call('estimate_cost', checkArgs);
|
|
90
|
+
requireThat(priceFingerprint(fresh) === quote.fingerprint, 'price_changed', 'The quote changed. Estimate again and obtain approval for the new quote.', { estimate: fresh.estimate });
|
|
91
|
+
checkEstimate(fresh, max_cost_usd);
|
|
92
|
+
} catch (error) { throw quoteError(error, max_cost_usd); }
|
|
63
93
|
quote.state = 'submitting';
|
|
64
94
|
quote.approved_at ??= this.now();
|
|
65
95
|
await this.state.write('quotes', id, quote);
|
package/src/network.mjs
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import net from 'node:net';
|
|
2
2
|
import dns from 'node:dns/promises';
|
|
3
|
+
import https from 'node:https';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
3
5
|
import { CliError, requireThat } from './errors.mjs';
|
|
6
|
+
import { CLI_VERSION } from './version.mjs';
|
|
4
7
|
|
|
5
8
|
export const SERVER = 'https://mcp.evolink.ai/mcp';
|
|
6
9
|
export const ISSUER = 'https://passport.evolink.ai';
|
|
7
|
-
export const USER_AGENT =
|
|
10
|
+
export const USER_AGENT = `EvoLinkCLI/${CLI_VERSION}`;
|
|
8
11
|
export const loopback = url => url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname);
|
|
9
12
|
|
|
10
13
|
export function serverURL(value = SERVER) {
|
|
@@ -26,39 +29,74 @@ export function authFetch(server, fetchFn = fetch) {
|
|
|
26
29
|
};
|
|
27
30
|
}
|
|
28
31
|
|
|
32
|
+
const blocked = new net.BlockList();
|
|
33
|
+
for (const [network, prefix] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['127.0.0.0', 8], ['169.254.0.0', 16],
|
|
34
|
+
['172.16.0.0', 12], ['192.168.0.0', 16], ['224.0.0.0', 3], ['100.64.0.0', 10]]) blocked.addSubnet(network, prefix, 'ipv4');
|
|
35
|
+
for (const address of ['::', '::1']) blocked.addAddress(address, 'ipv6');
|
|
36
|
+
for (const [network, prefix] of [['fc00::', 7], ['fe80::', 10], ['ff00::', 8]]) blocked.addSubnet(network, prefix, 'ipv6');
|
|
37
|
+
|
|
29
38
|
function privateIP(address) {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return a === 0 || a === 10 || a === 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a >= 224 || a === 100 && b >= 64 && b <= 127;
|
|
33
|
-
}
|
|
34
|
-
const ip = address.toLowerCase();
|
|
35
|
-
if (ip.startsWith('::ffff:')) return privateIP(ip.slice(7));
|
|
36
|
-
return ip === '::' || ip === '::1' || ip.startsWith('fc') || ip.startsWith('fd') || /^fe[89ab]/.test(ip);
|
|
39
|
+
const family = net.isIP(address);
|
|
40
|
+
return !family || blocked.check(address, family === 4 ? 'ipv4' : 'ipv6');
|
|
37
41
|
}
|
|
38
42
|
|
|
39
|
-
|
|
43
|
+
async function resolveResult(value, testOrigin) {
|
|
40
44
|
let url;
|
|
41
45
|
try { url = new URL(value); } catch { throw new CliError('invalid_result_url', 'The result URL is invalid.'); }
|
|
42
46
|
requireThat(!url.username && !url.password && !url.hash, 'invalid_result_url', 'The result URL contains unsupported credentials or a fragment.');
|
|
43
|
-
if (testOrigin && url.origin === testOrigin && loopback(url)) return url;
|
|
47
|
+
if (testOrigin && url.origin === testOrigin && loopback(url)) return { url, addresses: [] };
|
|
44
48
|
requireThat(url.protocol === 'https:', 'invalid_result_url', 'Result downloads require a public HTTPS URL.');
|
|
45
|
-
const
|
|
49
|
+
const host = url.hostname.replace(/^\[|\]$/g, '');
|
|
50
|
+
const family = net.isIP(host);
|
|
51
|
+
const addresses = family ? [{ address: host, family }] : await dns.lookup(host, { all: true });
|
|
46
52
|
requireThat(addresses.length > 0 && addresses.every(a => !privateIP(a.address)), 'invalid_result_url', 'The result URL points to a private network.');
|
|
47
|
-
return url;
|
|
53
|
+
return { url, addresses };
|
|
48
54
|
}
|
|
49
55
|
|
|
50
|
-
export async function
|
|
51
|
-
|
|
56
|
+
export async function publicURL(value, testOrigin) {
|
|
57
|
+
return (await resolveResult(value, testOrigin)).url;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function pinnedFetch(url, addresses, signal) {
|
|
61
|
+
// Preserve the original hostname for TLS while using only a validated IP.
|
|
62
|
+
const address = addresses.find(item => item.family === 4) || addresses[0];
|
|
63
|
+
return new Promise((resolve, reject) => {
|
|
64
|
+
const request = https.request(url, { method: 'GET', agent: false, signal,
|
|
65
|
+
family: address.family, headers: { 'User-Agent': USER_AGENT, 'Accept-Encoding': 'identity' },
|
|
66
|
+
lookup: (_host, options, callback) => options?.all
|
|
67
|
+
? callback(null, [address]) : callback(null, address.address, address.family),
|
|
68
|
+
}, incoming => {
|
|
69
|
+
const headers = new Headers();
|
|
70
|
+
for (let i = 0; i < incoming.rawHeaders.length; i += 2) headers.append(incoming.rawHeaders[i], incoming.rawHeaders[i + 1]);
|
|
71
|
+
const status = incoming.statusCode;
|
|
72
|
+
const noBody = [204, 205, 304].includes(status);
|
|
73
|
+
if (noBody) incoming.resume();
|
|
74
|
+
resolve(new Response(noBody ? null : Readable.toWeb(incoming), { status, headers }));
|
|
75
|
+
});
|
|
76
|
+
request.once('error', reject);
|
|
77
|
+
request.end();
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function resultFetch(value, { testOrigin, signal, fetchFn } = {}) {
|
|
82
|
+
let resolved = await resolveResult(value, testOrigin);
|
|
83
|
+
signal ||= AbortSignal.timeout(600_000);
|
|
52
84
|
for (let count = 0; count < 6; count++) {
|
|
53
|
-
const
|
|
85
|
+
const { url, addresses } = resolved;
|
|
86
|
+
const response = fetchFn || !addresses.length
|
|
87
|
+
? await (fetchFn || fetch)(url, { redirect: 'manual', headers: { 'User-Agent': USER_AGENT }, signal })
|
|
88
|
+
: await pinnedFetch(url, addresses, signal);
|
|
54
89
|
if ([301, 302, 303, 307, 308].includes(response.status)) {
|
|
55
90
|
const location = response.headers.get('location');
|
|
56
91
|
await response.body?.cancel();
|
|
57
92
|
requireThat(location, 'download_failed', 'The download redirect has no destination.');
|
|
58
|
-
|
|
93
|
+
resolved = await resolveResult(new URL(location, url).href, testOrigin);
|
|
59
94
|
continue;
|
|
60
95
|
}
|
|
61
|
-
|
|
96
|
+
if (!response.ok) {
|
|
97
|
+
await response.body?.cancel();
|
|
98
|
+
throw new CliError('download_failed', `The file service returned HTTP ${response.status}. Check the task again for a current result link.`);
|
|
99
|
+
}
|
|
62
100
|
return response;
|
|
63
101
|
}
|
|
64
102
|
throw new CliError('download_failed', 'The file service returned too many redirects.');
|
package/src/setup.mjs
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { prerequisites, verifyModels } from './doctor.mjs';
|
|
2
|
+
import { installSkill, skillStatus, validateAgent } from './skills.mjs';
|
|
3
|
+
import { CliError, errorView, requireThat } from './errors.mjs';
|
|
4
|
+
import { CLI_VERSION } from './version.mjs';
|
|
5
|
+
|
|
6
|
+
const LOGIN_ERRORS = new Set(['login_required', 'invalid_session', 'login_expired']);
|
|
7
|
+
|
|
8
|
+
export async function setup({ state, server, credentials, mcp, agent = 'all', skillHome, noBrowser = false,
|
|
9
|
+
timeout = 180_000, signal, progress = () => {}, version, platform }) {
|
|
10
|
+
validateAgent(agent);
|
|
11
|
+
return state.lock('setup', async () => {
|
|
12
|
+
const steps = [];
|
|
13
|
+
let phase = 'preflight', connected = false, models = false, skills;
|
|
14
|
+
const recovery = () => `evolink setup --agent ${agent}${noBrowser ? ' --no-browser' : ''}`;
|
|
15
|
+
try {
|
|
16
|
+
progress('Setup: checking runtime, local state and secure credential storage.');
|
|
17
|
+
const preflight = await prerequisites({ state, credentials, version, platform });
|
|
18
|
+
steps.push(...preflight.checks);
|
|
19
|
+
const failed = preflight.checks.find(c => c.status === 'failed');
|
|
20
|
+
if (failed) throw new CliError(failed.error.code, failed.error.message, failed.error.details);
|
|
21
|
+
phase = 'skills';
|
|
22
|
+
progress('Setup: checking and installing the bundled skill.');
|
|
23
|
+
// Resolve file conflicts before asking the user to authorize a browser login.
|
|
24
|
+
skills = await installSkill({ home: skillHome, agent });
|
|
25
|
+
steps.push({ name: 'skills', status: 'passed', reused: !skills.updated });
|
|
26
|
+
phase = 'connection';
|
|
27
|
+
let needsLogin = !preflight.auth.authenticated;
|
|
28
|
+
if (!needsLogin) {
|
|
29
|
+
try {
|
|
30
|
+
const balance = await mcp.call('check_balance');
|
|
31
|
+
requireThat(balance.ok === true, 'connection_failed', 'Balance verification failed. Retry the connection check.');
|
|
32
|
+
connected = true;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (!LOGIN_ERRORS.has(error.code)) throw error;
|
|
35
|
+
needsLogin = true;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
phase = 'login';
|
|
39
|
+
if (needsLogin) {
|
|
40
|
+
progress('Setup: browser approval is required. Keep this command running until login finishes.');
|
|
41
|
+
await credentials.login({ noBrowser, timeout, signal, progress });
|
|
42
|
+
}
|
|
43
|
+
steps.push({ name: 'login', status: 'passed', reused: !needsLogin });
|
|
44
|
+
phase = 'connection';
|
|
45
|
+
if (!connected) {
|
|
46
|
+
const balance = await mcp.call('check_balance');
|
|
47
|
+
requireThat(balance.ok === true, 'connection_failed', 'Balance verification failed. Retry evolink balance --json.');
|
|
48
|
+
connected = true;
|
|
49
|
+
}
|
|
50
|
+
steps.push({ name: 'connection', status: 'passed', verified: true });
|
|
51
|
+
phase = 'models';
|
|
52
|
+
await verifyModels(mcp); models = true;
|
|
53
|
+
steps.push({ name: 'models', status: 'passed', verified: true });
|
|
54
|
+
phase = 'skills';
|
|
55
|
+
const status = await skillStatus({ home: skillHome, agent });
|
|
56
|
+
requireThat(status.current, 'skill_changed', 'The skill changed during setup. Check evolink skills status before continuing.');
|
|
57
|
+
progress('Setup: CLI connection, models and skill files verified. Ask your assistant to confirm skill discovery.');
|
|
58
|
+
return { ok: true, setup_complete: true, cli_version: CLI_VERSION, agent, server: server.href,
|
|
59
|
+
connection_verified: connected, model_discovery_verified: models, skills, steps,
|
|
60
|
+
assistant_discovery: 'not_checked', next_step: skills.next_step };
|
|
61
|
+
} catch (error) {
|
|
62
|
+
const view = errorView(error);
|
|
63
|
+
steps.push({ name: phase, status: 'failed', error: view });
|
|
64
|
+
return { ok: false, setup_complete: false, cli_version: CLI_VERSION, agent, phase,
|
|
65
|
+
connection_verified: connected, model_discovery_verified: models, assistant_discovery: 'not_checked',
|
|
66
|
+
...(skills ? { skills } : {}), steps, error: view, recovery: recovery() };
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}
|
package/src/skills.mjs
CHANGED
|
@@ -2,36 +2,173 @@ import * as fs from 'node:fs/promises';
|
|
|
2
2
|
import os from 'node:os';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
|
-
import { randomUUID } from 'node:crypto';
|
|
6
|
-
import { requireThat } from './errors.mjs';
|
|
5
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
6
|
+
import { CliError, requireThat } from './errors.mjs';
|
|
7
|
+
import { State } from './state.mjs';
|
|
8
|
+
import { CLI_VERSION } from './version.mjs';
|
|
7
9
|
|
|
8
10
|
const AGENT_DIRS = {
|
|
9
11
|
codex: '.agents', 'claude-code': '.claude', cursor: '.agents',
|
|
10
12
|
gemini: '.agents', opencode: '.agents', copilot: '.agents',
|
|
11
13
|
openclaw: '.openclaw', hermes: '.hermes',
|
|
12
14
|
};
|
|
15
|
+
const MANIFEST = '.evolink-cli.json';
|
|
16
|
+
const LEGACY_HASHES = new Set([
|
|
17
|
+
'680faa81bab65b6324933fa24bed34f2680c88df0bbf843423b53e3d3c9b6de5', // Published 0.5.0.
|
|
18
|
+
'bed3f5dcba1d5d07e98f21f6ab45180eaa5983b610851d2aed25274114b64982', // Published 0.5.1.
|
|
19
|
+
]);
|
|
20
|
+
const digest = content => createHash('sha256').update(content).digest('hex');
|
|
21
|
+
const owned = content => content?.startsWith('---\nname: evolink-cli\n') && content.includes('<!-- evolink-media-cli-owned -->');
|
|
22
|
+
const source = fileURLToPath(new URL('../skills/evolink-cli/', import.meta.url));
|
|
13
23
|
|
|
14
|
-
export
|
|
15
|
-
requireThat(agent === 'all' || Object.hasOwn(AGENT_DIRS, agent), 'invalid_agent',
|
|
16
|
-
|
|
17
|
-
|
|
24
|
+
export function validateAgent(agent = 'all') {
|
|
25
|
+
requireThat(agent === 'all' || Object.hasOwn(AGENT_DIRS, agent), 'invalid_agent',
|
|
26
|
+
'Choose all, codex, claude-code, cursor, gemini, opencode, copilot, openclaw or hermes.');
|
|
27
|
+
return agent;
|
|
28
|
+
}
|
|
29
|
+
function targets(home, agent) {
|
|
30
|
+
validateAgent(agent);
|
|
18
31
|
const dirs = agent === 'all' ? [...new Set(Object.values(AGENT_DIRS))] : [AGENT_DIRS[agent]];
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
32
|
+
return dirs.map(dir => path.join(home, dir, 'skills', 'evolink-cli'));
|
|
33
|
+
}
|
|
34
|
+
async function readOptional(file) {
|
|
35
|
+
try { return await fs.readFile(file, 'utf8'); }
|
|
36
|
+
catch (e) { if (e.code === 'ENOENT') return undefined; throw e; }
|
|
37
|
+
}
|
|
38
|
+
async function bundle() {
|
|
39
|
+
const files = {};
|
|
40
|
+
async function visit(dir, prefix = '') {
|
|
41
|
+
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
|
|
42
|
+
const relative = prefix + entry.name;
|
|
43
|
+
requireThat(!entry.isSymbolicLink(), 'invalid_skill_bundle', 'The bundled skill cannot contain symbolic links.');
|
|
44
|
+
if (entry.isDirectory()) await visit(path.join(dir, entry.name), `${relative}/`);
|
|
45
|
+
else if (entry.isFile()) files[relative] = await fs.readFile(path.join(dir, entry.name));
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
await visit(source);
|
|
49
|
+
return files;
|
|
50
|
+
}
|
|
51
|
+
async function noSymlinks(home, dir, files) {
|
|
52
|
+
for (const file of ['', MANIFEST, ...Object.keys(files)]) {
|
|
53
|
+
const relative = path.relative(home, path.join(dir, file));
|
|
54
|
+
let current = home;
|
|
55
|
+
for (const part of relative.split(path.sep)) {
|
|
56
|
+
current = path.join(current, part);
|
|
57
|
+
try {
|
|
58
|
+
requireThat(!(await fs.lstat(current)).isSymbolicLink(), 'skill_conflict',
|
|
59
|
+
'A skill destination is a symbolic link. Choose a regular skill directory before installing.', { path: current });
|
|
60
|
+
} catch (e) { if (e.code !== 'ENOENT') throw e; break; }
|
|
61
|
+
}
|
|
28
62
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
63
|
+
}
|
|
64
|
+
async function inspect(home, dir, files) {
|
|
65
|
+
await noSymlinks(home, dir, files);
|
|
66
|
+
const previous = await readOptional(path.join(dir, 'SKILL.md'));
|
|
67
|
+
const raw = await readOptional(path.join(dir, MANIFEST));
|
|
68
|
+
let manifest;
|
|
69
|
+
try { manifest = raw ? JSON.parse(raw) : undefined; } catch { /* Treat damaged metadata as a conflict. */ }
|
|
70
|
+
const valid = manifest?.schema_version === 1 && typeof manifest.cli_version === 'string' &&
|
|
71
|
+
manifest.files && typeof manifest.files === 'object' && !Array.isArray(manifest.files) &&
|
|
72
|
+
Object.entries(manifest.files).every(([name, sha]) => /^[a-zA-Z0-9_.\/-]+$/.test(name) &&
|
|
73
|
+
!name.startsWith('/') && name.split('/').every(p => p && p !== '.' && p !== '..') && /^[a-f0-9]{64}$/.test(sha));
|
|
74
|
+
const changes = [];
|
|
75
|
+
const liveHashes = {};
|
|
76
|
+
let matches = true;
|
|
77
|
+
for (const [relative, content] of Object.entries(files)) {
|
|
78
|
+
const live = await readOptional(path.join(dir, relative));
|
|
79
|
+
liveHashes[relative] = live === undefined ? null : digest(live);
|
|
80
|
+
if (live === undefined || digest(live) !== digest(content)) matches = false;
|
|
81
|
+
// Existing untracked resources are user content and must not be overwritten.
|
|
82
|
+
if (live !== undefined && valid && (!manifest.files[relative] || digest(live) !== manifest.files[relative])) changes.push(relative);
|
|
83
|
+
if (live !== undefined && !raw && relative !== 'SKILL.md' && digest(live) !== digest(content)) changes.push(relative);
|
|
84
|
+
}
|
|
85
|
+
if (valid) {
|
|
86
|
+
await noSymlinks(home, dir, manifest.files);
|
|
87
|
+
for (const [relative, sha] of Object.entries(manifest.files)) {
|
|
88
|
+
const live = await readOptional(path.join(dir, relative));
|
|
89
|
+
liveHashes[relative] = live === undefined ? null : digest(live);
|
|
90
|
+
if (live === undefined || digest(live) !== sha) changes.push(relative);
|
|
91
|
+
}
|
|
34
92
|
}
|
|
35
|
-
|
|
36
|
-
|
|
93
|
+
if (previous && !valid && !matches && !LEGACY_HASHES.has(digest(previous))) changes.push('SKILL.md');
|
|
94
|
+
let status;
|
|
95
|
+
if (previous === undefined && raw === undefined && !changes.length) status = 'missing';
|
|
96
|
+
else if (!owned(previous) || raw && !valid) status = 'conflict';
|
|
97
|
+
else if (changes.length || !valid && !matches && !LEGACY_HASHES.has(digest(previous))) status = 'modified';
|
|
98
|
+
else if (!valid) status = LEGACY_HASHES.has(digest(previous)) ? 'legacy' : 'unmanaged';
|
|
99
|
+
else status = matches && manifest.cli_version === CLI_VERSION ? 'current' : 'outdated';
|
|
100
|
+
return { path: path.join(dir, 'SKILL.md'), directory: dir, status,
|
|
101
|
+
installed_cli_version: valid ? manifest.cli_version : null, changed_files: [...new Set(changes)],
|
|
102
|
+
_fingerprint: digest(JSON.stringify({ previous, raw, liveHashes })) };
|
|
103
|
+
}
|
|
104
|
+
function lock(home, fn) {
|
|
105
|
+
// Skills are shared across state directories and agents: use one per-home lock.
|
|
106
|
+
return new State(path.join(home, '.evolink-media')).lock('skills-install', fn);
|
|
107
|
+
}
|
|
108
|
+
function publicInstallation({ _fingerprint, ...view }) { return view; }
|
|
109
|
+
export async function skillStatus({ home = os.homedir(), agent = 'all' } = {}) {
|
|
110
|
+
const dirs = targets(home, agent);
|
|
111
|
+
return lock(home, async () => {
|
|
112
|
+
const files = await bundle();
|
|
113
|
+
const installations = await Promise.all(dirs.map(dir => inspect(home, dir, files)));
|
|
114
|
+
return { skill: 'evolink-cli', cli_version: CLI_VERSION, agent, current: installations.every(f => f.status === 'current'),
|
|
115
|
+
installations: installations.map(publicInstallation), assistant_discovery: 'not_checked',
|
|
116
|
+
next_step: 'Run evolink skills install for missing or outdated files. Ask your assistant to confirm discovery; only reopen the conversation if needed.' };
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
export async function installSkill({ home = os.homedir(), agent = 'all', replaceModified = false } = {}) {
|
|
120
|
+
const dirs = targets(home, agent);
|
|
121
|
+
return lock(home, async () => {
|
|
122
|
+
const files = await bundle();
|
|
123
|
+
const plans = await Promise.all(dirs.map(dir => inspect(home, dir, files)));
|
|
124
|
+
// Validate every destination before writing to any agent's skill directory.
|
|
125
|
+
const conflict = plans.find(plan => plan.status === 'conflict');
|
|
126
|
+
requireThat(!conflict, 'skill_conflict', 'A different skill or invalid installation metadata already exists. Resolve it before installing.', { path: conflict?.path });
|
|
127
|
+
const modified = plans.find(plan => plan.status === 'modified');
|
|
128
|
+
requireThat(!modified || replaceModified, 'skill_modified',
|
|
129
|
+
'The installed skill has local changes. Keep them, or explicitly use --replace-modified to back up and replace it.', { path: modified?.path, changed_files: modified?.changed_files });
|
|
130
|
+
const swaps = [];
|
|
131
|
+
const staged = [];
|
|
132
|
+
try {
|
|
133
|
+
for (const plan of plans.filter(p => p.status !== 'current')) {
|
|
134
|
+
const temp = path.join(path.dirname(plan.directory), `.evolink-cli-staging-${randomUUID()}`);
|
|
135
|
+
const backup = path.join(home, '.evolink-media', 'skill-backups', randomUUID());
|
|
136
|
+
await fs.mkdir(path.dirname(plan.directory), { recursive: true, mode: 0o700 });
|
|
137
|
+
await fs.mkdir(temp, { mode: 0o700 });
|
|
138
|
+
staged.push(temp);
|
|
139
|
+
let existed = false;
|
|
140
|
+
try { await fs.cp(plan.directory, temp, { recursive: true, dereference: false }); existed = true; }
|
|
141
|
+
catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
142
|
+
for (const [relative, content] of Object.entries(files)) {
|
|
143
|
+
const file = path.join(temp, relative);
|
|
144
|
+
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
145
|
+
await fs.writeFile(file, content, { mode: 0o600 });
|
|
146
|
+
}
|
|
147
|
+
await fs.writeFile(path.join(temp, MANIFEST), JSON.stringify({ schema_version: 1, cli_version: CLI_VERSION,
|
|
148
|
+
files: Object.fromEntries(Object.entries(files).map(([relative, content]) => [relative, digest(content)])) }, null, 2) + '\n', { mode: 0o600 });
|
|
149
|
+
const now = await inspect(home, plan.directory, files);
|
|
150
|
+
requireThat(now._fingerprint === plan._fingerprint, 'skill_changed', 'The skill changed during installation. Retry after the other editor finishes.', { path: plan.path });
|
|
151
|
+
const swap = { plan, temp, backup: existed ? backup : null, backedUp: false, installed: false };
|
|
152
|
+
swaps.push(swap);
|
|
153
|
+
if (existed) {
|
|
154
|
+
await fs.mkdir(path.dirname(backup), { recursive: true, mode: 0o700 });
|
|
155
|
+
await fs.rename(plan.directory, backup);
|
|
156
|
+
swap.backedUp = true;
|
|
157
|
+
}
|
|
158
|
+
await fs.rename(temp, plan.directory);
|
|
159
|
+
swap.installed = true;
|
|
160
|
+
}
|
|
161
|
+
} catch (e) {
|
|
162
|
+
for (const swap of swaps.reverse()) {
|
|
163
|
+
if (swap.installed) await fs.rename(swap.plan.directory, swap.temp);
|
|
164
|
+
if (swap.backedUp) await fs.rename(swap.backup, swap.plan.directory);
|
|
165
|
+
}
|
|
166
|
+
throw e;
|
|
167
|
+
} finally { for (const temp of staged) await fs.rm(temp, { recursive: true, force: true }); }
|
|
168
|
+
const installations = plans.map(plan => ({ path: plan.path, status: 'current', updated: plan.status !== 'current',
|
|
169
|
+
previous_status: plan.status, backup: swaps.find(s => s.plan === plan)?.backup || null }));
|
|
170
|
+
return { skill: 'evolink-cli', cli_version: CLI_VERSION, path: installations[0].path,
|
|
171
|
+
updated: installations.some(f => f.updated), installations, assistant_discovery: 'not_checked',
|
|
172
|
+
next_step: 'Ask your assistant to confirm it discovers evolink-cli. If it does not refresh skills, open a new conversation.' };
|
|
173
|
+
});
|
|
37
174
|
}
|
package/src/state.mjs
CHANGED
|
@@ -15,6 +15,41 @@ export function canonical(value) {
|
|
|
15
15
|
export const hash = value => createHash('sha256').update(canonical(value)).digest('hex');
|
|
16
16
|
export const validID = id => typeof id === 'string' && /^[a-zA-Z0-9._-]{1,96}$/.test(id) && !id.includes('..');
|
|
17
17
|
|
|
18
|
+
const hostID = createHash('sha256').update(os.hostname()).digest('hex').slice(0, 16);
|
|
19
|
+
const pause = () => new Promise(resolve => setTimeout(resolve, 100));
|
|
20
|
+
// Windows can briefly deny directory deletion while another waiter reads it.
|
|
21
|
+
const removeLock = dir => fs.rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
|
|
22
|
+
function dead(pid) {
|
|
23
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
24
|
+
try { process.kill(pid, 0); return false; }
|
|
25
|
+
catch (error) { return error.code === 'ESRCH'; }
|
|
26
|
+
}
|
|
27
|
+
async function ownerOf(dir) {
|
|
28
|
+
try { return JSON.parse(await fs.readFile(path.join(dir, 'owner.json'), 'utf8')); }
|
|
29
|
+
catch { return undefined; }
|
|
30
|
+
}
|
|
31
|
+
async function staleOwner(dir) {
|
|
32
|
+
const owner = await ownerOf(dir);
|
|
33
|
+
if (owner) return owner.hostname === os.hostname() && dead(owner.pid);
|
|
34
|
+
try { return Date.now() - (await fs.stat(dir)).mtimeMs > 30_000; }
|
|
35
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; return false; }
|
|
36
|
+
}
|
|
37
|
+
async function recovering(dir) {
|
|
38
|
+
let entries;
|
|
39
|
+
try { entries = await fs.readdir(dir); }
|
|
40
|
+
catch (error) { if (error.code === 'ENOENT') return false; throw error; }
|
|
41
|
+
let active = false;
|
|
42
|
+
for (const name of entries) {
|
|
43
|
+
const match = /^([a-f0-9]{16})\.([1-9][0-9]*)\.([a-f0-9-]{36})$/.exec(name);
|
|
44
|
+
// Old releases left an empty recovery directory, not an owned ticket.
|
|
45
|
+
if (!match) continue;
|
|
46
|
+
if (match[1] === hostID && dead(Number(match[2]))) {
|
|
47
|
+
await fs.unlink(path.join(dir, name)).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
48
|
+
} else active = true;
|
|
49
|
+
}
|
|
50
|
+
return active;
|
|
51
|
+
}
|
|
52
|
+
|
|
18
53
|
export class State {
|
|
19
54
|
// Retain the original storage location so renaming the command preserves sessions and request IDs.
|
|
20
55
|
constructor(home = process.env.EVOLINK_CLI_HOME || process.env.EVOLINK_MEDIA_HOME || path.join(os.homedir(), '.evolink-media')) {
|
|
@@ -48,36 +83,40 @@ export class State {
|
|
|
48
83
|
const dir = path.join(this.home, 'locks', id);
|
|
49
84
|
await fs.mkdir(path.dirname(dir), { recursive: true, mode: 0o700 });
|
|
50
85
|
const deadline = Date.now() + 10_000;
|
|
86
|
+
const recovery = `${dir}.recovery`;
|
|
87
|
+
const token = randomUUID();
|
|
88
|
+
const busy = () => {
|
|
89
|
+
if (Date.now() > deadline) throw new CliError('operation_busy', 'Another command is using this state. Wait for it to finish.');
|
|
90
|
+
};
|
|
51
91
|
for (;;) {
|
|
52
|
-
|
|
92
|
+
let acquired = false;
|
|
93
|
+
try { await fs.mkdir(dir, { mode: 0o700 }); acquired = true; }
|
|
53
94
|
catch (e) {
|
|
54
95
|
if (e.code !== 'EEXIST') throw e;
|
|
55
|
-
//
|
|
56
|
-
|
|
57
|
-
|
|
96
|
+
// Each recovery has a unique, process-owned ticket. New owners wait for
|
|
97
|
+
// all tickets before entering; a crash cannot leave an unowned guard.
|
|
98
|
+
await fs.mkdir(recovery, { recursive: true, mode: 0o700 });
|
|
99
|
+
const ticket = path.join(recovery, `${hostID}.${process.pid}.${randomUUID()}`);
|
|
100
|
+
await fs.writeFile(ticket, '', { flag: 'wx', mode: 0o600 });
|
|
58
101
|
try {
|
|
59
|
-
await
|
|
60
|
-
|
|
61
|
-
let stale = false;
|
|
62
|
-
try {
|
|
63
|
-
const owner = JSON.parse(await fs.readFile(path.join(dir, 'owner.json'), 'utf8'));
|
|
64
|
-
if (owner.hostname === os.hostname()) {
|
|
65
|
-
try { process.kill(owner.pid, 0); } catch (probe) { stale = probe.code === 'ESRCH'; }
|
|
66
|
-
}
|
|
67
|
-
} catch {
|
|
68
|
-
try { stale = Date.now() - (await fs.stat(dir)).mtimeMs > 30_000; }
|
|
69
|
-
catch (statError) { if (statError.code !== 'ENOENT') throw statError; }
|
|
70
|
-
}
|
|
71
|
-
if (stale) await fs.rm(dir, { recursive: true, force: true });
|
|
72
|
-
} catch (recoveryError) { if (recoveryError.code !== 'EEXIST') throw recoveryError; }
|
|
73
|
-
finally { if (recovering) await fs.rmdir(recovery); }
|
|
74
|
-
if (Date.now() > deadline) throw new CliError('operation_busy', 'Another command is using this state. Wait for it to finish.');
|
|
75
|
-
await new Promise(resolve => setTimeout(resolve, 100));
|
|
102
|
+
if (await staleOwner(dir)) await removeLock(dir);
|
|
103
|
+
} finally { await fs.unlink(ticket); }
|
|
76
104
|
}
|
|
105
|
+
if (!acquired) { busy(); await pause(); continue; }
|
|
106
|
+
let entered = false;
|
|
107
|
+
try {
|
|
108
|
+
await fs.writeFile(path.join(dir, 'owner.json'), JSON.stringify({ pid: process.pid, hostname: os.hostname(), token }), { mode: 0o600 });
|
|
109
|
+
while (await recovering(recovery)) { busy(); await pause(); }
|
|
110
|
+
// Another recovery may have removed this not-yet-entered owner.
|
|
111
|
+
if ((await ownerOf(dir))?.token !== token) { busy(); continue; }
|
|
112
|
+
entered = true;
|
|
113
|
+
return await fn();
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (entered || error.code !== 'ENOENT') throw error;
|
|
116
|
+
} finally {
|
|
117
|
+
if ((await ownerOf(dir))?.token === token) await removeLock(dir);
|
|
118
|
+
}
|
|
119
|
+
busy();
|
|
77
120
|
}
|
|
78
|
-
try {
|
|
79
|
-
await fs.writeFile(path.join(dir, 'owner.json'), JSON.stringify({ pid: process.pid, hostname: os.hostname() }), { mode: 0o600 });
|
|
80
|
-
return await fn();
|
|
81
|
-
} finally { await fs.rm(dir, { recursive: true, force: true }); }
|
|
82
121
|
}
|
|
83
122
|
}
|
package/src/version.mjs
ADDED