@evolinkai/cli 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +65 -5
  2. package/package.json +27 -8
  3. package/skills/evolink-cli/SKILL.md +11 -4
  4. package/skills/evolink-cli/references/capabilities.md +38 -0
  5. package/skills/evolink-cli/references/usage-and-budget.md +17 -0
  6. package/src/api.mjs +55 -0
  7. package/src/auth.mjs +6 -7
  8. package/src/cli.mjs +96 -29
  9. package/src/doctor.mjs +9 -6
  10. package/src/files.mjs +143 -7
  11. package/src/help.mjs +68 -0
  12. package/src/media.mjs +9 -7
  13. package/src/network.mjs +12 -1
  14. package/src/oauth.mjs +82 -0
  15. package/src/platform/LICENSE +178 -0
  16. package/src/platform/NOTICE +6 -0
  17. package/src/platform/core/src/config.js +92 -0
  18. package/src/platform/core/src/data/model-constraints.js +37 -0
  19. package/src/platform/core/src/data/model-params.generated.js +4 -0
  20. package/src/platform/core/src/data/model-params.js +28 -0
  21. package/src/platform/core/src/platform-client.js +50 -0
  22. package/src/platform/core/src/platform-operations.js +22 -0
  23. package/src/platform/core/src/request-context.js +53 -0
  24. package/src/platform/core/src/services/api-client.js +205 -0
  25. package/src/platform/core/src/services/catalog-client.js +45 -0
  26. package/src/platform/core/src/services/error-handler.js +404 -0
  27. package/src/platform/core/src/services/file-client.js +133 -0
  28. package/src/platform/core/src/services/http-policy.js +136 -0
  29. package/src/platform/core/src/services/model-capabilities.js +24 -0
  30. package/src/platform/core/src/services/model-catalog.js +68 -0
  31. package/src/platform/core/src/services/model-recommendations.js +35 -0
  32. package/src/platform/core/src/services/param-validator.js +201 -0
  33. package/src/platform/core/src/services/pricing-client.js +451 -0
  34. package/src/platform/core/src/services/utm.js +65 -0
  35. package/src/platform/core/src/tool-guidance.js +50 -0
  36. package/src/platform/core/src/tools/check-balance.js +90 -0
  37. package/src/platform/core/src/tools/discovery.js +86 -0
  38. package/src/platform/core/src/tools/estimate-cost.js +136 -0
  39. package/src/platform/core/src/tools/generate.js +234 -0
  40. package/src/platform/core/src/tools/get-model.js +146 -0
  41. package/src/platform/core/src/tools/get-task.js +57 -0
  42. package/src/platform/core/src/tools/list-tasks.js +170 -0
  43. package/src/platform/core/src/tools/search-models.js +115 -0
  44. package/src/platform/core/src/tools/shared.js +138 -0
  45. package/src/platform/core/src/tools/task-format.js +245 -0
  46. package/src/platform/core/src/tools/task-usage.js +108 -0
  47. package/src/platform/core/src/version.js +4 -0
  48. package/src/platform/source.json +80 -0
  49. package/src/setup.mjs +9 -5
  50. package/src/mcp.mjs +0 -36
package/src/cli.mjs CHANGED
@@ -3,9 +3,10 @@ import * as fs from 'node:fs/promises';
3
3
  import { State } from './state.mjs';
4
4
  import { serverURL } from './network.mjs';
5
5
  import { Credentials } from './auth.mjs';
6
- import { Mcp } from './mcp.mjs';
6
+ import { Api } from './api.mjs';
7
7
  import { Media } from './media.mjs';
8
- import { upload, download } from './files.mjs';
8
+ import { upload, download, downloadAll, getUpload } from './files.mjs';
9
+ import { commandHelp } from './help.mjs';
9
10
  import { installSkill, skillStatus, validateAgent } from './skills.mjs';
10
11
  import { doctor } from './doctor.mjs';
11
12
  import { setup } from './setup.mjs';
@@ -24,13 +25,17 @@ Read recent tasks across your EvoLink account (free), newest first.
24
25
  --status STATUS ${TASK_STATUS_FILTERS.join('|')}
25
26
  --type TYPE image|video|audio; omit to include all media types
26
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
30
+ --page N Page number, 1-100000 (default 1)
27
31
  --limit N Integer from 1 to 50 (default 20)
28
32
  --json Return one JSON envelope on stdout
29
33
 
30
34
  ${TASK_STATUS_HELP}
31
35
  Filters are case-sensitive. A returned task status can be pending;
32
36
  response statuses are not the same as allowed --status filters.
33
- --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.
34
39
  An empty list does not prove an uncertain submission created no task.
35
40
  cancelled is a read filter; the CLI does not provide a cancel command.
36
41
  Connection options: --server URL, --token-stdin.
@@ -51,20 +56,30 @@ const HELP = `EvoLink CLI ${CLI_VERSION} (Node.js 22+)
51
56
  balance Verify connection and account balance (free)
52
57
  models search [--query TEXT] [--type image|video|audio|all] [--limit N]
53
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)
54
62
  estimate --model MODEL --input-file FILE [--max-cost-usd USD] [--media-seconds N]
55
63
  generate image|video|audio --quote ID --confirm [--wait] [--timeout SECONDS]
56
64
  tasks get ID | tasks wait ID [--timeout SECONDS]
57
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)
58
70
  tasks resume --quote ID Recover using the original request ID
59
71
  upload FILE [--upload-path FOLDER]
60
- uploads get ID Recover a lost upload result (free)
72
+ uploads get ID Read a saved upload receipt (free)
61
73
  download TASK_ID --output FILE [--index N]
74
+ download TASK_ID --all --output-dir DIR [--template NAME] [--resume]
62
75
  skills install [--agent NAME] [--replace-modified]
63
76
  Install or update; back up replaced files
64
77
  skills status [--agent NAME] Check installed skill content and CLI version
65
78
  doctor [--agent NAME] Check prerequisites, connection, models and skills (free)
66
79
 
67
- Options: --json, --server URL, --token-stdin, --help, --version
80
+ Options: --json, --server RESOURCE_URL, --api-url URL, --files-url URL,
81
+ --token-stdin, --help, --version
82
+ The CLI calls the platform API directly. --server identifies the OAuth resource.
68
83
  Agents: all (default), codex, claude-code, cursor, gemini, opencode, copilot,
69
84
  openclaw, hermes.
70
85
  Input: --input JSON or --input-file FILE, plus optional --prompt TEXT.
@@ -72,6 +87,8 @@ ${TASK_STATUS_HELP}
72
87
  Task list types: image, video, audio; omit --type to include all types.
73
88
  Task list example: evolink tasks list --status processing --json
74
89
  Run evolink tasks list --help for filter details and recovery caveats.
90
+ Each command accepts --help --json for its machine-readable command reference.
91
+ Model/docs/usage capabilities come from the bundled shared platform module.
75
92
  After upgrading the package, run evolink skills install to refresh its skill.
76
93
 
77
94
  Login timeout: 30-900 seconds, default 180. On SSH, forward the callback port.
@@ -81,9 +98,9 @@ Spending caps protect the estimate at submission, not final settlement.
81
98
  Ctrl-C stops local waiting; submitted tasks continue on EvoLink.
82
99
  `;
