@evolinkai/cli 0.5.0 → 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/src/errors.mjs CHANGED
@@ -11,15 +11,39 @@ export function requireThat(condition, code, message, details) {
11
11
  if (!condition) throw new CliError(code, message, details);
12
12
  }
13
13
 
14
+ export function fileError(error, { file, missing = 'file_not_found' } = {}) {
15
+ if (error instanceof CliError) return error;
16
+ const messages = {
17
+ ENOENT: [missing, missing === 'output_directory_missing' ? 'The output directory does not exist. Create it or choose an existing directory.' : 'The local file does not exist. Check the path.'],
18
+ ENOTDIR: ['path_not_directory', 'A parent path is not a directory. Choose a valid file path.'],
19
+ EACCES: ['file_permission_denied', 'Permission to access the local file or directory was denied. Choose a location you can read or write.'],
20
+ EPERM: ['file_permission_denied', 'Permission to access the local file or directory was denied. Choose a location you can read or write.'],
21
+ EROFS: ['filesystem_read_only', 'The filesystem is read-only. Choose a writable location.'],
22
+ ENOSPC: ['disk_full', 'The filesystem has no free space. Free space or choose another disk, then retry.'],
23
+ EDQUOT: ['disk_full', 'The filesystem quota is exhausted. Free space or choose another disk, then retry.'],
24
+ EEXIST: ['file_exists', 'The output file already exists. Choose another path.'],
25
+ EISDIR: ['invalid_file', 'The path is a directory. Choose a regular file.'],
26
+ };
27
+ const mapped = messages[error?.code];
28
+ return mapped ? new CliError(...mapped, file ? { path: file } : undefined) : error;
29
+ }
30
+
31
+ export async function localFile(action, context) {
32
+ try { return await action(); }
33
+ catch (error) { throw fileError(error, context); }
34
+ }
35
+
14
36
  export function safeMessage(message) {
15
37
  return String(message)
16
38
  .replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')
17
39
  .replace(/\b(?:sk-|evup_)[a-zA-Z0-9_-]+/g, '[redacted]')
18
40
  .replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '[redacted]')
41
+ .replace(/([?&](?:token|access_token|refresh_token|api_key|key|client_secret|code|code_verifier)=)[^\s&#"'<>]+/gi, '$1[redacted]')
19
42
  .slice(0, 2000);
20
43
  }
21
44
 
22
45
  export function errorView(error) {
46
+ error = fileError(error);
23
47
  if (!(error instanceof CliError)) {
24
48
  return { code: 'request_failed', message: 'The operation failed. Retry free queries; use the saved quote to recover a submission.' };
25
49
  }
@@ -30,7 +54,7 @@ function safeDetails(value) {
30
54
  if (typeof value === 'string') return safeMessage(value);
31
55
  if (Array.isArray(value)) return value.map(safeDetails);
32
56
  if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value)
33
- .filter(([key]) => !key.startsWith('_') && !/^(access_token|refresh_token|client_secret|code_verifier|authorization|upload_url)$/i.test(key))
57
+ .filter(([key]) => !key.startsWith('_') && !/^(access_token|refresh_token|client_secret|code_verifier|authorization|upload_url|api_key|apiKey|x-api-key|x-goog-api-key|token|secret|password)$/i.test(key))
34
58
  .map(([key, nested]) => [key, safeDetails(nested)]));
35
59
  return value;
36
60
  }
package/src/files.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  import * as fs from 'node:fs/promises';
2
- import { createReadStream, createWriteStream } from 'node:fs';
2
+ import { createReadStream, createWriteStream, constants } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { randomUUID, createHash } from 'node:crypto';
5
5
  import { Readable, Transform } from 'node:stream';
6
6
  import { pipeline } from 'node:stream/promises';
7
7
  import { resultFetch, USER_AGENT, loopback } from './network.mjs';
8
- import { CliError, requireThat } from './errors.mjs';
8
+ import { CliError, requireThat, localFile, fileError } from './errors.mjs';
9
+ import { checkContentType, checkMediaPrefix } from './media-content.mjs';
9
10
 
10
11
  const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp',
11
12
  '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.aac': 'audio/aac', '.flac': 'audio/flac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg',
@@ -13,10 +14,11 @@ const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
13
14
 
