@evolinkai/cli 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +35 -6
  2. package/package.json +27 -8
  3. package/skills/evolink-cli/SKILL.md +5 -5
  4. package/skills/evolink-cli/references/capabilities.md +1 -1
  5. package/src/api.mjs +59 -0
  6. package/src/auth.mjs +6 -7
  7. package/src/cli.mjs +34 -30
  8. package/src/doctor.mjs +9 -6
  9. package/src/errors.mjs +21 -13
  10. package/src/files.mjs +61 -6
  11. package/src/help.mjs +8 -8
  12. package/src/media.mjs +11 -9
  13. package/src/network.mjs +12 -1
  14. package/src/oauth.mjs +90 -0
  15. package/src/platform/LICENSE +178 -0
  16. package/src/platform/NOTICE +6 -0
  17. package/src/platform/core/src/config.js +95 -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 +56 -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 +232 -0
  25. package/src/platform/core/src/services/catalog-client.js +45 -0
  26. package/src/platform/core/src/services/error-handler.js +452 -0
  27. package/src/platform/core/src/services/file-client.js +165 -0
  28. package/src/platform/core/src/services/http-policy.js +186 -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/public-error.js +63 -0
  35. package/src/platform/core/src/services/utm.js +65 -0
  36. package/src/platform/core/src/tool-guidance.js +50 -0
  37. package/src/platform/core/src/tools/check-balance.js +90 -0
  38. package/src/platform/core/src/tools/discovery.js +86 -0
  39. package/src/platform/core/src/tools/estimate-cost.js +136 -0
  40. package/src/platform/core/src/tools/generate.js +237 -0
  41. package/src/platform/core/src/tools/get-model.js +146 -0
  42. package/src/platform/core/src/tools/get-task.js +57 -0
  43. package/src/platform/core/src/tools/list-tasks.js +170 -0
  44. package/src/platform/core/src/tools/search-models.js +115 -0
  45. package/src/platform/core/src/tools/shared.js +158 -0
  46. package/src/platform/core/src/tools/task-billing.js +31 -0
  47. package/src/platform/core/src/tools/task-format.js +264 -0
  48. package/src/platform/core/src/tools/task-usage.js +108 -0
  49. package/src/platform/core/src/version.js +4 -0
  50. package/src/platform/source.json +84 -0
  51. package/src/setup.mjs +9 -5
  52. package/src/mcp.mjs +0 -43
package/src/files.mjs CHANGED
@@ -13,14 +13,16 @@ const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
13
13
  '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.aac': 'audio/aac', '.flac': 'audio/flac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg',
14
14
  '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm' };
15
15
 
16
- 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;
17
18
  const full = path.resolve(file);
18
19
  const stat = await localFile(() => fs.stat(full), { file: full });
19
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.');
20
21
  const type = MIME[path.extname(full).toLowerCase()];
21
22
  requireThat(type, 'unsupported_file', 'This file format is not supported. Use JPEG, PNG, GIF, WebP, supported audio, MP4, MOV or WebM.');
22
23
  await localFile(() => fs.access(full, constants.R_OK), { file: full });
23
- 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 } : {}) });
24
26
  requireThat(stat.size <= prepared.max_bytes, 'file_too_large', 'This file exceeds the upload limit.');
25
27
  const destination = new URL(prepared.upload_url);