83
100
 
84
- const OPTIONS = Object.fromEntries(['server', 'query', 'type', 'limit', 'model', 'input', 'input-file', 'prompt', 'media-seconds',
85
- 'max-cost-usd', 'quote', 'timeout', 'status', 'since', 'output', 'index', 'upload-path', 'agent'].map(k => [k, { type: 'string' }]));
86
- for (const k of ['json', 'token-stdin', 'no-browser', 'replace-modified', 'confirm', 'wait', 'help', 'version']) OPTIONS[k] = { type: 'boolean' };
101
+ const OPTIONS = Object.fromEntries(['server', 'api-url', 'files-url', 'query', 'type', 'limit', 'model', 'input', 'input-file', 'prompt', 'media-seconds',
102
+ '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' }]));
103
+ for (const k of ['json', 'token-stdin', 'no-browser', 'replace-modified', 'confirm', 'wait', 'all', 'resume', 'help', 'version']) OPTIONS[k] = { type: 'boolean' };
87
104
 
88
105
  function number(value, name, min, max, integer = false) {
89
106
  if (value === undefined) return undefined;
@@ -97,22 +114,37 @@ export function validateCommand(args, options) {
97
114
  const routes = {
98
115
  setup: [1, 'agent', 'no-browser', 'timeout'],
99
116
  'auth login': [2, 'no-browser', 'timeout'], 'auth status': [2], 'auth logout': [2], balance: [1],
100
- 'models search': [2, 'query', 'type', 'limit'], 'models show': [3],
117
+ 'models search': [2, 'query', 'type', 'limit', 'page'], 'models show': [3], 'models schema': [3],
118
+ 'models recommend': [2, 'type', 'query', 'references', 'limit'], 'docs search': [2, 'query', 'type', 'limit'],
119
+ usage: [1, 'since', 'until', 'type', 'model', 'max-pages'],
101
120
  estimate: [1, 'model', 'input', 'input-file', 'prompt', 'media-seconds', 'max-cost-usd'],
102
121
  'generate image': [2, 'quote', 'confirm', 'wait', 'timeout'], 'generate video': [2, 'quote', 'confirm', 'wait', 'timeout'], 'generate audio': [2, 'quote', 'confirm', 'wait', 'timeout'],
103
- 'tasks get': [3], 'tasks wait': [3, 'timeout'], 'tasks list': [2, 'type', 'status', 'since', 'limit'], 'tasks resume': [2, 'quote'],
104
- upload: [2, 'upload-path'], 'uploads get': [3], download: [2, 'output', 'index'],
122
+ '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'],
123
+ upload: [2, 'upload-path'], 'uploads get': [3], download: [2, 'output', 'index', 'all', 'output-dir', 'template', 'resume'],
105
124
  'skills install': [2, 'agent', 'replace-modified'], 'skills status': [2, 'agent'], doctor: [1, 'agent'],
106
125
  };
107
126
  const route = routes[`${command} ${action}`] || routes[command];
108
127
  requireThat(route && args.length === route[0], 'unknown_command', 'Unknown command or argument count. Run evolink --help.');
109
- const allowed = new Set(['json', 'server', 'token-stdin', ...route.slice(1)]);
128
+ const allowed = new Set(['json', 'server', 'api-url', 'files-url', 'token-stdin', ...route.slice(1)]);
110
129
  requireThat(Object.keys(options).every(k => allowed.has(k)), 'invalid_option', 'An option does not apply to this command. Run evolink --help.');
111
130
  if (options.agent !== undefined) validateAgent(options.agent);
112
131
  if (options.timeout !== undefined) number(options.timeout, 'timeout', command === 'setup' || command === 'auth' ? 30 : 1,
113
132
  command === 'setup' || command === 'auth' ? 900 : 86400, true);
114
133
  requireThat(!(command === 'setup' && options['token-stdin']), 'invalid_option', 'setup uses the saved OS login. Use balance or doctor for a one-command stdin token.');
115
- if (options.type !== undefined) requireThat(['image', 'video', 'audio', ...(command === 'models' ? ['all'] : [])].includes(options.type), 'invalid_type', 'Unsupported media type.');
134
+ if (options.type !== undefined) requireThat(['image', 'video', 'audio', ...(command === 'docs' || (command === 'models' && action === 'search') ? ['all'] : [])].includes(options.type), 'invalid_type', 'Unsupported media type.');
135
+ if (options.page !== undefined) number(options.page, 'page', 1, 100000, true);
136
+ if (options['max-pages'] !== undefined) number(options['max-pages'], 'max-pages', 1, 20, true);
137
+ if (options.limit !== undefined) number(options.limit, 'limit', 1, command === 'docs' ? 20 : action === 'recommend' ? 10 : 50, true);
138
+ if (command === 'models' && action === 'recommend') {
139
+ requireThat(options.type, 'missing_type', 'Pass --type image, video or audio.');
140
+ if (options.references !== undefined) references(options.references);
141
+ }
142
+ if (command === 'docs') requireThat(options.query?.trim(), 'missing_query', 'Pass --query with model reference keywords.');
143
+ if (command === 'tasks' && action === 'batch') taskIds(options.ids);
144
+ if (command === 'download') {
145
+ requireThat(options.all ? options['output-dir'] && !options.output && !options.index : options.output && !options['output-dir'] && !options.template && !options.resume,
146
+ 'invalid_option', 'Choose --output FILE [--index N], or --all --output-dir DIR [--template NAME] [--resume].');
147
+ }
116
148
  if (options.status !== undefined) requireThat(TASK_STATUS_FILTERS.includes(options.status), 'invalid_status',
117
149
  `Unsupported task status filter. ${TASK_STATUS_HELP}`, {
118
150
  param: 'status', value: options.status, allowed_values: TASK_STATUS_FILTERS,
@@ -121,6 +153,20 @@ export function validateCommand(args, options) {
121
153
  });
122
154
  }
123
155
 
156
+ function references(value) {
157
+ const kinds = value.split(',');
158
+ requireThat(kinds.length >= 1 && kinds.length <= 3 && kinds.every(kind => ['image', 'video', 'audio'].includes(kind)),
159
+ 'invalid_references', 'Use comma-separated reference kinds: image, video, audio.');
160
+ return [...new Set(kinds)];
161
+ }
162
+
163
+ function taskIds(value) {
164
+ const ids = (value ?? '').split(',');
165
+ requireThat(ids.length >= 1 && ids.length <= 50 && ids.every(id => /^[A-Za-z0-9._:-]{4,128}$/.test(id)),
166
+ 'invalid_task_ids', 'Pass --ids with 1-50 comma-separated task IDs.');
167
+ return [...new Set(ids)];
168
+ }
169
+
124
170
  async function estimateArgs(options) {
125
171
  requireThat(options.model, 'missing_model', 'Pass --model.');
126
172
  requireThat(!(options.input && options['input-file']), 'invalid_input', 'Choose --input or --input-file.');
@@ -138,19 +184,32 @@ async function estimateArgs(options) {
138
184
  return { model: options.model, input, ...(media !== undefined ? { media_seconds: media } : {}), ...(cap !== undefined ? { max_cost_usd: cap } : {}) };
139
185
  }
140
186
 
141
- export async function dispatch(positionals, options, { state, server, credentials, mcp, signal, progress, skillHome }) {
187
+ export async function dispatch(positionals, options, { state, server, credentials, client, mcp = client, signal, progress, skillHome }) {
188
+ client = mcp;
142
189
  const [command, action, id] = positionals;
143
- const media = new Media({ mcp, state, server });
190
+ const media = new Media({ client, state, server });
144
191
  if (command === 'auth') {
145
192
  if (action === 'login') return credentials.login({ noBrowser: options['no-browser'], timeout: options.timeout === undefined ? undefined : Number(options.timeout) * 1000, signal, progress });
146
193
  if (action === 'status') return credentials.status();
147
194
  if (action === 'logout') return credentials.logout();
148
195
  }
149
- if (command === 'balance') return mcp.call('check_balance');
196
+ if (command === 'balance') return client.call('check_balance');
150
197
  if (command === 'models') {
151
- if (action === 'show' && id) return mcp.call('get_model', { model: id });
152
- if (action === 'search') return mcp.call('search_models', { type: options.type || 'all', query: options.query, limit: number(options.limit, 'limit', 1, 50, true) || 20 });
198
+ if (action === 'show' && id) return client.call('get_model', { model: id });
199
+ if (action === 'schema' && id) {
200
+ const model = await client.call('get_model', { model: id });
201
+ requireThat(model.input_schema, 'schema_unavailable', 'The service has no versioned input schema for this model. Use models show for documented parameters; update the CLI if needed.');
202
+ return model;
203
+ }
204
+ if (action === 'search') return client.call('search_models', { type: options.type || 'all', query: options.query, limit: number(options.limit, 'limit', 1, 50, true) || 20,
205
+ ...(options.page !== undefined ? { page: Number(options.page) } : {}) },
206
+ options.page !== undefined ? { requireCapability: true, requiredInputs: ['page'] } : undefined);
207
+ if (action === 'recommend') return client.call('recommend_models', { type: options.type, query: options.query,
208
+ references: options.references ? references(options.references) : [], limit: number(options.limit, 'limit', 1, 10, true) || 3 }, { requireCapability: true });
153
209
  }
210
+ if (command === 'docs') return client.call('search_docs', { query: options.query, type: options.type || 'all', limit: number(options.limit, 'limit', 1, 20, true) || 5 }, { requireCapability: true });
211
+ if (command === 'usage') return client.call('get_task_usage', { since: options.since || '30d', until: options.until, model: options.model, type: options.type,
212
+ max_pages: number(options['max-pages'], 'max-pages', 1, 20, true) || 5 }, { requireCapability: true });
154
213
  if (command === 'estimate') return media.estimate(await estimateArgs(options));
155
214
  if (command === 'generate') {
156
215
  requireThat(options.quote, 'missing_quote', 'Run estimate and obtain user approval before generation.');
@@ -163,27 +222,34 @@ export async function dispatch(positionals, options, { state, server, credential
163
222
  return result;
164
223
  }
165
224
  if (command === 'tasks') {
166
- if (action === 'get' && id) return mcp.call('get_task', { task_id: id, wait_seconds: 0 });
225
+ if (action === 'get' && id) return client.call('get_task', { task_id: id, wait_seconds: 0 });
167
226
  if (action === 'wait' && id) return media.wait(id, { timeout: number(options.timeout, 'timeout', 1, 86400, true) || 1800, signal, progress });
168
227
  if (action === 'resume' && options.quote) return media.resume(options.quote);
169
- 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 });
228
+ if (action === 'batch') return client.call('list_tasks', { task_ids: taskIds(options.ids) });
229
+ if (action === 'list') {
230
+ const added = Object.fromEntries(['model', 'until', 'page'].filter(key => options[key] !== undefined).map(key => [key, key === 'page' ? Number(options[key]) : options[key]]));
231
+ return client.call('list_tasks', { type: options.type, status: options.status, since: options.since, limit: number(options.limit, 'limit', 1, 50, true) || 20, ...added },
232
+ Object.keys(added).length ? { requireCapability: true, requiredInputs: Object.keys(added) } : undefined);
233
+ }
170
234
  }
171
- if (command === 'upload' && action) return upload(action, { mcp, state, server, signal, upload_path: options['upload-path'] });
235
+ if (command === 'upload' && action) return upload(action, { client, state, server, signal, upload_path: options['upload-path'] });
172
236
  if (command === 'uploads' && action === 'get' && id) {
173
- const result = await mcp.call('get_upload', { upload_id: id });
237
+ if (client.uploadFile) return getUpload(id, { client, state, server });
238
+ const result = await client.call('get_upload', { upload_id: id });
174
239
  // A waiting upload may contain a bearer-like one-time URL; do not expose it.
175
240
  const { upload_url, text, ...view } = result;
176
241
  return { ...view, text: upload_url ? 'The upload is waiting for its original one-time PUT. No address is exposed by this recovery query.' : text };
177
242
  }
178
243
  if (command === 'download' && action) {
244
+ if (options.all) return downloadAll(action, options['output-dir'], { client, server, state, signal, template: options.template, resume: options.resume });
179
245
  requireThat(options.output, 'missing_output', 'Pass --output with a new local file path.');
180
- return download(action, options.output, { mcp, server, signal, index: number(options.index, 'index', 1, 50, true) || 1 });
246
+ return download(action, options.output, { client, server, signal, index: number(options.index, 'index', 1, 50, true) || 1 });
181
247
  }
182
248
  if (command === 'skills' && action === 'install') return installSkill({ home: skillHome, agent: options.agent, replaceModified: options['replace-modified'] });
183
249
  if (command === 'skills' && action === 'status') return skillStatus({ home: skillHome, agent: options.agent });
184
- if (command === 'setup') return setup({ state, server, credentials, mcp, agent: options.agent, skillHome,
250
+ if (command === 'setup') return setup({ state, server, credentials, client, agent: options.agent, skillHome,
185
251
  noBrowser: options['no-browser'], timeout: options.timeout === undefined ? undefined : Number(options.timeout) * 1000, signal, progress });
186
- if (command === 'doctor') return doctor({ state, server, credentials, mcp, agent: options.agent, skillHome });
252
+ if (command === 'doctor') return doctor({ state, server, credentials, client, agent: options.agent, skillHome });
187
253
  throw new CliError('unknown_command', 'Unknown command or missing argument. Run evolink --help.');
188
254
  }
189
255
 
@@ -214,16 +280,17 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
214
280
  catch { throw new CliError('invalid_option', 'Invalid command option. Run evolink --help.'); }
215
281
  if (options.version) { io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, version: CLI_VERSION }) + '\n' : CLI_VERSION + '\n'); return; }
216
282
  if (options.help || !positionals.length) {
217
- const help = options.help && positionals.length === 2 && positionals[0] === 'tasks' && positionals[1] === 'list' ? TASKS_LIST_HELP : HELP;
218
- io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, help }) + '\n' : help); return;
283
+ const reference = commandHelp(positionals);
284
+ const help = options.help && positionals.length === 2 && positionals[0] === 'tasks' && positionals[1] === 'list' ? TASKS_LIST_HELP : reference?.help || HELP;
285
+ io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, ...reference, help }) + '\n' : help); return;
219
286
  }