14
15
  export async function upload(file, { mcp, state, server, signal, upload_path, fetchFn = fetch }) {
15
16
  const full = path.resolve(file);
16
- const stat = await fs.stat(full);
17
+ const stat = await localFile(() => fs.stat(full), { file: full });
17
18
  requireThat(stat.isFile() && stat.size > 0 && stat.size <= 95 * 1024 * 1024, 'invalid_file', 'Uploads must be regular files between 1 byte and 95 MB.');
18
19
  const type = MIME[path.extname(full).toLowerCase()];
19
20
  requireThat(type, 'unsupported_file', 'This file format is not supported. Use JPEG, PNG, GIF, WebP, supported audio, MP4, MOV or WebM.');
21
+ await localFile(() => fs.access(full, constants.R_OK), { file: full });
20
22
  const prepared = await mcp.call('prepare_upload', { file_name: path.basename(full), ...(upload_path ? { upload_path } : {}) });
21
23
  requireThat(stat.size <= prepared.max_bytes, 'file_too_large', 'This file exceeds the upload limit.');
22
24
  const destination = new URL(prepared.upload_url);
@@ -44,24 +46,40 @@ export async function upload(file, { mcp, state, server, signal, upload_path, fe
44
46
  }
45
47
 
46
48
  export async function download(taskId, output, { mcp, server, index = 1, signal, maxBytes = 1024 ** 3, fetchFn }) {
49
+ const target = path.resolve(output);
50
+ const parent = await localFile(() => fs.stat(path.dirname(target)), { file: target, missing: 'output_directory_missing' });
51
+ requireThat(parent.isDirectory(), 'path_not_directory', 'The output parent is not a directory. Choose a valid file path.');
52
+ await localFile(() => fs.access(path.dirname(target), constants.W_OK), { file: target });
53
+ try { await fs.lstat(target); throw new CliError('file_exists', 'The output file already exists. Choose another path.'); }
54
+ catch (e) { if (e.code !== 'ENOENT') throw fileError(e, { file: target }); }
47
55
  const task = await mcp.call('get_task', { task_id: taskId, wait_seconds: 0 });
48
56
  requireThat(task.status === 'completed', 'task_not_ready', 'Wait for the task to complete before downloading.');
49
57
  const result = task.results?.[index - 1];
50
58
  requireThat(Number.isInteger(index) && index > 0 && result?.url, 'result_not_found', 'The requested result index does not exist.');
51
- const target = path.resolve(output);
52
59
  const temp = `${target}.${randomUUID()}.part`;
53
60
  let bytes = 0;
61
+ let prefix = Buffer.alloc(0), inspected = false, contentType;
54
62
  const digest = createHash('sha256');
55
63
  const guard = new Transform({ transform(chunk, encoding, callback) {
56
64
  bytes += chunk.length;
57
65
  if (bytes > maxBytes) { callback(new CliError('download_too_large', 'The download exceeded the size limit.')); return; }
66
+ if (!inspected) {
67
+ prefix = Buffer.concat([prefix, chunk.subarray(0, 512 - prefix.length)]);
68
+ if (prefix.length === 512) {
69
+ try { checkMediaPrefix(prefix, result.kind, contentType); inspected = true; }
70
+ catch (error) { callback(error); return; }
71
+ }
72
+ }
58
73
  digest.update(chunk); callback(null, chunk);
74
+ }, flush(callback) {
75
+ try { if (!inspected && bytes > 0) checkMediaPrefix(prefix, result.kind, contentType); callback(); }
76
+ catch (error) { callback(error); }
59
77
  } });
60
78
  const timeoutSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(600_000)]) : AbortSignal.timeout(600_000);
61
79
  try {
62
- try { await fs.access(target); throw new CliError('file_exists', 'The output file already exists. Choose another path.'); }
63
- catch (e) { if (e.code !== 'ENOENT') throw e; }
64
80
  const response = await resultFetch(result.url, { testOrigin: loopback(server) ? server.origin : undefined, signal: timeoutSignal, fetchFn });
81
+ try { contentType = checkContentType(response.headers.get('content-type'), result.kind); }
82
+ catch (error) { await response.body?.cancel(); throw error; }
65
83
  const length = Number(response.headers.get('content-length'));
66
84
  if (Number.isFinite(length) && length > maxBytes) {
67
85
  await response.body?.cancel();
@@ -72,5 +90,6 @@ export async function download(taskId, output, { mcp, server, index = 1, signal,
72
90
  requireThat(bytes > 0, 'download_failed', 'The file service returned an empty file.');
73
91
  await fs.link(temp, target);
74
92
  return { task_id: taskId, result_index: index, path: target, size_bytes: bytes, sha256: digest.digest('hex'), kind: result.kind };
75
- } finally { await fs.unlink(temp).catch(() => {}); }
93
+ } catch (error) { throw fileError(error, { file: target, missing: 'output_directory_missing' }); }
94
+ finally { await fs.unlink(temp).catch(() => {}); }
76
95
  }
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: '0.5.0' });
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.enough_balance !== false && quote.enough_limit !== false && quote.enough_daily_limit !== false,
13
- 'insufficient_balance', 'The account or spending limit does not cover this estimate.');
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
- const quote = await this.mcp.call('estimate_cost', input);
28
- checkEstimate(quote, max_cost_usd);
29
- requireThat(['image', 'video', 'audio'].includes(quote.type), 'unsupported_model', 'This model is not a media generation model.');
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
- const fresh = await this.mcp.call('estimate_cost', checkArgs);
61
- requireThat(priceFingerprint(fresh) === quote.fingerprint, 'price_changed', 'The quote changed. Estimate again and obtain approval for the new quote.', { estimate: fresh.estimate });
62
- checkEstimate(fresh, max_cost_usd);
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 = 'EvoLinkCLI/0.5.0';
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
- if (net.isIP(address) === 4) {
31
- const [a, b] = address.split('.').map(Number);
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
- export async function publicURL(value, testOrigin) {
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 addresses = await dns.lookup(url.hostname, { all: true });
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 resultFetch(value, { testOrigin, signal, fetchFn = fetch } = {}) {
51
- let url = await publicURL(value, testOrigin);
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 response = await fetchFn(url, { redirect: 'manual', headers: { 'User-Agent': USER_AGENT }, signal: signal || AbortSignal.timeout(600_000) });
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
- url = await publicURL(new URL(location, url).href, testOrigin);
93
+ resolved = await resolveResult(new URL(location, url).href, testOrigin);
59
94
  continue;
60
95
  }
61
- requireThat(response.ok, 'download_failed', `The file service returned HTTP ${response.status}. Check the task again for a current result link.`);
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
+ }