@evolinkai/cli 0.5.1 → 0.7.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/cli.mjs CHANGED
@@ -5,9 +5,13 @@ import { serverURL } from './network.mjs';
5
5
  import { Credentials } from './auth.mjs';
6
6
  import { Mcp } from './mcp.mjs';
7
7
  import { Media } from './media.mjs';
8
- import { upload, download } from './files.mjs';
9
- import { installSkill } from './skills.mjs';
10
- import { CliError, requireThat, errorView } from './errors.mjs';
8
+ import { upload, download, downloadAll } from './files.mjs';
9
+ import { commandHelp } from './help.mjs';
10
+ import { installSkill, skillStatus, validateAgent } from './skills.mjs';
11
+ import { doctor } from './doctor.mjs';
12
+ import { setup } from './setup.mjs';
13
+ import { CLI_VERSION } from './version.mjs';
14
+ import { CliError, requireThat, errorView, localFile } from './errors.mjs';
11
15
 
12
16
  const TASK_STATUS_FILTERS = Object.freeze(['processing', 'completed', 'failed', 'cancelled']);
13
17
  const TASK_STATUS_HELP = `Allowed task status filters: ${TASK_STATUS_FILTERS.join(', ')}.
@@ -21,13 +25,17 @@ Read recent tasks across your EvoLink account (free), newest first.
21
25
  --status STATUS ${TASK_STATUS_FILTERS.join('|')}
22
26
  --type TYPE image|video|audio; omit to include all media types
23
27
  --since TIME Creation time: ISO 8601, Unix seconds, or 30m, 2h, 1d
28
+ --until TIME Inclusive creation-time upper bound; same formats as since
29
+ --model MODEL Exact model ID (requires the updated MCP service)
30
+ --page N Page number, 1-100000 (default 1; updated MCP service)
24
31
  --limit N Integer from 1 to 50 (default 20)
25
32
  --json Return one JSON envelope on stdout
26
33
 
27
34
  ${TASK_STATUS_HELP}
28
35
  Filters are case-sensitive. A returned task status can be pending;
29
36
  response statuses are not the same as allowed --status filters.
30
- --since filters the returned recent batch; it does not search all history.
37
+ --since/--until filter the selected page; one call does not search all history.
38
+ total counts server-filtered tasks before time filtering; next_page continues.
31
39
  An empty list does not prove an uncertain submission created no task.
32
40
  cancelled is a read filter; the CLI does not provide a cancel command.
33
41
  Connection options: --server URL, --token-stdin.
@@ -38,23 +46,36 @@ Examples:
38
46
  evolink tasks list --since 30m --json
39
47
  `;
40
48
 
41
- const HELP = `EvoLink CLI 0.5.1 (Node.js 22+)
49
+ const HELP = `EvoLink CLI ${CLI_VERSION} (Node.js 22+)
42
50
 
43
- auth login [--no-browser] Sign in and approve in your browser
51
+ setup [--agent NAME] [--no-browser] [--timeout SECONDS]
52
+ Reuse or finish login, install skills and verify (free)
53
+ auth login [--no-browser] [--timeout SECONDS]
54
+ Sign in; keep this command running for the callback
44
55
  auth status | auth logout Check or revoke this CLI session
45
56
  balance Verify connection and account balance (free)
46
57
  models search [--query TEXT] [--type image|video|audio|all] [--limit N]
47
58
  models show MODEL Read parameters and pricing (free)
59
+ models schema MODEL Read versioned input/submission schemas (free)
60
+ models recommend --type TYPE [--query TEXT] [--references image,video,audio]
61
+ docs search --query TEXT Search official model reference excerpts (free)
48
62
  estimate --model MODEL --input-file FILE [--max-cost-usd USD] [--media-seconds N]
49
63
  generate image|video|audio --quote ID --confirm [--wait] [--timeout SECONDS]
50
64
  tasks get ID | tasks wait ID [--timeout SECONDS]
51
65
  tasks list [--type TYPE] [--status STATUS] [--since TIME] [--limit N]
66
+ [--until TIME] [--model MODEL] [--page N]
67
+ tasks batch --ids ID,ID Read up to 50 known tasks together (free)
68
+ usage [--since 30d] [--until TIME] [--model MODEL] [--type TYPE] [--max-pages N]
69
+ Summarize retained task costs; not a bill (free)
52
70
  tasks resume --quote ID Recover using the original request ID
53
71
  upload FILE [--upload-path FOLDER]
54
72
  uploads get ID Recover a lost upload result (free)
55
73
  download TASK_ID --output FILE [--index N]
56
- skills install [--agent NAME] Install the bundled skill for coding agents
57
- doctor Check runtime, login and connection (free)
74
+ download TASK_ID --all --output-dir DIR [--template NAME] [--resume]
75
+ skills install [--agent NAME] [--replace-modified]
76
+ Install or update; back up replaced files
77
+ skills status [--agent NAME] Check installed skill content and CLI version
78
+ doctor [--agent NAME] Check prerequisites, connection, models and skills (free)
58
79
 