220
287
  validateCommand(positionals, options);
221
288
  const server = serverURL(options.server);
222
289
  const state = new State();
223
290
  const token = options['token-stdin'] ? await stdinToken(io.stdin) : undefined;
224
291
  const credentials = new Credentials({ server, state, token });
225
- const mcp = new Mcp(credentials, { signal: controller.signal });
226
- const result = publicView(await dispatch(positionals, options, { state, server, credentials, mcp, signal: controller.signal, progress: message => io.stderr.write(message + '\n') }));
292
+ const client = new Api(credentials, { signal: controller.signal, apiUrl: options['api-url'], filesUrl: options['files-url'] });
293
+ const result = publicView(await dispatch(positionals, options, { state, server, credentials, client, signal: controller.signal, progress: message => io.stderr.write(message + '\n') }));
227
294
  const view = { schema_version: 1, ...result, ok: result.ok !== false };
228
295
  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` : ''}`);
229
296
  if (!view.ok) process.exitCode = view.error?.code === 'interrupted' ? 130 : 1;
package/src/doctor.mjs CHANGED
@@ -24,30 +24,32 @@ export async function prerequisites({ state, credentials, version = process.vers
24
24
  const auth = await check('credential_storage', () => credentials.status());
25
25
  return { runtime, storage, auth, checks };
26
26
  }
27
- export async function verifyModels(mcp) {
28
- const result = await mcp.call('search_models', { type: 'all', limit: 1 });
27
+ export async function verifyModels(client) {
28
+ const result = await client.call('search_models', { type: 'all', limit: 1 });
29
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
30
  requireThat(result.models.length > 0, 'model_catalog_empty', 'No models are currently available for this connection. Retry model discovery later.');
31
31
  return { verified: true, models_available: true };
32
32
  }
33
- export async function doctor({ state, server, credentials, mcp, version = process.version, platform = process.platform,
33
+ export async function doctor({ state, server, credentials, client, mcp = client, version = process.version, platform = process.platform,
34
34
  remote = !!process.env.SSH_CONNECTION, agent, skillHome }) {
35
+ client = mcp;
35
36
  const { runtime, storage, auth, checks } = await prerequisites({ state, credentials, version, platform });
36
37
  const login = auth?.authenticated === true;
37
38
  if (auth) checks.push(login ? { name: 'login', status: 'passed' } : {
38
39
  name: 'login', status: 'failed', error: errorView(new CliError('login_required', 'Run evolink auth login, finish browser approval, then run doctor again.')),
39
40
  });
40
41
  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
+ let connected = false, models = false, authorization;
42
43
  if (runtime && storage && login) {
43
44
  try {
44
- const result = await mcp.call('check_balance');
45
+ const result = await client.call('check_balance');
45
46
  requireThat(result.ok === true, 'connection_failed', 'Balance verification failed. Retry evolink balance --json.');
47
+ authorization = result.authorization;
46
48
  connected = true; checks.push({ name: 'connection', status: 'passed', verified: true });
47
49
  } catch (error) { checks.push({ name: 'connection', status: 'failed', error: errorView(error) }); }
48
50
  } else checks.push({ name: 'connection', status: 'skipped', reason: 'Fix the failed prerequisite checks before verifying the account connection.' });
49
51
  if (connected) {
50
- try { const details = await verifyModels(mcp); models = true; checks.push({ name: 'models', status: 'passed', ...details }); }
52
+ try { const details = await verifyModels(client); models = true; checks.push({ name: 'models', status: 'passed', ...details }); }
51
53
  catch (error) { checks.push({ name: 'models', status: 'failed', error: errorView(error) }); }
52
54
  } else checks.push({ name: 'models', status: 'skipped', reason: 'Verify the account connection first.' });
53
55
  let skills;
@@ -62,5 +64,6 @@ export async function doctor({ state, server, credentials, mcp, version = proces
62
64
  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
65
  return { ok: !!runtime && !!storage && connected && models && (agent === undefined || skills?.current === true),
64
66
  cli_version: CLI_VERSION, node: version, server: server.href, ...(auth ? { auth } : {}),
67
+ ...(authorization ? { authorization } : {}), ...(client.apiUrl ? { transport: 'rest', api_origin: client.apiUrl.origin } : {}),
65
68
  connection_verified: connected, model_discovery_verified: models, assistant_discovery: 'not_checked', checks, guidance };
66
69
  }
package/src/files.mjs CHANGED
@@ -5,21 +5,24 @@ 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, localFile, fileError } from './errors.mjs';
8
+ import { CliError, requireThat, localFile, fileError, errorView } from './errors.mjs';
9
+ import { hash } from './state.mjs';
9
10
  import { checkContentType, checkMediaPrefix } from './media-content.mjs';
10
11
 
11
12
  const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp',
12
13
  '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.aac': 'audio/aac', '.flac': 'audio/flac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg',
13
14
  '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm' };
14
15
 
15
- export async function upload(file, { mcp, state, server, signal, upload_path, fetchFn = fetch }) {
16
+ export async function upload(file, { client, mcp = client, state, server, signal, upload_path, fetchFn = fetch }) {
17
+ client = mcp;
16
18
  const full = path.resolve(file);
17
19
  const stat = await localFile(() => fs.stat(full), { file: full });
18
20
  requireThat(stat.isFile() && stat.size > 0 && stat.size <= 95 * 1024 * 1024, 'invalid_file', 'Uploads must be regular files between 1 byte and 95 MB.');
19
21
  const type = MIME[path.extname(full).toLowerCase()];
20
22
  requireThat(type, 'unsupported_file', 'This file format is not supported. Use JPEG, PNG, GIF, WebP, supported audio, MP4, MOV or WebM.');
21
23
  await localFile(() => fs.access(full, constants.R_OK), { file: full });
22
- const prepared = await mcp.call('prepare_upload', { file_name: path.basename(full), ...(upload_path ? { upload_path } : {}) });
24
+ if (client.uploadFile) return directUpload(full, stat.size, type, { client, state, server, upload_path });
25
+ const prepared = await client.call('prepare_upload', { file_name: path.basename(full), ...(upload_path ? { upload_path } : {}) });
23
26
  requireThat(stat.size <= prepared.max_bytes, 'file_too_large', 'This file exceeds the upload limit.');
24
27
  const destination = new URL(prepared.upload_url);
25
28
  requireThat(destination.origin === server.origin && destination.pathname === `/uploads/${prepared.upload_id}` && !destination.username && !destination.password,
@@ -37,7 +40,7 @@ export async function upload(file, { mcp, state, server, signal, upload_path, fe
37
40
  } catch { failure = 'The upload connection was interrupted.'; }
38
41
  finally { body.destroy(); }
39
42
  try {
40
- const result = await mcp.call('get_upload', { upload_id: prepared.upload_id });
43
+ const result = await client.call('get_upload', { upload_id: prepared.upload_id });
41
44
  if (result.state === 'done') return result;
42
45
  throw new CliError('upload_pending', failure || 'The upload is still being processed.', { upload_id: prepared.upload_id, state: result.state });
43
46
  } catch (e) {
@@ -45,14 +48,55 @@ export async function upload(file, { mcp, state, server, signal, upload_path, fe
45
48
  }
46
49
  }
47
50
 
48
- export async function download(taskId, output, { mcp, server, index = 1, signal, maxBytes = 1024 ** 3, fetchFn }) {
51
+ async function directUpload(file, size, mime, { client, state, server, upload_path }) {
52
+ const access = await client.credentials.access();
53
+ const upload_id = `cli-up-${randomUUID()}`;
54
+ const journal = { upload_id, backend: 'platform', server: server.href, api_origin: client.apiUrl.origin, binding: access.binding,
55
+ file_name: path.basename(file), size_bytes: size, state: 'uploading' };
56
+ await state.write('uploads', upload_id, journal);
57
+ const source = createReadStream(file);
58
+ try {
59
+ const result = await client.uploadFile(source, size, mime, path.basename(file), upload_path);
60
+ const data = result?.data;
61
+ requireThat(result?.success === true && typeof data?.file_id === 'string' && typeof data?.file_url === 'string',
62
+ 'upload_unknown', 'The file service returned no verified upload result.');
63
+ const url = new URL(data.file_url);
64
+ requireThat(!url.username && !url.password && !url.hash && (url.protocol === 'https:' || loopback(server) && url.origin === server.origin),
65
+ 'invalid_upload_result', 'The file service returned an invalid public reference URL.');
66
+ journal.state = 'done';
67
+ // Store an allowlisted receipt, never a token or a signed upload address.
68
+ journal.result = { ok: true, upload_id, state: 'done', file_id: data.file_id, file_url: data.file_url,
69
+ file_name: data.file_name, size_bytes: data.file_size, mime_type: data.mime_type, expires_at: data.expires_at };
70
+ await state.write('uploads', upload_id, journal);
71
+ return journal.result;
72
+ } catch (error) {
73
+ journal.state = 'outcome_unknown';
74
+ await state.write('uploads', upload_id, journal);
75
+ throw new CliError(error.code || 'upload_unknown', error.message || 'The upload outcome is unknown.', {
76
+ upload_id, state: journal.state, next_step: `evolink uploads get ${upload_id}` }, error.exitCode);
77
+ } finally { source.destroy(); }
78
+ }
79
+
80
+ export async function getUpload(id, { client, state, server }) {
81
+ const journal = await state.read('uploads', id);
82
+ requireThat(journal?.server === server.href, 'upload_not_found', 'No upload receipt exists for this login resource.');
83
+ requireThat(journal.backend === 'platform', 'legacy_upload', 'This upload used an older MCP-based CLI and its upload proxy. Recover it with the original CLI version; the direct API client cannot query an old proxy slot.', { upload_id: id });
84
+ requireThat(journal.api_origin === client.apiUrl.origin && journal.binding === (await client.credentials.access()).binding,
85
+ 'upload_session_changed', 'This receipt belongs to a different platform or login.');
86
+ if (journal.state === 'done') return journal.result;
87
+ return { ok: true, upload_id: id, state: 'outcome_unknown', result_verified: false,
88
+ text: 'No completed receipt was saved. The file service currently cannot look up an upload by client request ID. Check your files before uploading again; this command does not retry the upload.' };
89
+ }
90
+
91
+ export async function download(taskId, output, { client, mcp = client, server, index = 1, signal, maxBytes = 1024 ** 3, fetchFn, task: suppliedTask, beforeCommit }) {
92
+ client = mcp;
49
93
  const target = path.resolve(output);
50
94
  const parent = await localFile(() => fs.stat(path.dirname(target)), { file: target, missing: 'output_directory_missing' });
51
95
  requireThat(parent.isDirectory(), 'path_not_directory', 'The output parent is not a directory. Choose a valid file path.');
52
96
  await localFile(() => fs.access(path.dirname(target), constants.W_OK), { file: target });
53
97
  try { await fs.lstat(target); throw new CliError('file_exists', 'The output file already exists. Choose another path.'); }
54
98
  catch (e) { if (e.code !== 'ENOENT') throw fileError(e, { file: target }); }
55
- const task = await mcp.call('get_task', { task_id: taskId, wait_seconds: 0 });
99
+ const task = suppliedTask ?? await client.call('get_task', { task_id: taskId, wait_seconds: 0 });
56
100
  requireThat(task.status === 'completed', 'task_not_ready', 'Wait for the task to complete before downloading.');
57
101
  const result = task.results?.[index - 1];
58
102
  requireThat(Number.isInteger(index) && index > 0 && result?.url, 'result_not_found', 'The requested result index does not exist.');
@@ -88,8 +132,100 @@ export async function download(taskId, output, { mcp, server, index = 1, signal,
88
132
  requireThat(response.body, 'download_failed', 'The file service returned an empty response.');
89
133
  await pipeline(Readable.fromWeb(response.body), guard, createWriteStream(temp, { flags: 'wx', mode: 0o600 }), { signal: timeoutSignal });
90
134
  requireThat(bytes > 0, 'download_failed', 'The file service returned an empty file.');
135
+ const receipt = { task_id: taskId, result_index: index, path: target, size_bytes: bytes, sha256: digest.digest('hex'), kind: result.kind };
136
+ await beforeCommit?.(receipt);
91
137
  await fs.link(temp, target);
92
- return { task_id: taskId, result_index: index, path: target, size_bytes: bytes, sha256: digest.digest('hex'), kind: result.kind };
138
+ return receipt;
93
139
  } catch (error) { throw fileError(error, { file: target, missing: 'output_directory_missing' }); }
94
140
  finally { await fs.unlink(temp).catch(() => {}); }
95
141
  }
142
+
143
+ export function downloadNames(taskId, results, template = '{task_id}-{index}.{ext}') {
144
+ requireThat(typeof template === 'string' && template.length > 0 && template.length <= 200 && !/[\\/\x00-\x1f]/.test(template),
145
+ 'invalid_template', 'Use a filename template, without directory separators. Placeholders: {task_id}, {index}, {kind}, {ext}.');
146
+ const names = results.map((result, index) => {
147
+ let extension;
148
+ try { extension = path.extname(new URL(result.url).pathname).toLowerCase(); } catch {}
149
+ const ext = MIME[extension] ? extension.slice(1) : 'bin';
150
+ const values = { task_id: String(taskId).replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 128), index: String(index + 1), kind: result.kind, ext };
151
+ const name = template.replace(/\{(task_id|index|kind|ext)\}/g, (_, key) => values[key]);
152
+ requireThat(name.length <= 240 && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) && !name.includes('..')
153
+ && !/[. ]$/.test(name) && !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name),
154
+ 'invalid_template', 'The template must produce portable filenames with letters, digits, dots, underscores or hyphens.');
155
+ return name;
156
+ });
157
+ 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}.');
158
+ return names;
159
+ }
160
+
161
+ /** Recovery checks saved file digests; it never treats an unrelated existing file as a delivered result. */
162
+ export async function downloadAll(taskId, directory, { client, mcp = client, server, state, signal, template, resume = false, fetchFn }) {
163
+ const target = path.resolve(directory);
164
+ const receiptId = hash({ taskId, server: server.href, target });
165
+ return state.lock(`delivery-${receiptId}`, async () => {
166
+ const task = await mcp.call('get_task', { task_id: taskId, wait_seconds: 0 });
167
+ requireThat(task.status === 'completed', 'task_not_ready', 'Wait for the task to complete before downloading.');
168
+ requireThat(Array.isArray(task.results) && task.results.length > 0 && task.results.length <= 50,
169
+ 'invalid_result_count', 'Download all requires between 1 and 50 result links. Use individual downloads for larger tasks.');
170
+ const names = downloadNames(taskId, task.results, template);
171
+ const sources = task.results.map(result => {
172
+ const url = new URL(result.url);
173
+ return hash({ kind: result.kind, origin: url.origin, path: url.pathname });
174
+ });
175
+ let receipt = await state.read('deliveries', receiptId);
176
+ if (resume) {
177
+ requireThat(receipt && receipt.task_id === taskId && receipt.directory === target && receipt.server === server.href
178
+ && Array.isArray(receipt.files) && hash(receipt.names) === hash(names) && hash(receipt.sources) === hash(sources),
179
+ '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.');
180
+ } else {
181
+ requireThat(!receipt, 'delivery_exists', 'This task already has a delivery receipt for this directory. Use --resume to verify saved files and download the remainder.');
182
+ receipt = { task_id: taskId, directory: target, server: server.href, names, sources, files: [] };
183
+ }
184
+ await localFile(() => fs.mkdir(target, { recursive: true, mode: 0o700 }), { file: target });
185
+ requireThat((await fs.stat(target)).isDirectory(), 'path_not_directory', 'Choose an output directory.');
186
+ await state.write('deliveries', receiptId, receipt);
187
+ const failures = [], downloaded = [];
188
+ for (let index = 1; index <= names.length; index++) {
189
+ const file = path.join(target, names[index - 1]);
190
+ try {
191
+ requireThat(!signal?.aborted, 'interrupted', 'Stopped downloading locally. The completed EvoLink task is unchanged.');
192
+ let saved = receipt.files.find(item => item.result_index === index);
193
+ if (saved?.pending_commit) {
194
+ try { await fs.lstat(file); }
195
+ catch (error) {
196
+ if (error.code !== 'ENOENT') throw error;
197
+ receipt.files = receipt.files.filter(item => item.result_index !== index);
198
+ await state.write('deliveries', receiptId, receipt);
199
+ saved = undefined;
200
+ }
201
+ }
202
+ if (saved) {
203
+ const stat = await localFile(() => fs.lstat(file), { file });
204
+ requireThat(saved.path === file && /^[a-f0-9]{64}$/.test(saved.sha256) && stat.isFile() && stat.size === saved.size_bytes,
205
+ 'saved_file_changed', 'A previously downloaded file changed. It will not be overwritten. Choose a new output directory.');
206
+ const digest = createHash('sha256');
207
+ for await (const bytes of createReadStream(file, { signal })) digest.update(bytes);
208
+ requireThat(digest.digest('hex') === saved.sha256, 'saved_file_changed', 'A previously downloaded file changed. It will not be overwritten. Choose a new output directory.');
209
+ if (saved.pending_commit) { saved.pending_commit = false; await state.write('deliveries', receiptId, receipt); }
210
+ downloaded.push({ ...saved, verified_existing: true });
211
+ } else {
212
+ const result = await download(taskId, file, { mcp, server, index, signal, fetchFn, task, beforeCommit: async pending => {
213
+ receipt.files.push({ ...pending, pending_commit: true });
214
+ await state.write('deliveries', receiptId, receipt);
215
+ } });
216
+ Object.assign(receipt.files.find(item => item.result_index === index), result, { pending_commit: false });
217
+ await state.write('deliveries', receiptId, receipt);
218
+ downloaded.push(result);
219
+ }
220
+ } catch (error) {
221
+ failures.push({ result_index: index, path: file, error: errorView(error) });
222
+ if (signal?.aborted) break;
223
+ }
224
+ }
225
+ const complete = downloaded.length === names.length && failures.length === 0;
226
+ return { ok: complete, task_id: taskId, generation_status: 'completed', delivery_status: complete ? 'completed' : 'partial',
227
+ files: downloaded, failures, result_count: names.length, receipt_id: receiptId,
228
+ ...(signal?.aborted ? { error: { code: 'interrupted' } } : {}),
229
+ 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.'}` };
230
+ });
231
+ }
package/src/help.mjs ADDED
@@ -0,0 +1,68 @@
1
+ import { CliError } from './errors.mjs';
2
+
3
+ const choice = values => ({ type: 'string', allowed_values: values });
4
+ const integer = (min, max, defaultValue) => ({ type: 'integer', minimum: min, maximum: max, ...(defaultValue === undefined ? {} : { default: defaultValue }) });
5
+ const string = description => ({ type: 'string', description });
6
+ const flag = { type: 'boolean' };
7
+ const media = choice(['image', 'video', 'audio']);
8
+ const allMedia = choice(['image', 'video', 'audio', 'all']);
9
+ const time = string('Creation time: ISO 8601, Unix seconds, or relative 30m, 2h, 1d.');
10
+ const agent = string('all, codex, claude-code, cursor, gemini, opencode, copilot, openclaw, hermes');
11
+ const login = { 'no-browser': flag, timeout: integer(30, 900, 180) };
12
+ const COMMANDS = {
13
+ setup: ['[options]', 'Reuse or finish login, install and verify the skill. Free.', { agent, ...login }],
14
+ 'auth login': ['[options]', 'Browser OAuth login. Keep the command running until the callback completes.', login],
15
+ 'auth status': ['', 'Check this CLI login without spending money.', {}],
16
+ 'auth logout': ['', 'Revoke this CLI session; other OAuth sessions retain access.', {}],
17
+ balance: ['', 'Read account balance and the shared CLI/MCP OAuth key limits. Free.', {}],
18
+ 'models search': ['[options]', 'Search currently available models; search order is not a quality ranking.', { query: string('Search keywords'), type: allMedia, limit: integer(1, 50, 20), page: integer(1, 100000, 1) }],
19
+ 'models show': ['MODEL', 'Read documented parameters, example input, reference fields and pricing. Free.', {}],
20
+ 'models schema': ['MODEL', 'Read versioned input and generation-submission response schemas. The response schema may omit final task outputs; runtime constraints also apply.', {}],
21
+ 'models recommend': ['--type TYPE [options]', 'Compare documented available alternatives with selection reasons. Unit rates are not total quotes.', { type: media, query: string('Search keywords; every term must match'), references: string('Comma-separated image,video,audio'), limit: integer(1, 10, 3) }],
22
+ 'docs search': ['--query TEXT [options]', 'Search versioned official model reference excerpts, not the live full website.', { query: string('Required model reference keywords'), type: allMedia, limit: integer(1, 20, 5) }],
23
+ estimate: ['--model MODEL --input-file FILE [options]', 'Prepare a 15-minute quote. Show cost uncertainties and obtain user approval. max-cost-usd checks the submission estimate; it does not cap final settlement.', {
24
+ model: string('Required model ID'), input: string('JSON object; mutually exclusive with input-file'), 'input-file': string('Local JSON file; mutually exclusive with input'), prompt: string('Optional prompt'),
25
+ 'max-cost-usd': { type: 'number', exclusive_minimum: 0, maximum: 10000 }, 'media-seconds': { type: 'number', exclusive_minimum: 0, maximum: 3600 },
26
+ }],
27
+ 'tasks get': ['TASK_ID', 'Read one task. A failed task status is a successful query outcome. Free.', {}],
28
+ 'tasks wait': ['TASK_ID [options]', 'Wait locally. Ctrl-C stops waiting; the submitted task continues. Free.', { timeout: integer(1, 86400, 1800) }],
29
+ 'tasks batch': ['--ids ID,ID', 'Read 1-50 known tasks in one free query; missing IDs are reported, not regenerated.', { ids: string('Required comma-separated task IDs, at most 50') }],
30
+ 'tasks list': ['[options]', 'Page through account tasks. since/until filter only the selected page; total is before time filtering. Empty results do not prove no task was submitted.', {
31
+ status: choice(['processing', 'completed', 'failed', 'cancelled']), type: media, since: time, until: time, model: string('Exact model ID'), page: integer(1, 100000, 1), limit: integer(1, 50, 20),
32
+ }],
33
+ 'tasks resume': ['--quote ID', 'Recover an uncertain submission with the original request ID. Use generate for an approved quote that has never been submitted.', { quote: string('Original quote ID') }],
34
+ usage: ['[options]', 'Summarize reported completed-task credits by creation time. Account-wide retained tasks; bounded scan with coverage and missing-cost metadata. Excludes payments/refunds and pending reservations. Not a bill or final budget.', {
35
+ since: { ...time, default: '30d' }, until: time, model: string('Exact model ID'), type: media, 'max-pages': integer(1, 20, 5),
36
+ }],
37
+ upload: ['FILE [options]', 'Upload one readable local reference. Free. One-time upload addresses must not be exposed.', { 'upload-path': string('Optional upload folder') }],
38
+ 'uploads get': ['UPLOAD_ID', 'Read a saved upload receipt. An unknown result cannot be recovered by request ID; this command never uploads again. Free.', {}],
39
+ download: ['TASK_ID --output FILE | --all --output-dir DIR [options]', 'Download original media, verify content and preserve existing files. --all writes recovery receipts; --resume verifies prior SHA-256 hashes and downloads the remainder. Partial delivery exits nonzero and never regenerates.', {
40
+ output: string('New file path, for a single result'), index: integer(1, 50, 1), all: flag, 'output-dir': string('Directory, required with all'),
41
+ template: { ...string('Filename placeholders: {task_id}, {index}, {kind}, {ext}; no directories'), default: '{task_id}-{index}.{ext}' }, resume: flag,
42
+ }],
43
+ 'skills install': ['[options]', 'Install or synchronize bundled skill files; protect modified files and back up replacements.', { agent, 'replace-modified': flag }],
44
+ 'skills status': ['[options]', 'Compare installed skill contents and package version.', { agent }],
45
+ doctor: ['[options]', 'Check prerequisites, connection, model discovery and skill contents separately. Free.', { agent }],
46
+ };
47
+ for (const type of ['image', 'video', 'audio']) COMMANDS[`generate ${type}`] = [
48
+ '--quote ID --confirm [options]', 'Submit the saved quote after explicit user approval. Changes require a new quote. Never call generate to poll progress.',
49
+ { quote: string('Approved quote ID'), confirm: flag, wait: flag, timeout: integer(1, 86400, 1800) },
50
+ ];
51
+
52
+ export function commandHelp(positionals) {
53
+ if (!positionals.length) return { commands: Object.keys(COMMANDS) };
54
+ const name = COMMANDS[positionals.slice(0, 2).join(' ')] ? positionals.slice(0, 2).join(' ') : positionals[0];
55
+ const entry = COMMANDS[name];
56
+ if (!entry) {
57
+ const subcommands = Object.keys(COMMANDS).filter(command => command.startsWith(`${positionals[0]} `));
58
+ if (positionals.length === 1 && subcommands.length) return { command: positionals[0], subcommands,
59
+ help: [`Usage: evolink ${positionals[0]} COMMAND --help`, '', ...subcommands.map(command => ` ${command}`), ''].join('\n') };
60
+ throw new CliError('unknown_command', 'Unknown command. Run evolink --help for the command list.');
61
+ }
62
+ const [argumentsText, description, options] = entry;
63
+ const usage = `evolink ${name}${argumentsText ? ` ${argumentsText}` : ''}`;
64
+ const help = [`Usage: ${usage}`, '', description, '',
65
+ ...Object.entries(options).map(([key, spec]) => ` --${key} ${spec.allowed_values ? spec.allowed_values.join('|') : spec.description || spec.type}${spec.minimum !== undefined ? `; ${spec.minimum}-${spec.maximum}` : ''}${spec.default !== undefined ? ` (default ${spec.default})` : ''}`),
66
+ '', 'Connection/output options: --server RESOURCE_URL, --api-url URL, --files-url URL, --token-stdin, --json, --help.', 'This help query needs no login and sends no request.', ''].join('\n');
67
+ return { command: name, usage, description, options, help };
68
+ }