26
28
  requireThat(destination.origin === server.origin && destination.pathname === `/uploads/${prepared.upload_id}` && !destination.username && !destination.password,
@@ -38,7 +40,7 @@ export async function upload(file, { mcp, state, server, signal, upload_path, fe
38
40
  } catch { failure = 'The upload connection was interrupted.'; }
39
41
  finally { body.destroy(); }
40
42
  try {
41
- 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 });
42
44
  if (result.state === 'done') return result;
43
45
  throw new CliError('upload_pending', failure || 'The upload is still being processed.', { upload_id: prepared.upload_id, state: result.state });
44
46
  } catch (e) {
@@ -46,14 +48,67 @@ export async function upload(file, { mcp, state, server, signal, upload_path, fe
46
48
  }
47
49
  }
48
50
 
49
- export async function download(taskId, output, { mcp, server, index = 1, signal, maxBytes = 1024 ** 3, fetchFn, task: suppliedTask, beforeCommit }) {
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, upload_id);
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
+ let receipt;
88
+ try { receipt = await client.uploadReceipt?.(id); }
89
+ catch { throw new CliError('upload_unknown', 'The original upload receipt is unavailable. Keep this upload_id and retry this read later; no bytes were resent.',
90
+ { upload_id: id, state: 'outcome_unknown', next_step: `evolink uploads get ${id}` }); }
91
+ if (receipt?.state === 'done' && receipt.result_verified === true) {
92
+ const data = receipt.file;
93
+ journal.state = 'done';
94
+ journal.result = { ok: true, upload_id: id, state: 'done', file_id: data.file_id, file_url: data.file_url,
95
+ file_name: data.original_name ?? data.file_name, size_bytes: data.file_size, mime_type: data.mime_type, expires_at: data.expires_at };
96
+ await state.write('uploads', id, journal);
97
+ return journal.result;
98
+ }
99
+ return { ok: true, upload_id: id, state: 'outcome_unknown', result_verified: false,
100
+ text: 'No verified completed receipt is available. The upload may still have arrived. Check your files before starting another upload; this command only reads the original receipt and never resends bytes.' };
101
+ }
102
+
103
+ export async function download(taskId, output, { client, mcp = client, server, index = 1, signal, maxBytes = 1024 ** 3, fetchFn, task: suppliedTask, beforeCommit }) {
104
+ client = mcp;
50
105
  const target = path.resolve(output);
51
106
  const parent = await localFile(() => fs.stat(path.dirname(target)), { file: target, missing: 'output_directory_missing' });
52
107
  requireThat(parent.isDirectory(), 'path_not_directory', 'The output parent is not a directory. Choose a valid file path.');
53
108
  await localFile(() => fs.access(path.dirname(target), constants.W_OK), { file: target });
54
109
  try { await fs.lstat(target); throw new CliError('file_exists', 'The output file already exists. Choose another path.'); }
55
110
  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 });
111
+ const task = suppliedTask ?? await client.call('get_task', { task_id: taskId, wait_seconds: 0 });
57
112
  requireThat(task.status === 'completed', 'task_not_ready', 'Wait for the task to complete before downloading.');
58
113
  const result = task.results?.[index - 1];
59
114
  requireThat(Number.isInteger(index) && index > 0 && result?.url, 'result_not_found', 'The requested result index does not exist.');
@@ -116,7 +171,7 @@ export function downloadNames(taskId, results, template = '{task_id}-{index}.{ex
116
171
  }
117
172
 