59
80
  Options: --json, --server URL, --token-stdin, --help, --version
60
81
  Agents: all (default), codex, claude-code, cursor, gemini, opencode, copilot,
@@ -64,15 +85,20 @@ ${TASK_STATUS_HELP}
64
85
  Task list types: image, video, audio; omit --type to include all types.
65
86
  Task list example: evolink tasks list --status processing --json
66
87
  Run evolink tasks list --help for filter details and recovery caveats.
88
+ Each command accepts --help --json for its machine-readable command reference.
89
+ New model/docs/usage and page/model/until filters require the updated MCP service.
67
90
  After upgrading the package, run evolink skills install to refresh its skill.
91
+
92
+ Login timeout: 30-900 seconds, default 180. On SSH, forward the callback port.
93
+ The CLI verifies skill files; your assistant must confirm it loads evolink-cli.
68
94
  Quotes expire in 15 minutes. --confirm is only for an already approved quote.
69
95
  Spending caps protect the estimate at submission, not final settlement.
70
96
  Ctrl-C stops local waiting; submitted tasks continue on EvoLink.
71
97
  `;
72
98
 
73
99
  const OPTIONS = Object.fromEntries(['server', 'query', 'type', 'limit', 'model', 'input', 'input-file', 'prompt', 'media-seconds',
74
- 'max-cost-usd', 'quote', 'timeout', 'status', 'since', 'output', 'index', 'upload-path', 'agent'].map(k => [k, { type: 'string' }]));
75
- for (const k of ['json', 'token-stdin', 'no-browser', 'confirm', 'wait', 'help', 'version']) OPTIONS[k] = { type: 'boolean' };
100
+ 'max-cost-usd', 'quote', 'timeout', 'status', 'since', 'until', 'page', 'ids', 'references', 'max-pages', 'output', 'output-dir', 'template', 'index', 'upload-path', 'agent'].map(k => [k, { type: 'string' }]));
101
+ for (const k of ['json', 'token-stdin', 'no-browser', 'replace-modified', 'confirm', 'wait', 'all', 'resume', 'help', 'version']) OPTIONS[k] = { type: 'boolean' };
76
102
 
77
103
  function number(value, name, min, max, integer = false) {
78
104
  if (value === undefined) return undefined;
@@ -84,19 +110,39 @@ function number(value, name, min, max, integer = false) {
84
110
  export function validateCommand(args, options) {
85
111
  const [command, action] = args;
86
112
  const routes = {
87
- 'auth login': [2, 'no-browser'], 'auth status': [2], 'auth logout': [2], balance: [1],
88
- 'models search': [2, 'query', 'type', 'limit'], 'models show': [3],
113
+ setup: [1, 'agent', 'no-browser', 'timeout'],
114
+ 'auth login': [2, 'no-browser', 'timeout'], 'auth status': [2], 'auth logout': [2], balance: [1],
115
+ 'models search': [2, 'query', 'type', 'limit', 'page'], 'models show': [3], 'models schema': [3],
116
+ 'models recommend': [2, 'type', 'query', 'references', 'limit'], 'docs search': [2, 'query', 'type', 'limit'],
117
+ usage: [1, 'since', 'until', 'type', 'model', 'max-pages'],
89
118
  estimate: [1, 'model', 'input', 'input-file', 'prompt', 'media-seconds', 'max-cost-usd'],
90
119
  'generate image': [2, 'quote', 'confirm', 'wait', 'timeout'], 'generate video': [2, 'quote', 'confirm', 'wait', 'timeout'], 'generate audio': [2, 'quote', 'confirm', 'wait', 'timeout'],
91
- 'tasks get': [3], 'tasks wait': [3, 'timeout'], 'tasks list': [2, 'type', 'status', 'since', 'limit'], 'tasks resume': [2, 'quote'],
92
- upload: [2, 'upload-path'], 'uploads get': [3], download: [2, 'output', 'index'], 'skills install': [2, 'agent'], doctor: [1],
120
+ 'tasks get': [3], 'tasks wait': [3, 'timeout'], 'tasks batch': [2, 'ids'], 'tasks list': [2, 'type', 'status', 'since', 'until', 'model', 'page', 'limit'], 'tasks resume': [2, 'quote'],
121
+ upload: [2, 'upload-path'], 'uploads get': [3], download: [2, 'output', 'index', 'all', 'output-dir', 'template', 'resume'],
122
+ 'skills install': [2, 'agent', 'replace-modified'], 'skills status': [2, 'agent'], doctor: [1, 'agent'],
93
123
  };
94
124
  const route = routes[`${command} ${action}`] || routes[command];
95
125
  requireThat(route && args.length === route[0], 'unknown_command', 'Unknown command or argument count. Run evolink --help.');
96
126
  const allowed = new Set(['json', 'server', 'token-stdin', ...route.slice(1)]);
97
127
  requireThat(Object.keys(options).every(k => allowed.has(k)), 'invalid_option', 'An option does not apply to this command. Run evolink --help.');
98
- if (options.timeout !== undefined) number(options.timeout, 'timeout', 1, 86400, true);
99
- if (options.type !== undefined) requireThat(['image', 'video', 'audio', ...(command === 'models' ? ['all'] : [])].includes(options.type), 'invalid_type', 'Unsupported media type.');
128
+ if (options.agent !== undefined) validateAgent(options.agent);
129
+ if (options.timeout !== undefined) number(options.timeout, 'timeout', command === 'setup' || command === 'auth' ? 30 : 1,
130
+ command === 'setup' || command === 'auth' ? 900 : 86400, true);
131
+ requireThat(!(command === 'setup' && options['token-stdin']), 'invalid_option', 'setup uses the saved OS login. Use balance or doctor for a one-command stdin token.');
132
+ if (options.type !== undefined) requireThat(['image', 'video', 'audio', ...(command === 'docs' || (command === 'models' && action === 'search') ? ['all'] : [])].includes(options.type), 'invalid_type', 'Unsupported media type.');
133
+ if (options.page !== undefined) number(options.page, 'page', 1, 100000, true);
134
+ if (options['max-pages'] !== undefined) number(options['max-pages'], 'max-pages', 1, 20, true);
135
+ if (options.limit !== undefined) number(options.limit, 'limit', 1, command === 'docs' ? 20 : action === 'recommend' ? 10 : 50, true);
136
+ if (command === 'models' && action === 'recommend') {
137
+ requireThat(options.type, 'missing_type', 'Pass --type image, video or audio.');
138
+ if (options.references !== undefined) references(options.references);
139
+ }
140
+ if (command === 'docs') requireThat(options.query?.trim(), 'missing_query', 'Pass --query with model reference keywords.');
141
+ if (command === 'tasks' && action === 'batch') taskIds(options.ids);
142
+ if (command === 'download') {
143
+ requireThat(options.all ? options['output-dir'] && !options.output && !options.index : options.output && !options['output-dir'] && !options.template && !options.resume,
144
+ 'invalid_option', 'Choose --output FILE [--index N], or --all --output-dir DIR [--template NAME] [--resume].');
145
+ }
100
146
  if (options.status !== undefined) requireThat(TASK_STATUS_FILTERS.includes(options.status), 'invalid_status',
101
147
  `Unsupported task status filter. ${TASK_STATUS_HELP}`, {
102
148
  param: 'status', value: options.status, allowed_values: TASK_STATUS_FILTERS,
@@ -105,12 +151,27 @@ export function validateCommand(args, options) {
105
151
  });
106
152
  }
107
153
 
154
+ function references(value) {
155
+ const kinds = value.split(',');
156
+ requireThat(kinds.length >= 1 && kinds.length <= 3 && kinds.every(kind => ['image', 'video', 'audio'].includes(kind)),
157
+ 'invalid_references', 'Use comma-separated reference kinds: image, video, audio.');
158
+ return [...new Set(kinds)];
159
+ }
160
+
161
+ function taskIds(value) {
162
+ const ids = (value ?? '').split(',');
163
+ requireThat(ids.length >= 1 && ids.length <= 50 && ids.every(id => /^[A-Za-z0-9._:-]{4,128}$/.test(id)),
164
+ 'invalid_task_ids', 'Pass --ids with 1-50 comma-separated task IDs.');
165
+ return [...new Set(ids)];
166
+ }
167
+
108
168
  async function estimateArgs(options) {
109
169
  requireThat(options.model, 'missing_model', 'Pass --model.');
110
170
  requireThat(!(options.input && options['input-file']), 'invalid_input', 'Choose --input or --input-file.');
111
171
  let input = {};
112
- try { input = JSON.parse(options['input-file'] ? await fs.readFile(options['input-file'], 'utf8') : options.input || '{}'); }
113
- catch { throw new CliError('invalid_input', 'The input must be a JSON object or a readable JSON file.'); }
172
+ const raw = options['input-file'] ? await localFile(() => fs.readFile(options['input-file'], 'utf8'), { file: options['input-file'] }) : options.input || '{}';
173
+ try { input = JSON.parse(raw); }
174
+ catch { throw new CliError('invalid_input', 'The input must contain valid JSON.'); }
114
175
  requireThat(input && typeof input === 'object' && !Array.isArray(input), 'invalid_input', 'The model input must be a JSON object.');
115
176
  if (options.prompt !== undefined) {
116
177
  requireThat(input.prompt === undefined || input.prompt === options.prompt, 'invalid_input', 'prompt was supplied twice with different values.');
@@ -125,15 +186,27 @@ export async function dispatch(positionals, options, { state, server, credential
125
186
  const [command, action, id] = positionals;
126
187
  const media = new Media({ mcp, state, server });
127
188
  if (command === 'auth') {
128
- if (action === 'login') return credentials.login({ noBrowser: options['no-browser'], signal, progress });
189
+ if (action === 'login') return credentials.login({ noBrowser: options['no-browser'], timeout: options.timeout === undefined ? undefined : Number(options.timeout) * 1000, signal, progress });
129
190
  if (action === 'status') return credentials.status();
130
191
  if (action === 'logout') return credentials.logout();
131
192
  }
132
193
  if (command === 'balance') return mcp.call('check_balance');
133
194
  if (command === 'models') {
134
195
  if (action === 'show' && id) return mcp.call('get_model', { model: id });
135
- if (action === 'search') return mcp.call('search_models', { type: options.type || 'all', query: options.query, limit: number(options.limit, 'limit', 1, 50, true) || 20 });
196
+ if (action === 'schema' && id) {
197
+ const model = await mcp.call('get_model', { model: id });
198
+ requireThat(model.input_schema, 'schema_unavailable', 'The service has no versioned input schema for this model. Use models show for documented parameters; ask for the MCP service update if needed.');
199
+ return model;
200
+ }
201
+ if (action === 'search') return mcp.call('search_models', { type: options.type || 'all', query: options.query, limit: number(options.limit, 'limit', 1, 50, true) || 20,
202
+ ...(options.page !== undefined ? { page: Number(options.page) } : {}) },
203
+ options.page !== undefined ? { requireCapability: true, requiredInputs: ['page'] } : undefined);
204
+ if (action === 'recommend') return mcp.call('recommend_models', { type: options.type, query: options.query,
205
+ references: options.references ? references(options.references) : [], limit: number(options.limit, 'limit', 1, 10, true) || 3 }, { requireCapability: true });
136
206
  }
207
+ if (command === 'docs') return mcp.call('search_docs', { query: options.query, type: options.type || 'all', limit: number(options.limit, 'limit', 1, 20, true) || 5 }, { requireCapability: true });
208
+ if (command === 'usage') return mcp.call('get_task_usage', { since: options.since || '30d', until: options.until, model: options.model, type: options.type,
209
+ max_pages: number(options['max-pages'], 'max-pages', 1, 20, true) || 5 }, { requireCapability: true });
137
210
  if (command === 'estimate') return media.estimate(await estimateArgs(options));
138
211
  if (command === 'generate') {
139
212
  requireThat(options.quote, 'missing_quote', 'Run estimate and obtain user approval before generation.');
@@ -149,7 +222,12 @@ export async function dispatch(positionals, options, { state, server, credential
149
222
  if (action === 'get' && id) return mcp.call('get_task', { task_id: id, wait_seconds: 0 });
150
223
  if (action === 'wait' && id) return media.wait(id, { timeout: number(options.timeout, 'timeout', 1, 86400, true) || 1800, signal, progress });
151
224
  if (action === 'resume' && options.quote) return media.resume(options.quote);
152
- if (action === 'list') return mcp.call('list_tasks', { type: options.type, status: options.status, since: options.since, limit: number(options.limit, 'limit', 1, 50, true) || 20 });
225
+ if (action === 'batch') return mcp.call('list_tasks', { task_ids: taskIds(options.ids) });
226
+ if (action === 'list') {
227
+ const added = Object.fromEntries(['model', 'until', 'page'].filter(key => options[key] !== undefined).map(key => [key, key === 'page' ? Number(options[key]) : options[key]]));
228
+ return mcp.call('list_tasks', { type: options.type, status: options.status, since: options.since, limit: number(options.limit, 'limit', 1, 50, true) || 20, ...added },
229
+ Object.keys(added).length ? { requireCapability: true, requiredInputs: Object.keys(added) } : undefined);
230
+ }
153
231
  }
154
232
  if (command === 'upload' && action) return upload(action, { mcp, state, server, signal, upload_path: options['upload-path'] });
155
233
  if (command === 'uploads' && action === 'get' && id) {
@@ -159,15 +237,15 @@ export async function dispatch(positionals, options, { state, server, credential
159
237
  return { ...view, text: upload_url ? 'The upload is waiting for its original one-time PUT. No address is exposed by this recovery query.' : text };
160
238
  }
161
239
  if (command === 'download' && action) {
240
+ if (options.all) return downloadAll(action, options['output-dir'], { mcp, server, state, signal, template: options.template, resume: options.resume });
162
241
  requireThat(options.output, 'missing_output', 'Pass --output with a new local file path.');
163
242
  return download(action, options.output, { mcp, server, signal, index: number(options.index, 'index', 1, 50, true) || 1 });
164
243
  }
165
- if (command === 'skills' && action === 'install') return installSkill({ home: skillHome, agent: options.agent });
166
- if (command === 'doctor') {
167
- const status = await credentials.status();
168
- const balance = await mcp.call('check_balance');
169
- return { node: process.version, server: server.href, auth: status, connection_verified: balance.ok === true };
170
- }
244
+ if (command === 'skills' && action === 'install') return installSkill({ home: skillHome, agent: options.agent, replaceModified: options['replace-modified'] });
245
+ if (command === 'skills' && action === 'status') return skillStatus({ home: skillHome, agent: options.agent });
246
+ if (command === 'setup') return setup({ state, server, credentials, mcp, agent: options.agent, skillHome,
247
+ noBrowser: options['no-browser'], timeout: options.timeout === undefined ? undefined : Number(options.timeout) * 1000, signal, progress });
248
+ if (command === 'doctor') return doctor({ state, server, credentials, mcp, agent: options.agent, skillHome });
171
249
  throw new CliError('unknown_command', 'Unknown command or missing argument. Run evolink --help.');
172
250
  }
173
251
 
@@ -196,10 +274,11 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
196
274
  let positionals;
197
275
  try { ({ values: options, positionals } = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true })); }
198
276
  catch { throw new CliError('invalid_option', 'Invalid command option. Run evolink --help.'); }
199
- if (options.version) { io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, version: '0.5.1' }) + '\n' : '0.5.1\n'); return; }
277
+ if (options.version) { io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, version: CLI_VERSION }) + '\n' : CLI_VERSION + '\n'); return; }
200
278
  if (options.help || !positionals.length) {
201
- const help = options.help && positionals.length === 2 && positionals[0] === 'tasks' && positionals[1] === 'list' ? TASKS_LIST_HELP : HELP;
202
- io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, help }) + '\n' : help); return;
279
+ const reference = commandHelp(positionals);
280
+ const help = options.help && positionals.length === 2 && positionals[0] === 'tasks' && positionals[1] === 'list' ? TASKS_LIST_HELP : reference?.help || HELP;
281
+ io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, ...reference, help }) + '\n' : help); return;
203
282
  }
204
283
  validateCommand(positionals, options);
205
284
  const server = serverURL(options.server);
@@ -208,8 +287,9 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
208
287
  const credentials = new Credentials({ server, state, token });
209
288
  const mcp = new Mcp(credentials, { signal: controller.signal });
210
289
  const result = publicView(await dispatch(positionals, options, { state, server, credentials, mcp, signal: controller.signal, progress: message => io.stderr.write(message + '\n') }));
211
- const view = { schema_version: 1, ...result, ok: true };
290
+ const view = { schema_version: 1, ...result, ok: result.ok !== false };
212
291
  io.stdout.write(options.json ? JSON.stringify(view) + '\n' : `${result.text || JSON.stringify(view, null, 2)}\n${result.quote_id ? `Quote: ${result.quote_id}\n` : ''}`);
292
+ if (!view.ok) process.exitCode = view.error?.code === 'interrupted' ? 130 : 1;
213
293
  } catch (error) {
214
294
  const view = { schema_version: 1, ok: false, error: errorView(error) };
215
295
  (options.json ? io.stdout : io.stderr).write(options.json ? JSON.stringify(view) + '\n' : `${view.error.code}: ${view.error.message}\n${view.error.details ? JSON.stringify(view.error.details, null, 2) + '\n' : ''}`);
package/src/doctor.mjs ADDED
@@ -0,0 +1,66 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { CliError, errorView, requireThat } from './errors.mjs';
4
+ import { skillStatus } from './skills.mjs';
5
+ import { CLI_VERSION } from './version.mjs';
6
+
7
+ export async function prerequisites({ state, credentials, version = process.version, platform = process.platform }) {
8
+ const checks = [];
9
+ async function check(name, action) {
10
+ try { const details = await action(); checks.push({ name, status: 'passed', ...details }); return details; }
11
+ catch (error) { checks.push({ name, status: 'failed', error: errorView(error) }); }
12
+ }
13
+ const runtime = await check('runtime', async () => {
14
+ requireThat(Number(version.replace(/^v/, '').split('.')[0]) >= 22, 'unsupported_runtime', 'Install Node.js 22 or newer before using this CLI.');
15
+ return { version, platform, cli_version: CLI_VERSION };
16
+ });
17
+ const storage = await check('local_state', async () => {
18
+ await fs.mkdir(state.home, { recursive: true, mode: 0o700 });
19
+ const probe = await fs.mkdtemp(path.join(state.home, '.doctor-'));
20
+ try { await fs.writeFile(path.join(probe, 'probe'), 'EvoLink diagnostic', { mode: 0o600 }); }
21
+ finally { await fs.rm(probe, { recursive: true, force: true }); }
22
+ return { writable: true };
23
+ });
24
+ const auth = await check('credential_storage', () => credentials.status());
25
+ return { runtime, storage, auth, checks };
26
+ }
27
+ export async function verifyModels(mcp) {
28
+ const result = await mcp.call('search_models', { type: 'all', limit: 1 });
29
+ requireThat(result.ok === true && Array.isArray(result.models), 'model_catalog_unavailable', 'The model catalog could not be verified. Retry evolink models search --json.');
30
+ requireThat(result.models.length > 0, 'model_catalog_empty', 'No models are currently available for this connection. Retry model discovery later.');
31
+ return { verified: true, models_available: true };
32
+ }
33
+ export async function doctor({ state, server, credentials, mcp, version = process.version, platform = process.platform,
34
+ remote = !!process.env.SSH_CONNECTION, agent, skillHome }) {
35
+ const { runtime, storage, auth, checks } = await prerequisites({ state, credentials, version, platform });
36
+ const login = auth?.authenticated === true;
37
+ if (auth) checks.push(login ? { name: 'login', status: 'passed' } : {
38
+ name: 'login', status: 'failed', error: errorView(new CliError('login_required', 'Run evolink auth login, finish browser approval, then run doctor again.')),
39
+ });
40
+ else checks.push({ name: 'login', status: 'skipped', reason: 'Credential storage must be available before checking the saved login.' });
41
+ let connected = false, models = false;
42
+ if (runtime && storage && login) {
43
+ try {
44
+ const result = await mcp.call('check_balance');
45
+ requireThat(result.ok === true, 'connection_failed', 'Balance verification failed. Retry evolink balance --json.');
46
+ connected = true; checks.push({ name: 'connection', status: 'passed', verified: true });
47
+ } catch (error) { checks.push({ name: 'connection', status: 'failed', error: errorView(error) }); }
48
+ } else checks.push({ name: 'connection', status: 'skipped', reason: 'Fix the failed prerequisite checks before verifying the account connection.' });
49
+ if (connected) {
50
+ try { const details = await verifyModels(mcp); models = true; checks.push({ name: 'models', status: 'passed', ...details }); }
51
+ catch (error) { checks.push({ name: 'models', status: 'failed', error: errorView(error) }); }
52
+ } else checks.push({ name: 'models', status: 'skipped', reason: 'Verify the account connection first.' });
53
+ let skills;
54
+ if (agent !== undefined) {
55
+ try {
56
+ skills = await skillStatus({ home: skillHome, agent });
57
+ checks.push({ name: 'skills', status: skills.current ? 'passed' : 'failed', ...skills });
58
+ } catch (error) { checks.push({ name: 'skills', status: 'failed', error: errorView(error) }); }
59
+ }
60
+ const guidance = [];
61
+ if (platform === 'linux') guidance.push('Linux needs an unlocked Secret Service keyring in the current D-Bus session. Run login and later commands in that same session; tokens are never saved to plaintext files.');
62
+ if (remote) guidance.push('SSH login redirects the browser to 127.0.0.1 on the CLI host. Use SSH local port forwarding for the callback port printed in the authorization link, or run the CLI on your local computer. --no-browser only prints the link; it does not forward the callback.');
63
+ return { ok: !!runtime && !!storage && connected && models && (agent === undefined || skills?.current === true),
64
+ cli_version: CLI_VERSION, node: version, server: server.href, ...(auth ? { auth } : {}),
65
+ connection_verified: connected, model_discovery_verified: models, assistant_discovery: 'not_checked', checks, guidance };
66
+ }
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,13 @@
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, errorView } from './errors.mjs';
9
+ import { hash } from './state.mjs';
10
+ import { checkContentType, checkMediaPrefix } from './media-content.mjs';
9
11
 
10
12
  const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp',
11
13
  '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.aac': 'audio/aac', '.flac': 'audio/flac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg',
@@ -13,10 +15,11 @@ const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
13
15
 
14
16
  export async function upload(file, { mcp, state, server, signal, upload_path, fetchFn = fetch }) {
15
17
  const full = path.resolve(file);
16
- const stat = await fs.stat(full);
18
+ const stat = await localFile(() => fs.stat(full), { file: full });
17
19
  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
20
  const type = MIME[path.extname(full).toLowerCase()];
19
21
  requireThat(type, 'unsupported_file', 'This file format is not supported. Use JPEG, PNG, GIF, WebP, supported audio, MP4, MOV or WebM.');
22
+ await localFile(() => fs.access(full, constants.R_OK), { file: full });
20
23
  const prepared = await mcp.call('prepare_upload', { file_name: path.basename(full), ...(upload_path ? { upload_path } : {}) });
21
24
  requireThat(stat.size <= prepared.max_bytes, 'file_too_large', 'This file exceeds the upload limit.');
22
25
  const destination = new URL(prepared.upload_url);
@@ -43,25 +46,41 @@ export async function upload(file, { mcp, state, server, signal, upload_path, fe
43
46
  }
44
47
  }
45
48
 
46
- export async function download(taskId, output, { mcp, server, index = 1, signal, maxBytes = 1024 ** 3, fetchFn }) {
47
- const task = await mcp.call('get_task', { task_id: taskId, wait_seconds: 0 });
49
+ export async function download(taskId, output, { mcp, server, index = 1, signal, maxBytes = 1024 ** 3, fetchFn, task: suppliedTask, beforeCommit }) {
50
+ const target = path.resolve(output);
51
+ const parent = await localFile(() => fs.stat(path.dirname(target)), { file: target, missing: 'output_directory_missing' });
52
+ requireThat(parent.isDirectory(), 'path_not_directory', 'The output parent is not a directory. Choose a valid file path.');
53
+ await localFile(() => fs.access(path.dirname(target), constants.W_OK), { file: target });
54
+ try { await fs.lstat(target); throw new CliError('file_exists', 'The output file already exists. Choose another path.'); }
55
+ catch (e) { if (e.code !== 'ENOENT') throw fileError(e, { file: target }); }
56
+ const task = suppliedTask ?? await mcp.call('get_task', { task_id: taskId, wait_seconds: 0 });
48
57
  requireThat(task.status === 'completed', 'task_not_ready', 'Wait for the task to complete before downloading.');
49
58
  const result = task.results?.[index - 1];
50
59
  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
60
  const temp = `${target}.${randomUUID()}.part`;
53
61
  let bytes = 0;
62
+ let prefix = Buffer.alloc(0), inspected = false, contentType;
54
63
  const digest = createHash('sha256');
55
64
  const guard = new Transform({ transform(chunk, encoding, callback) {
56
65
  bytes += chunk.length;
57
66
  if (bytes > maxBytes) { callback(new CliError('download_too_large', 'The download exceeded the size limit.')); return; }
67
+ if (!inspected) {
68
+ prefix = Buffer.concat([prefix, chunk.subarray(0, 512 - prefix.length)]);
69
+ if (prefix.length === 512) {
70
+ try { checkMediaPrefix(prefix, result.kind, contentType); inspected = true; }
71
+ catch (error) { callback(error); return; }
72
+ }
73
+ }
58
74
  digest.update(chunk); callback(null, chunk);
75
+ }, flush(callback) {
76
+ try { if (!inspected && bytes > 0) checkMediaPrefix(prefix, result.kind, contentType); callback(); }
77
+ catch (error) { callback(error); }
59
78
  } });
60
79
  const timeoutSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(600_000)]) : AbortSignal.timeout(600_000);
61
80
  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
81
  const response = await resultFetch(result.url, { testOrigin: loopback(server) ? server.origin : undefined, signal: timeoutSignal, fetchFn });
82
+ try { contentType = checkContentType(response.headers.get('content-type'), result.kind); }
83
+ catch (error) { await response.body?.cancel(); throw error; }
65
84
  const length = Number(response.headers.get('content-length'));
66
85
  if (Number.isFinite(length) && length > maxBytes) {
67
86
  await response.body?.cancel();
@@ -70,7 +89,100 @@ export async function download(taskId, output, { mcp, server, index = 1, signal,
70
89
  requireThat(response.body, 'download_failed', 'The file service returned an empty response.');
71
90
  await pipeline(Readable.fromWeb(response.body), guard, createWriteStream(temp, { flags: 'wx', mode: 0o600 }), { signal: timeoutSignal });
72
91
  requireThat(bytes > 0, 'download_failed', 'The file service returned an empty file.');
92
+ const receipt = { task_id: taskId, result_index: index, path: target, size_bytes: bytes, sha256: digest.digest('hex'), kind: result.kind };
93
+ await beforeCommit?.(receipt);
73
94
  await fs.link(temp, target);
74
- 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(() => {}); }
95
+ return receipt;
96
+ } catch (error) { throw fileError(error, { file: target, missing: 'output_directory_missing' }); }
97
+ finally { await fs.unlink(temp).catch(() => {}); }
98
+ }
99
+
100
+ export function downloadNames(taskId, results, template = '{task_id}-{index}.{ext}') {
101
+ requireThat(typeof template === 'string' && template.length > 0 && template.length <= 200 && !/[\\/\x00-\x1f]/.test(template),
102
+ 'invalid_template', 'Use a filename template, without directory separators. Placeholders: {task_id}, {index}, {kind}, {ext}.');
103
+ const names = results.map((result, index) => {
104
+ let extension;
105
+ try { extension = path.extname(new URL(result.url).pathname).toLowerCase(); } catch {}
106
+ const ext = MIME[extension] ? extension.slice(1) : 'bin';
107
+ const values = { task_id: String(taskId).replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 128), index: String(index + 1), kind: result.kind, ext };
108
+ const name = template.replace(/\{(task_id|index|kind|ext)\}/g, (_, key) => values[key]);
109
+ requireThat(name.length <= 240 && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) && !name.includes('..')
110
+ && !/[. ]$/.test(name) && !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name),
111
+ 'invalid_template', 'The template must produce portable filenames with letters, digits, dots, underscores or hyphens.');
112
+ return name;
113
+ });
114
+ requireThat(new Set(names.map(name => name.toLowerCase())).size === names.length, 'duplicate_output_path', 'The template must produce a different filename for every result; include {index}.');
115
+ return names;
116
+ }
117
+
118
+ /** Recovery checks saved file digests; it never treats an unrelated existing file as a delivered result. */
119
+ export async function downloadAll(taskId, directory, { mcp, server, state, signal, template, resume = false, fetchFn }) {
120
+ const target = path.resolve(directory);
121
+ const receiptId = hash({ taskId, server: server.href, target });
122
+ return state.lock(`delivery-${receiptId}`, async () => {
123
+ const task = await mcp.call('get_task', { task_id: taskId, wait_seconds: 0 });
124
+ requireThat(task.status === 'completed', 'task_not_ready', 'Wait for the task to complete before downloading.');
125
+ requireThat(Array.isArray(task.results) && task.results.length > 0 && task.results.length <= 50,
126
+ 'invalid_result_count', 'Download all requires between 1 and 50 result links. Use individual downloads for larger tasks.');
127
+ const names = downloadNames(taskId, task.results, template);
128
+ const sources = task.results.map(result => {
129
+ const url = new URL(result.url);
130
+ return hash({ kind: result.kind, origin: url.origin, path: url.pathname });
131
+ });
132
+ let receipt = await state.read('deliveries', receiptId);
133
+ if (resume) {
134
+ requireThat(receipt && receipt.task_id === taskId && receipt.directory === target && receipt.server === server.href
135
+ && Array.isArray(receipt.files) && hash(receipt.names) === hash(names) && hash(receipt.sources) === hash(sources),
136
+ 'delivery_receipt_mismatch', 'No matching delivery receipt exists, or the task outputs/template changed. Keep the task ID; choose a new directory for a fresh download.');
137
+ } else {
138
+ requireThat(!receipt, 'delivery_exists', 'This task already has a delivery receipt for this directory. Use --resume to verify saved files and download the remainder.');
139
+ receipt = { task_id: taskId, directory: target, server: server.href, names, sources, files: [] };
140
+ }
141
+ await localFile(() => fs.mkdir(target, { recursive: true, mode: 0o700 }), { file: target });
142
+ requireThat((await fs.stat(target)).isDirectory(), 'path_not_directory', 'Choose an output directory.');
143
+ await state.write('deliveries', receiptId, receipt);
144
+ const failures = [], downloaded = [];
145
+ for (let index = 1; index <= names.length; index++) {
146
+ const file = path.join(target, names[index - 1]);
147
+ try {
148
+ requireThat(!signal?.aborted, 'interrupted', 'Stopped downloading locally. The completed EvoLink task is unchanged.');
149
+ let saved = receipt.files.find(item => item.result_index === index);
150
+ if (saved?.pending_commit) {
151
+ try { await fs.lstat(file); }
152
+ catch (error) {
153
+ if (error.code !== 'ENOENT') throw error;
154
+ receipt.files = receipt.files.filter(item => item.result_index !== index);
155
+ await state.write('deliveries', receiptId, receipt);
156
+ saved = undefined;
157
+ }
158
+ }
159
+ if (saved) {
160
+ const stat = await localFile(() => fs.lstat(file), { file });
161
+ requireThat(saved.path === file && /^[a-f0-9]{64}$/.test(saved.sha256) && stat.isFile() && stat.size === saved.size_bytes,
162
+ 'saved_file_changed', 'A previously downloaded file changed. It will not be overwritten. Choose a new output directory.');
163
+ const digest = createHash('sha256');
164
+ for await (const bytes of createReadStream(file, { signal })) digest.update(bytes);
165
+ requireThat(digest.digest('hex') === saved.sha256, 'saved_file_changed', 'A previously downloaded file changed. It will not be overwritten. Choose a new output directory.');
166
+ if (saved.pending_commit) { saved.pending_commit = false; await state.write('deliveries', receiptId, receipt); }
167
+ downloaded.push({ ...saved, verified_existing: true });
168
+ } else {
169
+ const result = await download(taskId, file, { mcp, server, index, signal, fetchFn, task, beforeCommit: async pending => {
170
+ receipt.files.push({ ...pending, pending_commit: true });
171
+ await state.write('deliveries', receiptId, receipt);
172
+ } });
173
+ Object.assign(receipt.files.find(item => item.result_index === index), result, { pending_commit: false });
174
+ await state.write('deliveries', receiptId, receipt);
175
+ downloaded.push(result);
176
+ }
177
+ } catch (error) {
178
+ failures.push({ result_index: index, path: file, error: errorView(error) });
179
+ if (signal?.aborted) break;
180
+ }
181
+ }
182
+ const complete = downloaded.length === names.length && failures.length === 0;
183
+ return { ok: complete, task_id: taskId, generation_status: 'completed', delivery_status: complete ? 'completed' : 'partial',
184
+ files: downloaded, failures, result_count: names.length, receipt_id: receiptId,
185
+ ...(signal?.aborted ? { error: { code: 'interrupted' } } : {}),
186
+ text: `${downloaded.length}/${names.length} original files verified or downloaded.${complete ? '' : ' Delivery is incomplete. Keep this task ID; retry download --all with the same directory/template and --resume. Do not generate again.'}` };
187
+ });
76
188
  }