118
173
  /** 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 }) {
174
+ export async function downloadAll(taskId, directory, { client, mcp = client, server, state, signal, template, resume = false, fetchFn }) {
120
175
  const target = path.resolve(directory);
121
176
  const receiptId = hash({ taskId, server: server.href, target });
122
177
  return state.lock(`delivery-${receiptId}`, async () => {
package/src/help.mjs CHANGED
@@ -13,13 +13,13 @@ const COMMANDS = {
13
13
  setup: ['[options]', 'Reuse or finish login, install and verify the skill. Free.', { agent, ...login }],
14
14
  'auth login': ['[options]', 'Browser OAuth login. Keep the command running until the callback completes.', login],
15
15
  'auth status': ['', 'Check this CLI login without spending money.', {}],
16
- 'auth logout': ['', 'Revoke this CLI session.', {}],
17
- balance: ['', 'Read account balance and the calling MCP key limits. Free.', {}],
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
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
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. Requires updated MCP.', {}],
21
- 'models recommend': ['--type TYPE [options]', 'Compare documented available alternatives with selection reasons. Unit rates are not total quotes. Requires updated MCP.', { 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. Requires updated MCP.', { query: string('Required model reference keywords'), type: allMedia, limit: integer(1, 20, 5) }],
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
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
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
25
  'max-cost-usd': { type: 'number', exclusive_minimum: 0, maximum: 10000 }, 'media-seconds': { type: 'number', exclusive_minimum: 0, maximum: 3600 },
@@ -31,11 +31,11 @@ const COMMANDS = {
31
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
32
  }],
33
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. Requires updated MCP.', {
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
35
  since: { ...time, default: '30d' }, until: time, model: string('Exact model ID'), type: media, 'max-pages': integer(1, 20, 5),
36
36
  }],
37
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', 'Recover upload state without exposing its one-time address. Free.', {}],
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
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
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
41
  template: { ...string('Filename placeholders: {task_id}, {index}, {kind}, {ext}; no directories'), default: '{task_id}-{index}.{ext}' }, resume: flag,
@@ -63,6 +63,6 @@ export function commandHelp(positionals) {
63
63
  const usage = `evolink ${name}${argumentsText ? ` ${argumentsText}` : ''}`;
64
64
  const help = [`Usage: ${usage}`, '', description, '',
65
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 URL, --token-stdin, --json, --help.', 'This help query needs no login and sends no request.', ''].join('\n');
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
67
  return { command: name, usage, description, options, help };
68
68
  }
package/src/media.mjs CHANGED
@@ -38,12 +38,12 @@ export function checkEstimate(quote, cap) {
38
38
  }
39
39
 
40
40
  export class Media {
41
- constructor({ mcp, state, server, now = Date.now }) { this.mcp = mcp; this.state = state; this.server = server.href; this.now = now; }
41
+ constructor({ client, mcp = client, state, server, now = Date.now }) { this.client = mcp; this.state = state; this.server = server.href; this.now = now; }
42
42
  async estimate(args) {
43
43
  const { max_cost_usd, ...input } = args;
44
44
  let quote;
45
45
  try {
46
- quote = await this.mcp.call('estimate_cost', input);
46
+ quote = await this.client.call('estimate_cost', input);
47
47
  checkEstimate(quote, max_cost_usd);
48
48
  requireThat(['image', 'video', 'audio'].includes(quote.type), 'unsupported_model', 'This model is not a media generation model.');
49
49
  } catch (error) { throw quoteError(error, max_cost_usd); }
@@ -53,6 +53,7 @@ export class Media {
53
53
  const id = randomUUID();
54
54
  const argsToSubmit = { ...input, model: quote.model, ...(effectiveCap !== undefined ? { max_cost_usd: effectiveCap } : {}) };
55
55
  const stored = { id, server: this.server, binding: quote._binding, args: argsToSubmit,
56
+ ...(this.client.apiUrl ? { backend: 'platform', api_origin: this.client.apiUrl.origin } : {}),
56
57
  type: quote.type, args_hash: hash(argsToSubmit), fingerprint: priceFingerprint(quote), estimate: quote.estimate,
57
58
  created_at: this.now(), expires_at: this.now() + 15 * 60_000, state: 'quoted', client_request_id: `cli-${randomUUID()}` };
58
59
  await this.state.write('quotes', id, stored);
@@ -62,7 +63,8 @@ export class Media {
62
63
  async load(id) {
63
64
  const quote = await this.state.read('quotes', id);
64
65
  requireThat(quote?.server === this.server, 'quote_not_found', 'This quote does not exist for the current server.');
65
- requireThat(quote.binding === (await this.mcp.credentials.access()).binding, 'quote_session_changed', 'This quote belongs to a different login. Estimate again in the current session.');
66
+ requireThat(!quote.api_origin || quote.api_origin === this.client.apiUrl?.origin, 'quote_platform_changed', 'This quote belongs to a different platform API.');
67
+ requireThat(quote.binding === (await this.client.credentials.access()).binding, 'quote_session_changed', 'This quote belongs to a different login. Estimate again in the current session.');
66
68
  requireThat(quote.args_hash === hash(quote.args), 'quote_changed', 'The saved request changed. Estimate again.');
67
69
  return quote;
68
70
  }
@@ -72,7 +74,7 @@ export class Media {
72
74
  return this.state.lock(`quote-${id}`, async () => {
73
75
  const quote = await this.load(id);
74
76
  requireThat(quote.type === kind, 'quote_type_mismatch', 'Use the media type shown in the saved quote.');
75
- if (quote.task_id) return { ...await this.mcp.call('get_task', { task_id: quote.task_id, wait_seconds: 0 }), quote_id: id, recovered: true };
77
+ if (quote.task_id) return { ...await this.client.call('get_task', { task_id: quote.task_id, wait_seconds: 0 }), quote_id: id, recovered: true };
76
78
  requireThat(quote.state !== 'refused', 'submission_refused',
77
79
  'EvoLink refused this submission and reported no charge. Resolve the original error, estimate again with the same budget, and obtain approval for the new quote.',
78
80
  { quote_id: id, client_request_id: quote.client_request_id, charged: 'no', submission_allowed: false });
@@ -86,7 +88,7 @@ export class Media {
86
88
  const { max_cost_usd, ...checkArgs } = quote.args;
87
89
  let fresh;
88
90
  try {
89
- fresh = await this.mcp.call('estimate_cost', checkArgs);
91
+ fresh = await this.client.call('estimate_cost', checkArgs);
90
92
  requireThat(priceFingerprint(fresh) === quote.fingerprint, 'price_changed', 'The quote changed. Estimate again and obtain approval for the new quote.', { estimate: fresh.estimate });
91
93
  checkEstimate(fresh, max_cost_usd);
92
94
  } catch (error) { throw quoteError(error, max_cost_usd); }
@@ -95,12 +97,12 @@ export class Media {
95
97
  await this.state.write('quotes', id, quote);
96
98
  let result;
97
99
  try {
98
- result = await this.mcp.call(`generate_${kind}`, { ...quote.args, client_request_id: quote.client_request_id });
100
+ result = await this.client.call(`generate_${kind}`, { ...quote.args, client_request_id: quote.client_request_id });
99
101
  requireThat(typeof result.task_id === 'string' && result.task_id.length > 0, 'outcome_unknown', 'The submission returned no task ID. Recover with the original quote.');
100
102
  } catch (e) {
101
- quote.state = e.details?.charged === 'no' ? 'refused' : 'outcome_unknown';
103
+ quote.state = e.details?.charged === 'no' && ['not_submitted', 'rejected'].includes(e.details?.submission_state) ? 'refused' : 'outcome_unknown';
102
104
  await this.state.write('quotes', id, quote);
103
- throw new CliError(e.code || 'outcome_unknown', e.message, { ...(e.details || {}), quote_id: id, client_request_id: quote.client_request_id,
105
+ throw new CliError(e.code || 'outcome_unknown', e.message, { ...(e.details || {}), ...(quote.state === 'outcome_unknown' ? { charged: 'unknown', submission_state: 'outcome_unknown' } : {}), quote_id: id, client_request_id: quote.client_request_id,
104
106
  recovery: `evolink tasks resume --quote ${id}` }, e.exitCode);
105
107
  }
106
108
  quote.state = 'submitted';
@@ -118,7 +120,7 @@ export class Media {
118
120
  for (;;) {
119
121
  if (signal?.aborted) throw new CliError('interrupted', 'Stopped waiting locally. The EvoLink task continues.', { task_id: taskId }, 130);
120
122
  const remaining = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
121
- const task = await this.mcp.call('get_task', { task_id: taskId, wait_seconds: Math.min(30, remaining) });
123
+ const task = await this.client.call('get_task', { task_id: taskId, wait_seconds: Math.min(30, remaining) });
122
124
  if (task.status === 'completed') return task;
123
125
  if (['failed', 'cancelled'].includes(task.status)) throw new CliError('task_failed', 'The generation task did not complete.', { task });
124
126
  progress(`${task.task_id}: ${task.status}${task.progress !== undefined ? ` (${task.progress}%)` : ''}`);
package/src/network.mjs CHANGED
@@ -7,6 +7,8 @@ import { CLI_VERSION } from './version.mjs';
7
7
 
8
8
  export const SERVER = 'https://mcp.evolink.ai/mcp';
9
9
  export const ISSUER = 'https://passport.evolink.ai';
10
+ export const API = 'https://api.evolink.ai';
11
+ export const FILES = 'https://files-api.evolink.ai';
10
12
  export const USER_AGENT = `EvoLinkCLI/${CLI_VERSION}`;
11
13
  export const loopback = url => url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname);
12
14
 
@@ -19,7 +21,7 @@ export function serverURL(value = SERVER) {
19
21
  }
20
22
 
21
23
  export function authFetch(server, fetchFn = fetch) {
22
- const origins = new Set([server.origin, server.href === SERVER ? ISSUER : server.origin]);
24
+ const origins = new Set([server.href === SERVER ? ISSUER : server.origin]);
23
25
  return async (input, options = {}) => {
24
26
  const url = new URL(input instanceof Request ? input.url : input);
25
27
  requireThat(origins.has(url.origin) && !url.username && !url.password, 'untrusted_auth_server', 'The login endpoint is outside the configured EvoLink service.');
@@ -29,6 +31,15 @@ export function authFetch(server, fetchFn = fetch) {
29
31
  };
30
32
  }
31
33
 
34
+ export function serviceURL(value, production, resource) {
35
+ let url;
36
+ try { url = new URL(value); } catch { throw new CliError('invalid_api_url', 'Invalid platform service URL.'); }
37
+ requireThat(!url.username && !url.password && !url.search && !url.hash && url.pathname === '/'
38
+ && (url.origin === production || loopback(resource) && loopback(url)),
39
+ 'invalid_api_url', 'Use the EvoLink production service, or an explicit loopback service with a loopback test resource.');
40
+ return url;
41
+ }
42
+
32
43
  const blocked = new net.BlockList();
33
44
  for (const [network, prefix] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['127.0.0.0', 8], ['169.254.0.0', 16],
34
45
  ['172.16.0.0', 12], ['192.168.0.0', 16], ['224.0.0.0', 3], ['100.64.0.0', 10]]) blocked.addSubnet(network, prefix, 'ipv4');
package/src/oauth.mjs ADDED
@@ -0,0 +1,90 @@
1
+ import { randomBytes, createHash } from 'node:crypto';
2
+ import { CliError, requireThat } from './errors.mjs';
3
+ import { ISSUER, SERVER } from './network.mjs';
4
+
5
+ // Passport discovery is independent of MCP health and protected-resource metadata.
6
+ export async function metadata(server, fetchFn) {
7
+ const issuer = server.href === SERVER ? ISSUER : server.origin;
8
+ const response = await fetchFn(`${issuer}/.well-known/oauth-authorization-server`);
9
+ requireThat(response.ok, 'login_unavailable', 'Passport login discovery is unavailable. Retry login.');
10
+ const data = await response.json();
11
+ requireThat(data.issuer === issuer && data.code_challenge_methods_supported?.includes('S256'),
12
+ 'invalid_auth_metadata', 'Passport did not provide the expected issuer and PKCE method.');
13
+ for (const key of ['authorization_endpoint', 'token_endpoint', 'revocation_endpoint', ...(data.registration_endpoint ? ['registration_endpoint'] : [])]) {
14
+ let endpoint;
15
+ try { endpoint = new URL(data[key]); } catch { throw new CliError('invalid_auth_metadata', 'Passport did not provide valid login endpoints.'); }
16
+ requireThat(endpoint.origin === issuer && !endpoint.username && !endpoint.password && !endpoint.hash,
17
+ 'untrusted_auth_server', 'The login endpoint is outside Passport.');
18
+ }
19
+ return data;
20
+ }
21
+
22
+ async function client(provider, data, fetchFn, newLogin = false) {
23
+ let value = await provider.clientInformation();
24
+ if (value) requireThat(value.issuer === data.issuer && typeof value.client_id === 'string' && !value.client_secret,
25
+ 'invalid_client', 'The saved public OAuth client belongs to a different service.');
26
+ // A rolled-back Passport may no longer support media grants for this public
27
+ // identity. Only a new login can change clients; an existing refresh cannot.
28
+ if (newLogin && value?.client_id === 'evolink-cli' && data.evolink_cli_mcp_supported !== true) value = undefined;
29
+ if ((!value || newLogin) && data.evolink_cli_mcp_supported === true) {
30
+ value = { client_id: 'evolink-cli', issuer: data.issuer, token_endpoint_auth_method: 'none' };
31
+ await provider.saveClientInformation(value);
32
+ }
33
+ if (!value) {
34
+ requireThat(data.registration_endpoint, 'registration_unavailable', 'Passport does not support CLI client registration. Update the login service or retry later.');
35
+ const response = await fetchFn(data.registration_endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' },
36
+ body: JSON.stringify(provider.clientMetadata) });
37
+ requireThat(response.ok, 'registration_failed', 'Passport could not register this CLI login.');
38
+ value = await response.json();
39
+ requireThat(typeof value.client_id === 'string' && value.client_id.length > 0, 'invalid_client', 'Passport returned no public client ID.');
40
+ requireThat(!value.client_secret && value.token_endpoint_auth_method !== 'client_secret_basic', 'invalid_client', 'The CLI requires a public OAuth client.');
41
+ value = { client_id: value.client_id, issuer: data.issuer, token_endpoint_auth_method: 'none',
42
+ redirect_uris: value.redirect_uris ?? provider.clientMetadata.redirect_uris };
43
+ await provider.saveClientInformation(value);
44
+ }
45
+ return value;
46
+ }
47
+
48
+ async function token(provider, data, clientInfo, parameters, fetchFn) {
49
+ const response = await fetchFn(data.token_endpoint, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
50
+ body: new URLSearchParams({ client_id: clientInfo.client_id, resource: provider.server.href, ...parameters }) });
51
+ if (!response.ok) {
52
+ let code;
53
+ try { code = (await response.json()).error; } catch { /* Never echo credential-bearing response bodies. */ }
54
+ throw new CliError(code === 'invalid_grant' ? 'login_expired' : code === 'invalid_client' ? 'invalid_client' : 'login_unavailable',
55
+ code === 'invalid_grant' ? 'This login expired. Run evolink auth login.' : 'Passport could not complete this login. Retry auth login.');
56
+ }
57
+ const value = await response.json();
58
+ requireThat(typeof value.access_token === 'string' && value.access_token.length > 0 && value.token_type?.toLowerCase() === 'bearer'
59
+ && Number.isFinite(value.expires_in) && value.expires_in > 0 && (!value.issuer || value.issuer === data.issuer)
60
+ && (!value.scope || value.scope.split(' ').includes('mcp')), 'invalid_token_response', 'Passport returned an invalid login response.');
61
+ const prior = await provider.tokens();
62
+ const oldRefresh = parameters.grant_type === 'refresh_token' ? prior?.refresh_token : undefined;
63
+ requireThat(typeof value.refresh_token === 'string' && value.refresh_token.length > 0 || oldRefresh,
64
+ 'invalid_token_response', 'Passport returned no refresh credential.');
65
+ await provider.saveTokens({ ...value, refresh_token: value.refresh_token || oldRefresh, issuer: data.issuer });
66
+ return 'AUTHORIZED';
67
+ }
68
+
69
+ export async function refresh(provider, fetchFn) {
70
+ const data = await metadata(provider.server, fetchFn);
71
+ const info = await client(provider, data, fetchFn);
72
+ const saved = await provider.tokens();
73
+ requireThat(saved?.issuer === data.issuer && saved.refresh_token, 'login_required', 'Run evolink auth login.');
74
+ return token(provider, data, info, { grant_type: 'refresh_token', refresh_token: saved.refresh_token }, fetchFn);
75
+ }
76
+
77
+ export async function authorize(provider, fetchFn, authorizationCode) {
78
+ const data = await metadata(provider.server, fetchFn);
79
+ const info = await client(provider, data, fetchFn, !authorizationCode);
80
+ if (authorizationCode) return token(provider, data, info, { grant_type: 'authorization_code', code: authorizationCode,
81
+ redirect_uri: String(provider.redirectUrl), code_verifier: await provider.codeVerifier() }, fetchFn);
82
+ const verifier = randomBytes(32).toString('base64url');
83
+ await provider.saveCodeVerifier(verifier);
84
+ const url = new URL(data.authorization_endpoint);
85
+ url.search = new URLSearchParams({ client_id: info.client_id, response_type: 'code', redirect_uri: String(provider.redirectUrl),
86
+ scope: 'mcp offline_access', resource: provider.server.href, state: provider.state(),
87
+ code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256' }).toString();
88
+ await provider.redirectToAuthorization(url);
89
+ return 'REDIRECT';
90
+ }
@@ -0,0 +1,178 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and the Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any Contribution
81
+ embodied within the Work constitutes direct or contributory patent
82
+ infringement, then any patent licenses granted to You under this License
83
+ for that Work shall terminate as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the
86
+ Work or Derivative Works thereof in any medium, with or without
87
+ modifications, and in Source or Object form, provided that You
88
+ meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative Works
91
+ a copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices
94
+ stating that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works
97
+ that You distribute, all copyright, patent, trademark, and
98
+ attribution notices from the Source form of the Work,
99
+ excluding those notices that do not pertain to any part of
100
+ the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, You must include a readable copy of the
104
+ attribution notices contained within such NOTICE file, in
105
+ at least one of the following places: within a NOTICE text file
106
+ distributed as part of the Derivative Works; within the Source
107
+ form or documentation, if provided along with the Derivative Works;
108
+ or, within a display generated by the Derivative Works, if and
109
+ wherever such third-party notices normally appear. The contents
110
+ of the NOTICE file are for informational purposes only and
111
+ do not modify the License. You may add Your own attribution
112
+ notices within Derivative Works that You distribute, alongside
113
+ or as an addendum to the NOTICE text from the Work, provided
114
+ that such additional attribution notices cannot be construed
115
+ as modifying the License.
116
+
117
+ You may add Your own license statement for Your modifications and
118
+ may provide additional grant of rights to use, copy, modify, merge,
119
+ publish, distribute, sublicense, and/or sell copies of the
120
+ Contribution, either on an original or modified basis.
121
+
122
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
123
+ any Contribution intentionally submitted for inclusion in the Work
124
+ by You to the Licensor shall be under the terms and conditions of
125
+ this License, without any additional terms or conditions.
126
+ Notwithstanding the above, nothing herein shall supersede or modify
127
+ the terms of any separate license agreement you may have executed
128
+ with Licensor regarding such Contributions.
129
+
130
+ 6. Trademarks. This License does not grant permission to use the trade
131
+ names, trademarks, service marks, or product names of the Licensor,
132
+ except as required for reasonable and customary use in describing the
133
+ origin of the Work and reproducing the content of the NOTICE file.
134
+
135
+ 7. Disclaimer of Warranty. Unless required by applicable law or
136
+ agreed to in writing, Licensor provides the Work (and each
137
+ Contributor provides its Contributions) on an "AS IS" BASIS,
138
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
139
+ implied, including, without limitation, any warranties or conditions
140
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
141
+ PARTICULAR PURPOSE. You are solely responsible for determining the
142
+ appropriateness of using or reproducing the Work and assume any
143
+ risks associated with Your exercise of permissions under this License.
144
+
145
+ 8. Limitation of Liability. In no event and under no legal theory,
146
+ whether in tort (including negligence), contract, or otherwise,
147
+ unless required by applicable law (such as deliberate and grossly
148
+ negligent acts) or agreed to in writing, shall any Contributor be
149
+ liable to You for damages, including any direct, indirect, special,
150
+ incidental, or exemplary damages of any character arising as a
151
+ result of this License or out of the use or inability to use the
152
+ Work (including but not limited to damages for loss of goodwill,
153
+ work stoppage, computer failure or malfunction, or all other
154
+ commercial damages or losses), even if such Contributor has been
155
+ advised of the possibility of such damages.
156
+
157
+ 9. Accepting Warranty or Additional Liability. While redistributing
158
+ the Work or Derivative Works thereof, You may choose to offer,
159
+ and charge a fee for, acceptance of support, warranty, indemnity,
160
+ or other liability obligations and/or rights consistent with this
161
+ License. However, in accepting such obligations, You may offer only
162
+ conditions that are completely consistent with this License.
163
+
164
+ END OF TERMS AND CONDITIONS
165
+
166
+ Copyright 2024 EvoLink AI
167
+
168
+ Licensed under the Apache License, Version 2.0 (the "License");
169
+ you may not use this file except in compliance with the License.
170
+ You may obtain a copy of the License at
171
+
172
+ http://www.apache.org/licenses/LICENSE-2.0
173
+
174
+ Unless required by applicable law or agreed to in writing, software
175
+ distributed under the License is distributed on an "AS IS" BASIS,
176
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
177
+ See the License for the specific language governing permissions and
178
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ EvoLink platform operations
2
+ Copyright 2024 EvoLink AI
3
+
4
+ Derived from Evolink-AI/evolink-mcp, baseline acc9fd43b945e3917b47809fc94f85ba26c7c8db.
5
+ Modified for shared CLI REST and MCP operation execution.
6
+ Licensed under Apache-2.0; see LICENSE.
@@ -0,0 +1,95 @@
1
+ // Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
2
+ // Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
3
+ import { execFileSync } from 'node:child_process';
4
+ import { currentRequestCredentials, processCredentialsAllowed } from './request-context.js';
5
+ import { API_KEYS_URL } from './services/http-policy.js';
6
+ import { trackedLink } from './services/utm.js';
7
+ import { MCP_VERSION } from './version.js';
8
+ export class CredentialError extends Error {
9
+ constructor(message) { super(message); this.name = 'CredentialError'; }
10
+ }
11
+ const BASE_URLS = {
12
+ official: 'https://api.evolink.ai',
13
+ beta: 'https://beta-api.evolink.ai',
14
+ };
15
+ /**
16
+ * EVOLINK_BASE_URL overrides the channel default so the same build can point
17
+ * at canary/staging gateways (e.g. https://t-api.evolink.ai) without patching
18
+ * dist. HTTPS is required except for loopback development hosts.
19
+ */
20
+ function resolveBaseUrl(channel) {
21
+ const override = (process.env.EVOLINK_BASE_URL ?? '').trim().replace(/\/+$/, '');
22
+ if (!override)
23
+ return BASE_URLS[channel];
24
+ let parsed;
25
+ try {
26
+ parsed = new URL(override);
27
+ }
28
+ catch {
29
+ throw new Error(`EVOLINK_BASE_URL is not a valid URL: ${override}`);
30
+ }
31
+ const loopback = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';
32
+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && loopback)) {
33
+ throw new Error('EVOLINK_BASE_URL must use HTTPS (or HTTP on localhost).');
34
+ }
35
+ return override;
36
+ }
37
+ export function createConfig(channel) {
38
+ return {
39
+ channel,
40
+ baseUrl: resolveBaseUrl(channel),
41
+ };
42
+ }
43
+ /**
44
+ * The User-Agent of the hosted service's gateway calls. EvoLink's own services
45
+ * use "<service>/<version>"; the gateway records whether a signed-in call came
46
+ * through this service (mcp_via_service) and never authenticates by it.
47
+ */
48
+ export const MCP_SERVICE_USER_AGENT = `evolink-mcp-service/${MCP_VERSION}`;
49
+ /**
50
+ * Authentication headers for one gateway call. A signed-in hosted connection
51
+ * forwards its own Passport access token (key custody A) with the service
52
+ * User-Agent; everything else sends the caller's API key.
53
+ */
54
+ export function gatewayAuthHeaders() {
55
+ const channel = currentRequestCredentials()?.serviceChannel;
56
+ if (!channel)
57
+ return { 'Authorization': `Bearer ${getApiKey()}` };
58
+ return {
59
+ 'User-Agent': currentRequestCredentials()?.http?.userAgent ?? MCP_SERVICE_USER_AGENT,
60
+ 'Authorization': `Bearer ${channel.accessToken}`,
61
+ };
62
+ }
63
+ export function getApiKey() {
64
+ const scoped = currentRequestCredentials();
65
+ if (scoped) {
66
+ if (scoped.apiKey)
67
+ return scoped.apiKey;
68
+ throw new CredentialError(scoped.unavailableReason ?? 'No EvoLink credential is available for this request.');
69
+ }
70
+ if (!processCredentialsAllowed()) {
71
+ throw new CredentialError('No EvoLink credential is available for this request.');
72
+ }
73
+ const configured = process.env.EVOLINK_API_KEY?.trim();
74
+ if (configured)
75
+ return configured;
76
+ const helper = process.env.EVOLINK_CREDENTIAL_HELPER?.trim() || 'evolink';
77
+ if (helper.includes('\0'))
78
+ throw new CredentialError('EVOLINK_CREDENTIAL_HELPER is invalid');
79
+ try {
80
+ const key = execFileSync(helper, ['credential', 'get'], {
81
+ encoding: 'utf8',
82
+ timeout: 5_000,
83
+ maxBuffer: 64 * 1024,
84
+ stdio: ['ignore', 'pipe', 'pipe'],
85
+ }).trim();
86
+ if (key)
87
+ return key;
88
+ }
89
+ catch {
90
+ // Return one stable recovery message without echoing helper stderr or key material.
91
+ }
92
+ throw new CredentialError(`No EvoLink API key is available. Set EVOLINK_API_KEY to a key from ${trackedLink(API_KEYS_URL, 'api_keys')}, ` +
93
+ 'or set EVOLINK_CREDENTIAL_HELPER to an API-key helper that implements `credential get`. ' +
94
+ 'The browser-login @evolinkai/cli does not export API keys; use its own `evolink auth login` workflow or hosted MCP for OAuth.');
95
+ }