@evolinkai/cli 0.9.1 → 0.10.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.
package/README.md CHANGED
@@ -40,12 +40,14 @@ else
40
40
  fi
41
41
  ```
42
42
 
43
- Check Node.js and npm separately when installation is needed. In PowerShell, use `Get-Command evolink -ErrorAction SilentlyContinue` inside an `if`. If installation already succeeded, check PATH and the active Node/npm installation. Do not suppress actual version, runtime or installation failures with `|| true`. `auth status --json` returning `ok: true` and `authenticated: false` means sign-in is needed; an error should be resolved before login.
43
+ Check Node.js and npm separately when installation is needed. In PowerShell, use `Get-Command evolink -ErrorAction SilentlyContinue` inside an `if`. If installation already succeeded, check PATH and the active Node/npm installation. Do not suppress actual version, runtime or installation failures with `|| true`. `auth status --json` returning `ok: true` and `authenticated: false` means sign-in is needed; an error should be resolved before login. A saved login reports `access_token_expires_at`; the short-lived access token renews automatically before each command, so an elapsed time there is not an expired login. Verify a saved login with `evolink balance --json`, and sign in again only on `authenticated: false` or a `login_required`/`login_expired` error.
44
44
 
45
45
  The skill is bundled with the package. By default it installs into `~/.agents/skills/evolink-cli` (Codex, Cursor, Gemini CLI, OpenCode and Copilot CLI), `~/.claude/skills/evolink-cli` (Claude Code), `~/.openclaw/skills/evolink-cli` (OpenClaw) and `~/.hermes/skills/evolink-cli` (Hermes). Select one with `skills install --agent NAME`; run `--help` for the supported names. Verify discovery in the assistant rather than treating a written skill file as proof of integration. Browser-only chat assistants should keep using the hosted MCP connection. See [Claude Code skill locations](https://code.claude.com/docs/en/skills) and [Cursor skill locations](https://cursor.com/docs/skills).
46
46
 
47
47
  After upgrading the npm package, run `evolink skills install` again to refresh the installed skill copies, then verify that the assistant discovers the updated skill. Open a new conversation only if discovery does not refresh. Fix reusable guidance in `skills/evolink-cli/SKILL.md` in this package; editing only a local installed copy will not distribute the fix.
48
48
 
49
+ `setup`, `doctor` and `auth login` compare the installed version with the latest npm release and report `update`; other commands print a short notice at most once a day (see [Update notices](#update-notices)). A bilingual local callback page after browser approval, instead of a return to evolink.ai, means the installed CLI is older than 0.9.1: upgrade, then run `evolink skills install`.
50
+
49
51
  ## Setup and skill updates
50
52
 
51
53
  Starting with CLI 0.6.0, use the selected assistant's name:
@@ -72,6 +74,22 @@ Replacement backs up the previous skill directory under `~/.evolink-media/skill-
72
74
 
73
75
  For an idempotent installation prompt, check Node.js 22+ and `evolink --version` before installing; reuse a suitable installed CLI. In a released version supporting `setup`, use it with the current assistant's name. With older versions, retain the four separate setup steps above, reuse a working login, and explicitly verify balance, model discovery and assistant skill discovery. Installation authorization does not authorize a paid test generation.
74
76
 
77
+ ## Update notices
78
+
79
+ Starting with CLI 0.10.0, `setup`, `doctor` and `auth login` ask the npm registry for the latest `@evolinkai/cli` release every time and report `update`: `status` (`available`, `current`, `unknown` or `disabled`), `update_available`, `current_version`, `latest_version` and the update `command`. An available update is guidance only; it never fails setup or doctor, and login and setup print one extra progress line.
80
+
81
+ Other commands, except the offline `auth status`, reuse a registry answer from the last 24 hours, or ask again. When a newer stable release exists, they print one line on stderr after the command's own output:
82
+
83
+ ```text
84
+ EvoLink CLI 0.10.1 is available (installed 0.10.0). Update with npm install -g @evolinkai/cli@latest, then run evolink skills install.
85
+ ```
86
+
87
+ The same release is announced at most once a day; stdout and `--json` envelopes are unchanged, and the notice never changes the exit code. A check sends one anonymous `GET` for the package's dist-tags to `registry.npmjs.org` with the CLI User-Agent, waits at most 3 seconds, and stores its result in the state directory (`update-check/npm.json`). It uses the same `fetch` as the CLI's other requests, so proxy settings such as Node's `NODE_USE_ENV_PROXY=1` with `HTTPS_PROXY` apply alike; a request still open at the deadline does not keep the process running. Help output, invalid commands and loopback test resources never trigger it.
88
+
89
+ Set `EVOLINK_CLI_UPDATE_CHECK=0` to turn these checks off; `NO_UPDATE_NOTIFIER` with any value (the update-notifier convention) and a `CI` variable other than `0` or `false` also turn them off. To check by hand, compare `evolink --version` with `npm view @evolinkai/cli version`, or watch the repository's GitHub Releases (`cli-v*` tags).
90
+
91
+ Without `--agent`, `evolink doctor` also inspects installed skill copies for all supported assistants. `skills.status` is `not_installed`, `current`, `outdated`, `needs_attention` or `unavailable`. Outdated copies add guidance to run `evolink skills install`; local changes and conflicts are reported without being replaced. These findings do not change `ok`; `doctor --agent NAME` keeps checking the selected skill as a required step.
92
+
75
93
  ## Quoted generation
76
94
 
77
95
  ```sh
@@ -224,7 +242,7 @@ See [Gemini trusted folders](https://geminicli.com/docs/cli/trusted-folders/) an
224
242
 
225
243
  Generation errors preserve the saved quote and request ID when acceptance or charging is uncertain. `charged: no` alone does not authorize a new request: `submission_state` must also establish `not_submitted` or `rejected`. Recover uncertain submissions with the original quote, and query a known task. A new generation needs a fresh estimate and user approval.
226
244
 
227
- A failed/cancelled task does not establish a refund. `tasks get` can successfully return that task, while `tasks wait` exits nonzero with the same task and billing details. `billing.refund_status` reports account-balance evidence: `unknown`, `pending`, `failed`, `completed`, or `not_required`. A completed refund includes recorded credits and time; key-limit restoration remains unknown. Old gateways without billing fields retain unknown status, rather than claiming zero charge or a completed refund.
245
+ A failed task is not charged: the credits reserved at submission are returned automatically, as `billing_note` says. Its `error.code` and `error.message` are what the API reports (the message on one line, without secrets, service addresses or links other than EvoLink docs); `channel_*` codes, which concern EvoLink's own upstream accounts, are reported as `service_unavailable`. A cancelled task does not establish a refund. `tasks get` can successfully return a failed task, while `tasks wait` exits nonzero with `task_failed`, a message naming the error code, and the same task and billing details. `billing.refund_status` reports account-balance evidence: `unknown`, `pending`, `failed`, `completed`, or `not_required`. A completed refund includes recorded credits and time; key-limit restoration remains unknown. Without billing fields the status stays `unknown`: a failed task still carries the `billing_note`, but no completed refund is claimed.
228
246
 
229
247
  ### Rules estimates and refresh
230
248
 
package/bin/evolink.mjs CHANGED
@@ -7,4 +7,11 @@ if (Number(process.versions.node.split('.')[0]) < 22) {
7
7
  } else {
8
8
  const { main } = await import('../src/cli.mjs');
9
9
  await main();
10
+ // A registry request given up at its deadline can keep a socket open for minutes (for example through a
11
+ // proxy that never answers). The command is complete: write out its output, then exit instead of waiting.
12
+ const { abandonedUpdateChecks } = await import('../src/update.mjs');
13
+ if (abandonedUpdateChecks()) {
14
+ for (const stream of [process.stdout, process.stderr]) await new Promise(resolve => stream.write('', resolve));
15
+ process.exit();
16
+ }
10
17
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evolinkai/cli",
3
- "version": "0.9.1",
3
+ "version": "0.10.1",
4
4
  "description": "Generate images, video and audio with EvoLink, with browser login and quoted submissions.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -31,10 +31,12 @@ fi
31
31
 
32
32
  In PowerShell, use `Get-Command evolink -ErrorAction SilentlyContinue` inside an `if` instead. A missing command is not an EvoLink service failure. If setup is requested and installation is permitted, check Node.js 22+ and npm separately, install `npm install -g @evolinkai/cli`, then verify `evolink --version`. If installation was already reported successful, check PATH and the active Node/npm installation before reinstalling. Do not hide a broken installed command, unsupported runtime or denied installation with `|| true`.
33
33
 
34
- Check `evolink --version` and `evolink --help` before choosing setup commands. For versions supporting it, use `evolink setup --agent NAME --json` with the current assistant's supported name. It reuses a verified login, installs the bundled skill and checks balance and model discovery without submitting paid tasks. If this command is unavailable, use `auth status` (a successful response with `authenticated: false` means login is needed), `auth login` when needed, `skills install --agent NAME`, `balance` and `models search --limit 1` separately.
34
+ Check `evolink --version` and `evolink --help` before choosing setup commands. For versions supporting it, use `evolink setup --agent NAME --json` with the current assistant's supported name. It reuses a verified login, installs the bundled skill and checks balance and model discovery without submitting paid tasks. If this command is unavailable, use `auth status` (a successful response with `authenticated: false` means login is needed), `auth login` when needed, `skills install --agent NAME`, `balance` and `models search --limit 1` separately. `auth status` is offline: it reports the saved login and `access_token_expires_at`, the expiry of a short-lived access token that the CLI renews automatically before each command. An elapsed time there does not mean the login expired and is not a reason to run `auth login`; confirm a saved login with `balance --json`, and sign in again only on `authenticated: false` or a `login_required`/`login_expired` error.
35
35
 
36
36
  Let the user sign in and approve in the browser. If the browser does not open, show the printed authorization link. Keep the login process alive until it finishes; the default wait is 180 seconds, and supported versions accept `auth login --timeout SECONDS` (30–900). After timeout or interruption, start a new login and use its new link. A browser approval page alone does not prove connection. For a network error with a saved login, retry the failed free check rather than logging in again.
37
37
 
38
+ `setup`, `doctor` and `auth login` report `update` with `status`, `update_available` and `latest_version` from the npm registry; since CLI 0.10.0 other commands except the offline `auth status` may also print one stderr line beginning `EvoLink CLI X is available`, at most once a day. Neither is a command failure; loopback test servers and `EVOLINK_CLI_UPDATE_CHECK=0` skip the check. When an update is available, or browser approval ends on a bilingual 127.0.0.1 page instead of returning to evolink.ai (a CLI older than 0.9.1), upgrade with `npm install -g @evolinkai/cli@latest`, then run `skills install --agent NAME` and confirm the assistant reloaded the skill. During a requested setup, upgrade before continuing; otherwise tell the user and upgrade only after the user agrees, finishing or pausing an in-progress quote, generation or delivery first. Do not turn the check off unless the user asks.
39
+
38
40
  `skills status --agent NAME --json` compares installed resources with this CLI's bundle. Updating the npm package alone does not refresh previously installed skill copies. After upgrading the CLI, run `skills install` to synchronize them. On `skill_modified`, preserve the user's edits; use `--replace-modified` only when the user explicitly chooses replacement, which creates a backup. A written file or `assistant_discovery: not_checked` is not proof that the assistant loaded the skill. Confirm discovery in the current assistant; reopen the conversation only if it cannot refresh. Do not edit an installed skill copy as a substitute for fixing the package source.
39
41
 
40
42
  If the assistant host denies a tool call, stop and explain the required permission. Keep the original budget and input; do not remove spending caps, rewrite the command to evade checks, or switch transports after a denial. Gemini CLI noninteractive sessions may block parameters discovered from tool output; use its interactive permission flow, or a separately configured native EvoLink MCP connection in a new session when the user chooses that route. For Gemini native MCP, check `gemini mcp list` in the intended workspace, review workspace trust through its normal permission flow, and verify a real read-only EvoLink call. Headless MCP permissions use scoped `mcpName` policy rules; do not silently grant generation permission or count an exit without tool calls as successful integration.
@@ -77,9 +79,9 @@ The saved model and input are the submitted model and input. A changed or expire
77
79
 
78
80
  Use `generate` for the first submission of an approved quote. `tasks resume` is only for a submission whose reply was lost or whose outcome is unknown; it is not a quote-status command. If it returns `submission_not_started`, no task exists: use the original already-approved quote with `generate`, without creating another quote.
79
81
 
80
- Use `--json` for commands consumed by the assistant. Progress is on stderr; stdout is one JSON envelope with `schema_version: 1`. `ok: false` and a nonzero exit code indicate a command error; a successful task query reporting `status: failed` is a task outcome, not a failed CLI invocation. Read the error's recovery details before retrying. For `invalid_status`, use `error.details.allowed_values` and correct only the free query; local status validation occurs before a platform request. Never guess an enum, interpret an empty list as a service failure, or resubmit a paid task to fix a query error. Run `evolink --help` for the maintained command reference and `evolink tasks list --help` for task filters.
82
+ Use `--json` for commands consumed by the assistant. Progress is on stderr; stdout is one JSON envelope with `schema_version: 1`. `ok: false` and a nonzero exit code indicate a command error; a successful task query reporting `status: failed` is a task outcome, not a failed CLI invocation. Tell the user its `error.code` and `error.message` (EvoLink's explanation). A failed task is not charged; the credits reserved at submission are returned automatically (`billing_note`). Read the error's recovery details before retrying. For `invalid_status`, use `error.details.allowed_values` and correct only the free query; local status validation occurs before a platform request. Never guess an enum, interpret an empty list as a service failure, or resubmit a paid task to fix a query error. Run `evolink --help` for the maintained command reference and `evolink tasks list --help` for task filters.
81
83
 
82
- For setup problems, run `evolink doctor --agent NAME --json` if the installed version supports the agent option; otherwise use `doctor --json`. Read every failed or skipped check. On Linux, login and later commands need the same unlocked Secret Service/D-Bus session. On SSH hosts, opening the link on another computer requires forwarding the loopback callback port; `--no-browser` does not solve callback routing. Report connection, model discovery and assistant skill discovery separately.
84
+ For setup problems, run `evolink doctor --agent NAME --json` if the installed version supports the agent option; otherwise use `doctor --json`. Read every failed or skipped check and every `guidance` entry; without `--agent`, outdated or modified skill copies appear in `guidance` and `skills` without failing the check. On Linux, login and later commands need the same unlocked Secret Service/D-Bus session. On SSH hosts, opening the link on another computer requires forwarding the loopback callback port; `--no-browser` does not solve callback routing. Report connection, model discovery and assistant skill discovery separately.
83
85
 
84
86
 
85
87
  Estimates use published full pricing rules and show public default prices, excluding
package/src/auth.mjs CHANGED
@@ -2,6 +2,7 @@ import http from 'node:http';
2
2
  import { randomBytes, randomUUID } from 'node:crypto';
3
3
  import { spawn } from 'node:child_process';
4
4
  import { authorize, refresh, metadata } from './oauth.mjs';
5
+ import { updateAdvice } from './update.mjs';
5
6
  import { hash } from './state.mjs';
6
7
  import { authFetch, ISSUER, SERVER, SITE } from './network.mjs';
7
8
  import { CliError, requireThat } from './errors.mjs';
@@ -57,8 +58,10 @@ export class OAuthProvider {
57
58
  const issuer = this.server.href === SERVER ? ISSUER : this.server.origin;
58
59
  requireThat(tokens.issuer === issuer && tokens.token_type?.toLowerCase() === 'bearer', 'invalid_token_response', 'The login service returned an unsupported token.');
59
60
  const prior = await this.vault.read();
61
+ // A refresh keeps the original sign-in time; status shows it as logged_in_at.
62
+ const loggedInAt = this.newLogin ? new Date().toISOString() : prior?.logged_in_at;
60
63
  await this.vault.write({ tokens, binding: this.newLogin ? randomUUID() : prior?.binding || randomUUID(),
61
- expires_at: Date.now() + (tokens.expires_in ?? 300) * 1000 });
64
+ expires_at: Date.now() + (tokens.expires_in ?? 300) * 1000, ...(loggedInAt ? { logged_in_at: loggedInAt } : {}) });
62
65
  }
63
66
  async saveCodeVerifier(value) { this.verifier = value; }
64
67
  async codeVerifier() { requireThat(this.verifier, 'login_expired', 'Start login again.'); return this.verifier; }
@@ -86,6 +89,9 @@ export function openBrowser(url, onFailure = () => {}) {
86
89
  * page language itself (its saved choice, then the browser language, English otherwise). */
87
90
  export const LOGIN_LANDING_URL = `${SITE}/mcp?login=cli`;
88
91
 
92
+ /** Shown with auth status so an assistant does not treat a lapsed access token as an expired login. */
93
+ export const STATUS_NOTE = 'The access token is short-lived and renews automatically before each command, so an elapsed access_token_expires_at does not mean the login expired. Verify the login with evolink balance --json; sign in again only when authenticated is false or a command reports login_required or login_expired.';
94
+
89
95
  export async function callbackListener({ state, issuer, timeout = 180_000, signal }) {
90
96
  let settled = false;
91
97
  let resolveCode, rejectCode;
@@ -155,10 +161,12 @@ export class Credentials {
155
161
  return { access_token: saved.tokens.access_token, binding: saved.binding };
156
162
  });
157
163
  }
158
- async login({ noBrowser = false, timeout = 180_000, progress = () => {}, browser = openBrowser, signal } = {}) {
164
+ async login({ noBrowser = false, timeout = 180_000, progress = () => {}, browser = openBrowser, signal, update } = {}) {
159
165
  requireThat(!this.token, 'invalid_option', 'auth login cannot use --token-stdin.');
160
166
  requireThat(Number.isInteger(timeout) && timeout >= 30_000 && timeout <= 900_000, 'invalid_option', 'Login timeout must be between 30 and 900 seconds.');
161
167
  return this.lock(async () => {
168
+ // The registry request runs alongside the browser approval and never changes the login outcome.
169
+ const updating = update?.().catch(() => undefined);
162
170
  progress('Login: preparing browser authorization.');
163
171
  await this.vault.read();
164
172
  const provider = this.provider();
@@ -186,14 +194,34 @@ export class Credentials {
186
194
  }
187
195
  requireThat(result === 'AUTHORIZED', 'login_failed', 'Login could not finish.');
188
196
  progress('Login: complete. Verify the connection with evolink balance --json.');
189
- return { authenticated: true, server: this.server.href, credential_storage: 'os_keyring' };
197
+ const outcome = { authenticated: true, server: this.server.href, credential_storage: 'os_keyring' };
198
+ // Say now when this release is behind, while the terminal is still in front of the user.
199
+ const updateInfo = await updating;
200
+ if (updateInfo) {
201
+ outcome.update = updateInfo;
202
+ const advice = updateAdvice(updateInfo);
203
+ if (advice) progress(advice);
204
+ }
205
+ return outcome;
206
+ } catch (error) {
207
+ // An outdated release is a likely reason for a failed login; an interrupted one needs no hint.
208
+ const hint = error.code !== 'interrupted' && updateAdvice(await updating);
209
+ if (hint) progress(hint);
210
+ throw error;
190
211
  } finally { await listener.close(); }
191
212
  });
192
213
  }
214
+ /** Offline view of the saved login. The access token renews itself before each command, so an elapsed
215
+ * access_token_expires_at is not an expired login; only a failed renewal (login_expired) is. */
193
216
  async status() {
194
217
  if (this.token) return { authenticated: true, credential_storage: 'stdin', server: this.server.href };
195
218
  const saved = await this.vault.read();
196
- return { authenticated: !!saved?.tokens, server: this.server.href, credential_storage: 'os_keyring', expires_at: saved ? new Date(saved.expires_at).toISOString() : undefined };
219
+ if (!saved?.tokens) return { authenticated: false, server: this.server.href, credential_storage: 'os_keyring', text: `Not signed in to ${this.server.href}. Run evolink auth login.` };
220
+ return { authenticated: true, server: this.server.href, credential_storage: 'os_keyring',
221
+ ...(saved.logged_in_at ? { logged_in_at: saved.logged_in_at } : {}),
222
+ access_token_expires_at: Number.isFinite(saved.expires_at) ? new Date(saved.expires_at).toISOString() : undefined,
223
+ access_token_renewal: 'automatic', login_check: 'evolink balance --json', note: STATUS_NOTE,
224
+ text: `Signed in to ${this.server.href}; credentials are in the OS keyring. ${STATUS_NOTE}` };
197
225
  }
198
226
  async logout() {
199
227
  requireThat(!this.token, 'invalid_option', 'auth logout requires the stored login.');
package/src/cli.mjs CHANGED
@@ -10,6 +10,7 @@ import { commandHelp } from './help.mjs';
10
10
  import { installSkill, skillStatus, validateAgent } from './skills.mjs';
11
11
  import { doctor } from './doctor.mjs';
12
12
  import { setup } from './setup.mjs';
13
+ import { checkForUpdate, updateNotice } from './update.mjs';
13
14
  import { CLI_VERSION } from './version.mjs';
14
15
  import { CliError, requireThat, errorView, localFile } from './errors.mjs';
15
16
 
@@ -52,7 +53,7 @@ const HELP = `EvoLink CLI ${CLI_VERSION} (Node.js 22+)
52
53
  Reuse or finish login, install skills and verify (free)
53
54
  auth login [--no-browser] [--timeout SECONDS]
54
55
  Sign in; keep this command running for the callback
55
- auth status | auth logout Check or revoke this CLI session
56
+ auth status | auth logout Check the saved login offline, or revoke it
56
57
  balance Verify connection and account balance (free)
57
58
  models search [--query TEXT] [--type image|video|audio|all] [--limit N]
58
59
  models show MODEL Read parameters and pricing (free)
@@ -79,7 +80,8 @@ const HELP = `EvoLink CLI ${CLI_VERSION} (Node.js 22+)
79
80
  skills install [--agent NAME] [--replace-modified]
80
81
  Install or update; back up replaced files
81
82
  skills status [--agent NAME] Check installed skill content and CLI version
82
- doctor [--agent NAME] Check prerequisites, connection, models and skills (free)
83
+ doctor [--agent NAME] Check prerequisites, connection, models, skills
84
+ and CLI updates (free)
83
85
 
84
86
  Options: --json, --server RESOURCE_URL, --api-url URL, --files-url URL,
85
87
  --token-stdin, --help, --version
@@ -94,6 +96,9 @@ Run evolink tasks list --help for filter details and recovery caveats.
94
96
  Each command accepts --help --json for its machine-readable command reference.
95
97
  Model/docs/usage capabilities come from the bundled shared platform module.
96
98
  After upgrading the package, run evolink skills install to refresh its skill.
99
+ setup, doctor and auth login report update.update_available with the latest release;
100
+ other commands except auth status print one stderr line, at most once a day, when a
101
+ newer release exists. EVOLINK_CLI_UPDATE_CHECK=0 turns these npm registry checks off.
97
102
 
98
103
  Login timeout: 30-900 seconds, default 180. On SSH, forward the callback port.
99
104
  The CLI verifies skill files; your assistant must confirm it loads evolink-cli.
@@ -102,6 +107,9 @@ Spending caps protect the estimate at submission, not final settlement.
102
107
  Ctrl-C stops local waiting; submitted tasks continue on EvoLink.
103
108
  `;
104
109
 
110
+ // setup, doctor and auth login report the update status in their own result; auth status stays offline.
111
+ const NO_UPDATE_NOTICE = new Set(['setup', 'doctor', 'auth login', 'auth status']);
112
+
105
113
  const OPTIONS = Object.fromEntries(['server', 'api-url', 'files-url', 'query', 'type', 'limit', 'model', 'modality', 'view', 'product-id', 'operation', 'lifecycle', 'input', 'input-file', 'prompt', 'media-seconds',
106
114
  'pricing-source', 'pricing-parameters', 'refresh-quote', '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' }]));
107
115
  for (const k of ['json', 'token-stdin', 'no-browser', 'replace-modified', 'confirm', 'wait', 'all', 'resume', 'help', 'version']) OPTIONS[k] = { type: 'boolean' };
@@ -195,12 +203,15 @@ async function estimateArgs(options) {
195
203
  return { model: options.model, input, ...(pricingParameters !== undefined ? { pricing_parameters: pricingParameters } : {}), ...(options['pricing-source'] ? { pricing_source: options['pricing-source'] } : {}), ...(media !== undefined ? { media_seconds: media } : {}), ...(cap !== undefined ? { max_cost_usd: cap } : {}) };
196
204
  }
197
205
 
198
- export async function dispatch(positionals, options, { state, server, credentials, client, mcp = client, signal, progress, skillHome }) {
206
+ export async function dispatch(positionals, options, { state, server, credentials, client, mcp = client, signal, progress, skillHome, updates }) {
207
+ // login, setup and doctor always ask the registry and report the outcome, including a disabled check;
208
+ // loopback test resources never contact it.
209
+ const update = () => checkForUpdate({ state, server, force: true, signal, ...updates });
199
210
  client = mcp;
200
211
  const [command, action, id] = positionals;
201
212
  const media = new Media({ client, state, server });
202
213
  if (command === 'auth') {
203
- if (action === 'login') return credentials.login({ noBrowser: options['no-browser'], timeout: options.timeout === undefined ? undefined : Number(options.timeout) * 1000, signal, progress });
214
+ if (action === 'login') return credentials.login({ noBrowser: options['no-browser'], timeout: options.timeout === undefined ? undefined : Number(options.timeout) * 1000, signal, progress, update });
204
215
  if (action === 'status') return credentials.status();
205
216
  if (action === 'logout') return credentials.logout();
206
217
  }
@@ -274,8 +285,8 @@ export async function dispatch(positionals, options, { state, server, credential
274
285
  if (command === 'skills' && action === 'install') return installSkill({ home: skillHome, agent: options.agent, replaceModified: options['replace-modified'] });
275
286
  if (command === 'skills' && action === 'status') return skillStatus({ home: skillHome, agent: options.agent });
276
287
  if (command === 'setup') return setup({ state, server, credentials, client, agent: options.agent, skillHome,
277
- noBrowser: options['no-browser'], timeout: options.timeout === undefined ? undefined : Number(options.timeout) * 1000, signal, progress });
278
- if (command === 'doctor') return doctor({ state, server, credentials, client, agent: options.agent, skillHome });
288
+ noBrowser: options['no-browser'], timeout: options.timeout === undefined ? undefined : Number(options.timeout) * 1000, signal, progress, update });
289
+ if (command === 'doctor') return doctor({ state, server, credentials, client, agent: options.agent, skillHome, update });
279
290
  throw new CliError('unknown_command', 'Unknown command or missing argument. Run evolink --help.');
280
291
  }
281
292
 
@@ -294,17 +305,29 @@ async function stdinToken(stream) {
294
305
  return token;
295
306
  }
296
307
 
297
- export async function main(argv = process.argv.slice(2), io = { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin }) {
308
+ export async function main(argv = process.argv.slice(2), io = { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin },
309
+ { env = process.env, fetchFn, now, timeout, updateState } = {}) {
298
310
  let options = { json: argv.includes('--json') };
299
311
  const controller = new AbortController();
300
312
  const interrupt = () => controller.abort();
301
313
  process.once('SIGINT', interrupt);
302
314
  process.once('SIGTERM', interrupt);
315
+ // The update notice follows the command's own output on stderr; stdout stays one envelope.
316
+ let update;
317
+ const updates = { env, fetchFn, now, timeout };
318
+ const checkUpdate = server => {
319
+ // Building the state path can throw (for example without a home directory); that never fails the command.
320
+ update = Promise.resolve().then(() => updateNotice({ state: updateState || new State(), server, signal: controller.signal, ...updates }))
321
+ .catch(() => undefined);
322
+ };
303
323
  try {
304
324
  let positionals;
305
325
  try { ({ values: options, positionals } = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true })); }
306
326
  catch { throw new CliError('invalid_option', 'Invalid command option. Run evolink --help.'); }
307
- if (options.version) { io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, version: CLI_VERSION }) + '\n' : CLI_VERSION + '\n'); return; }
327
+ if (options.version) {
328
+ checkUpdate();
329
+ io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, version: CLI_VERSION }) + '\n' : CLI_VERSION + '\n'); return;
330
+ }
308
331
  if (options.help || !positionals.length) {
309
332
  const reference = commandHelp(positionals);
310
333
  const help = options.help && positionals.length === 2 && positionals[0] === 'tasks' && positionals[1] === 'list' ? TASKS_LIST_HELP : reference?.help || HELP;
@@ -316,7 +339,9 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
316
339
  const token = options['token-stdin'] ? await stdinToken(io.stdin) : undefined;
317
340
  const credentials = new Credentials({ server, state, token });
318
341
  const client = new Api(credentials, { signal: controller.signal, apiUrl: options['api-url'], filesUrl: options['files-url'] });
319
- const result = publicView(await dispatch(positionals, options, { state, server, credentials, client, signal: controller.signal, progress: message => io.stderr.write(message + '\n') }));
342
+ // Only a fully validated command checks: invalid tokens and service URLs fail without contacting npm.
343
+ if (!NO_UPDATE_NOTICE.has(positionals[0]) && !NO_UPDATE_NOTICE.has(positionals.slice(0, 2).join(' '))) checkUpdate(server);
344
+ const result = publicView(await dispatch(positionals, options, { state, server, credentials, client, signal: controller.signal, progress: message => io.stderr.write(message + '\n'), updates }));
320
345
  const view = { schema_version: 1, ...result, ok: result.ok !== false };
321
346
  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` : ''}`);
322
347
  if (!view.ok) process.exitCode = view.error?.code === 'interrupted' ? 130 : 1;
@@ -324,5 +349,10 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
324
349
  const view = { schema_version: 1, ok: false, error: errorView(error) };
325
350
  (options.json ? io.stdout : io.stderr).write(options.json ? JSON.stringify(view) + '\n' : `${view.error.code}: ${view.error.message}\n${view.error.details ? JSON.stringify(view.error.details, null, 2) + '\n' : ''}`);
326
351
  process.exitCode = error.exitCode || (controller.signal.aborted ? 130 : 1);
327
- } finally { process.removeListener('SIGINT', interrupt); process.removeListener('SIGTERM', interrupt); }
352
+ } finally {
353
+ // Ctrl-C while the check finishes stops the check, not the completed command.
354
+ const notice = await update;
355
+ process.removeListener('SIGINT', interrupt); process.removeListener('SIGTERM', interrupt);
356
+ if (notice && !controller.signal.aborted) io.stderr.write(notice + '\n');
357
+ }
328
358
  }
package/src/doctor.mjs CHANGED
@@ -3,6 +3,18 @@ import path from 'node:path';
3
3
  import { CliError, errorView, requireThat } from './errors.mjs';
4
4
  import { skillStatus } from './skills.mjs';
5
5
  import { CLI_VERSION } from './version.mjs';
6
+ import { updateAdvice } from './update.mjs';
7
+
8
+ const SKILL_REFRESH = new Set(['outdated', 'legacy', 'unmanaged']);
9
+ // Without --agent, report installed copies only: a CLI used without skills is healthy.
10
+ function installedSkills(result) {
11
+ const installations = result.installations.filter(i => i.status !== 'missing')
12
+ .map(({ path: file, status, installed_cli_version }) => ({ path: file, status, installed_cli_version }));
13
+ const status = !installations.length ? 'not_installed'
14
+ : installations.some(i => i.status !== 'current' && !SKILL_REFRESH.has(i.status)) ? 'needs_attention'
15
+ : installations.some(i => SKILL_REFRESH.has(i.status)) ? 'outdated' : 'current';
16
+ return { agent: 'all', status, cli_version: result.cli_version, installations };
17
+ }
6
18
 
7
19
  export async function prerequisites({ state, credentials, version = process.version, platform = process.platform }) {
8
20
  const checks = [];
@@ -21,7 +33,11 @@ export async function prerequisites({ state, credentials, version = process.vers
21
33
  finally { await fs.rm(probe, { recursive: true, force: true }); }
22
34
  return { writable: true };
23
35
  });
24
- const auth = await check('credential_storage', () => credentials.status());
36
+ const auth = await check('credential_storage', async () => {
37
+ // The offline explanation stays out of the check row; doctor verifies the login itself.
38
+ const { text, note, ...view } = await credentials.status();
39
+ return view;
40
+ });
25
41
  return { runtime, storage, auth, checks };
26
42
  }
27
43
  export async function verifyModels(client) {
@@ -31,8 +47,10 @@ export async function verifyModels(client) {
31
47
  return { verified: true, models_available: true };
32
48
  }
33
49
  export async function doctor({ state, server, credentials, client, mcp = client, version = process.version, platform = process.platform,
34
- remote = !!process.env.SSH_CONNECTION, agent, skillHome }) {
50
+ remote = !!process.env.SSH_CONNECTION, agent, skillHome, update }) {
35
51
  client = mcp;
52
+ // The registry request runs alongside the account checks and never fails doctor.
53
+ const updating = update?.().catch(() => undefined);
36
54
  const { runtime, storage, auth, checks } = await prerequisites({ state, credentials, version, platform });
37
55
  const login = auth?.authenticated === true;
38
56
  if (auth) checks.push(login ? { name: 'login', status: 'passed' } : {
@@ -52,18 +70,28 @@ export async function doctor({ state, server, credentials, client, mcp = client,
52
70
  try { const details = await verifyModels(client); models = true; checks.push({ name: 'models', status: 'passed', ...details }); }
53
71
  catch (error) { checks.push({ name: 'models', status: 'failed', error: errorView(error) }); }
54
72
  } else checks.push({ name: 'models', status: 'skipped', reason: 'Verify the account connection first.' });
55
- let skills;
73
+ let skills, installed;
56
74
  if (agent !== undefined) {
57
75
  try {
58
76
  skills = await skillStatus({ home: skillHome, agent });
59
77
  checks.push({ name: 'skills', status: skills.current ? 'passed' : 'failed', ...skills });
60
78
  } catch (error) { checks.push({ name: 'skills', status: 'failed', error: errorView(error) }); }
79
+ } else {
80
+ try { installed = installedSkills(await skillStatus({ home: skillHome })); }
81
+ catch (error) { installed = { agent: 'all', status: 'unavailable', error: errorView(error) }; }
61
82
  }
83
+ // An available update is guidance, not a failed check.
84
+ const updateInfo = await updating;
62
85
  const guidance = [];
86
+ const advice = updateAdvice(updateInfo);
87
+ if (advice) guidance.push(advice);
63
88
  if (platform === 'linux') guidance.push('Linux needs an unlocked Secret Service keyring in the current D-Bus session. Run login and later commands in that same session; tokens are never saved to plaintext files.');
64
89
  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.');
90
+ if (installed?.status === 'outdated') guidance.push(`Installed evolink-cli skill files are older than CLI ${CLI_VERSION}. Run evolink skills install, then ask your assistant to reload the skill.`);
91
+ if (installed?.status === 'needs_attention') guidance.push('An installed evolink-cli skill has local changes or conflicts with another skill. Review evolink skills status --json; replace local changes only by choice with --replace-modified.');
65
92
  return { ok: !!runtime && !!storage && connected && models && (agent === undefined || skills?.current === true),
66
- cli_version: CLI_VERSION, node: version, server: server.href, ...(auth ? { auth } : {}),
93
+ cli_version: CLI_VERSION, node: version, server: server.href, ...(auth ? { auth } : {}), ...(updateInfo ? { update: updateInfo } : {}),
67
94
  ...(authorization ? { authorization } : {}), ...(client.apiUrl ? { transport: 'rest', api_origin: client.apiUrl.origin } : {}),
68
- connection_verified: connected, model_discovery_verified: models, assistant_discovery: 'not_checked', checks, guidance };
95
+ connection_verified: connected, model_discovery_verified: models, assistant_discovery: 'not_checked',
96
+ ...(installed ? { skills: installed } : {}), checks, guidance };
69
97
  }
package/src/help.mjs CHANGED
@@ -12,7 +12,7 @@ const login = { 'no-browser': flag, timeout: integer(30, 900, 180) };
12
12
  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
- 'auth status': ['', 'Check this CLI login without spending money.', {}],
15
+ 'auth status': ['', 'Offline view of the saved login. The access token renews automatically before each command; an elapsed access_token_expires_at is not an expired login. Verify with balance.', {}],
16
16
  'auth logout': ['', 'Revoke this CLI session; other OAuth sessions retain access.', {}],
17
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) }],
@@ -48,7 +48,7 @@ const COMMANDS = {
48
48
  }],
49
49
  'skills install': ['[options]', 'Install or synchronize bundled skill files; protect modified files and back up replacements.', { agent, 'replace-modified': flag }],
50
50
  'skills status': ['[options]', 'Compare installed skill contents and package version.', { agent }],
51
- doctor: ['[options]', 'Check prerequisites, connection, model discovery and skill contents separately. Free.', { agent }],
51
+ doctor: ['[options]', 'Check prerequisites, connection, model discovery, skill contents and CLI updates separately. An available update, and installed skill findings without --agent, are guidance only. Free.', { agent }],
52
52
  };
53
53
  for (const type of ['image', 'video', 'audio']) COMMANDS[`generate ${type}`] = [
54
54
  '--quote ID --confirm [options]', 'Submit the saved quote after explicit user approval. Changes require a new quote. Never call generate to poll progress.',
package/src/media.mjs CHANGED
@@ -161,7 +161,11 @@ export class Media {
161
161
  const remaining = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
162
162
  const task = await this.client.call('get_task', { task_id: taskId, wait_seconds: Math.min(30, remaining) });
163
163
  if (task.status === 'completed') return task;
164
- if (['failed', 'cancelled'].includes(task.status)) throw new CliError('task_failed', 'The generation task did not complete.', { task });
164
+ // task.error.code is the shared core's user-facing code, the one the API reports.
165
+ if (['failed', 'cancelled'].includes(task.status)) {
166
+ throw new CliError('task_failed', `The generation task ${task.status === 'failed' ? 'failed' : 'was cancelled'}${
167
+ task.error?.code ? ` with error code ${task.error.code}` : ''}.`, { task });
168
+ }
165
169
  progress(`${task.task_id}: ${task.status}${task.progress !== undefined ? ` (${task.progress}%)` : ''}`);
166
170
  if (Date.now() >= deadline) throw new CliError('wait_timeout', 'The task is still running. Continue with tasks wait.', { task_id: taskId });
167
171
  await new Promise(resolve => { const timer = setTimeout(done, 500); function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); } signal?.addEventListener('abort', done, { once: true }); });
@@ -1,6 +1,6 @@
1
1
  // Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
2
2
  // Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
3
- import { publicIdentifier, publicLabel, publicNumber } from './public-error.js';
3
+ import { publicIdentifier, publicLabel, publicNumber, publicText } from './public-error.js';
4
4
  import { currentCredentialMode } from '../request-context.js';
5
5
  import { API_KEYS_URL, MCP_CONSOLE_URL, MCP_KEY_NAME, TOP_UP_URL, siteUrl } from './http-policy.js';
6
6
  import { trackedLink } from './utm.js';
@@ -403,7 +403,7 @@ const TASK_ERROR_MAP = {
403
403
  retryable: false,
404
404
  },
405
405
  request_cancelled: {
406
- suggestion: 'The task was cancelled. Check this task’s billing state before deciding whether to request another generation.',
406
+ suggestion: 'The task was cancelled or interrupted before it completed.',
407
407
  retryable: false,
408
408
  },
409
409
  resource_not_found: {
@@ -411,11 +411,13 @@ const TASK_ERROR_MAP = {
411
411
  retryable: false,
412
412
  },
413
413
  generation_timeout: {
414
- suggestion: 'The generation timed out. Check the original task and its billing state before considering another generation.',
414
+ suggestion: 'The generation timed out. Retain the task ID before considering another generation.',
415
415
  retryable: true,
416
416
  },
417
+ // A task fails with this code when the upstream channel is rate-limited or out of capacity.
418
+ // The user's balance and key limits are checked at submission and refuse the request instead.
417
419
  quota_exceeded: {
418
- suggestion: `The generation encountered a quota limit. Check balance and limits before requesting another generation; top up at ${TOP_UP_URL} if the balance is low.`,
420
+ suggestion: 'The upstream channel’s capacity or rate limit was reached. This is not the user’s balance or key limit. Wait before considering another generation.',
419
421
  retryable: true,
420
422
  },
421
423
  resource_exhausted: {
@@ -427,11 +429,11 @@ const TASK_ERROR_MAP = {
427
429
  retryable: false,
428
430
  },
429
431
  service_error: {
430
- suggestion: 'The generation service reported an error. Retain the task ID and check its billing state.',
432
+ suggestion: 'The generation service reported an error. Retain the task ID.',
431
433
  retryable: true,
432
434
  },
433
435
  service_unavailable: {
434
- suggestion: 'The generation service was temporarily unavailable. Retain the task ID and check its billing state.',
436
+ suggestion: 'The generation service was temporarily unavailable. Retain the task ID.',
435
437
  retryable: true,
436
438
  },
437
439
  unknown_error: {
@@ -439,19 +441,55 @@ const TASK_ERROR_MAP = {
439
441
  retryable: false,
440
442
  },
441
443
  };
444
+ /** A rule-specific code: invalid_* names an input the user can fix; the rest have no fixed guidance. */
445
+ const RULE_INPUT_ERROR = {
446
+ suggestion: 'Fix the input this code names, checking this model’s get_model rules.',
447
+ retryable: false,
448
+ };
449
+ const RULE_ERROR = {
450
+ suggestion: 'EvoLink reported this error code for the task. Retain the task ID and give it to EvoLink support if the cause is unclear.',
451
+ retryable: false,
452
+ };
453
+ /**
454
+ * The code the user sees on the API, so the user and the assistant name the same error.
455
+ * channel_* codes describe EvoLink's own upstream channel accounts, which the user cannot fix;
456
+ * the user-facing code for them is service_unavailable.
457
+ */
458
+ export function publicTaskErrorCode(value) {
459
+ const code = typeof value === 'string' ? value.trim().toLowerCase() : '';
460
+ if (!/^[a-z][a-z0-9_]{0,63}$/.test(code))
461
+ return 'unknown_error';
462
+ return code.startsWith('channel_') ? 'service_unavailable' : code;
463
+ }
442
464
  export function getTaskErrorInfo(code) {
443
- const info = TASK_ERROR_MAP[code] ?? TASK_ERROR_MAP.unknown_error;
444
- // The top-up link is tagged for the caller when the hint is shown, not when the table is built.
445
- return info.suggestion.includes(TOP_UP_URL)
446
- ? { ...info, suggestion: info.suggestion.replace(TOP_UP_URL, trackedLink(TOP_UP_URL, 'top_up')) }
447
- : info;
465
+ return Object.prototype.hasOwnProperty.call(TASK_ERROR_MAP, code) ? TASK_ERROR_MAP[code]
466
+ : code.startsWith('invalid_') ? RULE_INPUT_ERROR : RULE_ERROR;
467
+ }
468
+ /** Longest gateway explanation passed on for one failed task, in characters. */
469
+ const TASK_MESSAGE_MAX = 1000;
470
+ /**
471
+ * The gateway's explanation of a failed task, as API users see it, on one line: secrets,
472
+ * service addresses and links other than EvoLink docs are removed. It says why the task failed;
473
+ * what to do next still comes from the suggestion.
474
+ */
475
+ export function publicTaskMessage(value) {
476
+ if (typeof value !== 'string')
477
+ return undefined;
478
+ // Four live rules type the upload-guide link as "https: //"; repair it rather than drop it.
479
+ const text = publicText(value.replace(/https: \/\/evolink\.ai\//g, 'https://evolink.ai/'))
480
+ .replace(/[\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, '')
481
+ .replace(/\s+/g, ' ').trim();
482
+ if (!text)
483
+ return undefined;
484
+ const chars = [...text];
485
+ return chars.length > TASK_MESSAGE_MAX ? `${chars.slice(0, TASK_MESSAGE_MAX - 1).join('').trimEnd()}…` : text;
448
486
  }
449
487
  export function publicTaskError(error = {}) {
450
- const code = Object.prototype.hasOwnProperty.call(TASK_ERROR_MAP, error.code ?? '')
451
- ? error.code : 'unknown_error';
488
+ const code = publicTaskErrorCode(error.code);
452
489
  const info = getTaskErrorInfo(code);
453
- return { code, message: code === 'unknown_error' ? 'Generation failed; the cause is unknown.'
454
- : `Generation did not complete (${code}).`, ...info };
490
+ const message = publicTaskMessage(error.message)
491
+ ?? (code === 'unknown_error' ? 'Generation failed; the cause is unknown.' : `Generation did not complete (${code}).`);
492
+ return { code, message, ...info };
455
493
  }
456
494
  export function formatTaskError(error) {
457
495
  const info = publicTaskError(error);
@@ -150,8 +150,10 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
150
150
  else if (p.type === 'boolean' && typeof value !== 'boolean') {
151
151
  fail('invalid_quote_parameter', `Pricing parameter ${name} must be boolean.`, name);
152
152
  }
153
+ // Published enums may spell numbers as strings ("5") while the generation input carries a number (5);
154
+ // lookup expressions compare by text, so the allowed-value check does the same.
153
155
  const allowed = p.values ?? p.enum;
154
- if (allowed && !allowed.some(candidate => candidate === value))
156
+ if (allowed && !allowed.some(candidate => String(candidate) === String(value)))
155
157
  fail('invalid_quote_parameter', `Pricing parameter ${name} is not an allowed value.`, name);
156
158
  parameters[name] = value;
157
159
  }
@@ -3,6 +3,13 @@
3
3
  import { z } from 'zod';
4
4
  import { getPricingRules } from './pricing-rules-client.js';
5
5
  import { QuoteError, prepareQuoteParameters, quoteRequestHash } from './pricing-quote-client.js';
6
+ /**
7
+ * How long an approval from estimate_cost may be passed to generate_*. The rules' own
8
+ * `fresh_until` is a short refresh window (minutes); people confirming a price in a chat
9
+ * need longer. generate_* re-evaluates the current rules and refuses with `price_changed`
10
+ * when the price moved, so a longer approval cannot submit at a stale price.
11
+ */
12
+ export const APPROVAL_TTL_MS = 30 * 60_000;
6
13
  function fail(code, message) { throw new QuoteError(code, message); }
7
14
  function gcd(a, b) { while (b)
8
15
  [a, b] = [b, a % b]; return a < 0n ? -a : a; }
@@ -204,7 +211,7 @@ export function calculateRulesEstimate(body, entry, input, options = {}) {
204
211
  fail('invalid_pricing_expression', 'The estimated charge exceeds its supported range.');
205
212
  const amounts = amountsForUC(String(total)), requestHash = quoteRequestHash(entry.id, input, options.mediaSeconds, options.pricingParameters);
206
213
  const approval = { source: 'pricing_rules', price_scope: 'public_default', model_id: entry.id,
207
- request_hash: requestHash, total_uc: amounts.uc, expires_at: body.meta.fresh_until,
214
+ request_hash: requestHash, total_uc: amounts.uc, expires_at: new Date(Date.now() + APPROVAL_TTL_MS).toISOString(),
208
215
  fingerprint: quoteRequestHash(entry.id, { rules: economicRules(rule), parameters: params,
209
216
  exchange_rate_version: body.meta.exchange_rate_version, components, missing: [...missing].sort(), total_uc: amounts.uc }) };
210
217
  const estimate = { status: missing.size ? components.length ? 'partial' : 'needs_input' : 'estimated', min_usd: Number(amounts.usd), max_usd: Number(amounts.usd),
@@ -28,6 +28,11 @@ export function publicText(value) {
28
28
  && ['/dashboard/credits', '/dashboard/keys', '/dashboard/mcp'].includes(url.pathname)
29
29
  && [...url.searchParams].every(([key, v]) => key.startsWith('utm_') && /^[a-z0-9_-]{1,80}$/i.test(v) || key === 'tab' && v === 'mcp'))
30
30
  return value;
31
+ // Official documentation pages, which gateway task errors link to (for example the upload guide).
32
+ if (url.origin === 'https://evolink.ai' && !url.username && !url.password
33
+ && /^\/docs\/[A-Za-z0-9_.\/-]*$/.test(url.pathname) && !url.pathname.includes('//') && /^(#[A-Za-z0-9_-]{1,80})?$/.test(url.hash)
34
+ && [...url.searchParams].every(([key, v]) => key.startsWith('utm_') && /^[a-z0-9_-]{1,80}$/i.test(v)))
35
+ return value;
31
36
  }
32
37
  catch { }
33
38
  return '[service address]';
@@ -2,6 +2,7 @@
2
2
  // Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
3
3
  import { z } from 'zod';
4
4
  import { listTasks, queryTasks } from '../services/api-client.js';
5
+ import { publicTaskErrorCode } from '../services/error-handler.js';
5
6
  import { READ_ONLY, errorResult, failure, money, ok, usdOf } from './shared.js';
6
7
  import { TASK_ID } from './get-task.js';
7
8
  import { RESULT_DELIVERY_GUIDANCE, RESULT_DELIVERY_INSTRUCTIONS, RESULT_LINK_HOURS, resultDeliveryMarkdown, resultLinks, resultResources, taskOutputs } from './task-format.js';
@@ -39,8 +40,9 @@ function rowFromTask(task) {
39
40
  row.charged_credits = used;
40
41
  row.charged_usd = task.usage?.cost?.usd ?? usdOf(used);
41
42
  }
42
- if (task.error?.code)
43
- row.error_code = task.error.code;
43
+ // The same user-facing code as get_task, never an upstream channel code.
44
+ if (task.status === 'failed' || task.error?.code)
45
+ row.error_code = publicTaskErrorCode(task.error?.code);
44
46
  return row;
45
47
  }
46
48
  function rowLine(row) {
@@ -123,8 +125,9 @@ export function registerListTasks(server, config) {
123
125
  items = items.filter(item => item.created_at * 1000 >= sinceMs);
124
126
  if (untilMs !== undefined)
125
127
  items = items.filter(item => item.created_at * 1000 <= untilMs);
126
- // The list endpoint omits result links; read finished tasks in one batch to include them.
127
- const finished = items.filter(item => item.status === 'completed' && item.has_results).map(item => item.id).slice(0, MAX_IDS);
128
+ // The list endpoint omits result links and error codes; read those tasks in one batch to include them.
129
+ const finished = items.filter(item => item.status === 'completed' && item.has_results || item.status === 'failed')
130
+ .map(item => item.id).slice(0, MAX_IDS);
128
131
  const details = new Map();
129
132
  if (finished.length > 0) {
130
133
  for (const task of await queryTasks(config, finished))
@@ -146,8 +149,6 @@ export function registerListTasks(server, config) {
146
149
  row.charged_credits = item.credits_used;
147
150
  row.charged_usd = usdOf(item.credits_used);
148
151
  }
149
- if (item.has_error)
150
- row.error_code = 'failed';
151
152
  return row;
152
153
  });
153
154
  const filters = [status && `status ${status}`, type && `type ${type}`, model && `model ${model}`, since && `since ${since}`, until && `until ${until}`].filter(Boolean).join(', ');
@@ -20,6 +20,8 @@ export const RESULT_DELIVERY_INSTRUCTIONS = [
20
20
  /** Compact tool description; the full contract is sent in server instructions and completed results. */
21
21
  export const RESULT_DELIVERY_GUIDANCE = 'On completion, promptly deliver original links with the 24-hour expiry and delivery_markdown. Edit only when the user explicitly requests or authorizes post-processing. Keep original links alongside optional embedded MCP thumbnails; do not add remote-image Markdown or use image syntax for video/audio.';
22
22
  export const TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled']);
23
+ /** The gateway charges nothing for a failed task and releases its reservation (refund, or expiry as a backstop). */
24
+ export const FAILED_TASK_BILLING = 'The task failed, so it is not charged. The credits reserved at submission are returned automatically.';
23
25
  const MEDIA_EXTENSIONS = {
24
26
  png: { kind: 'image', mimeType: 'image/png' },
25
27
  jpg: { kind: 'image', mimeType: 'image/jpeg' },
@@ -187,6 +189,7 @@ export function describeTask(task) {
187
189
  const billing = taskBilling(task);
188
190
  structured.billing = billing;
189
191
  lines.push(`Error: ${info.code} — ${info.message}`);
192
+ let verify = ' Query get_task again to verify billing.';
190
193
  if (billing.refund_status === 'completed') {
191
194
  lines.push(`Account balance refund completed: ${money(billing.refunded_credits)}. Key limit restoration is unknown.`);
192
195
  structured.refunded = true;
@@ -200,10 +203,15 @@ export function describeTask(task) {
200
203
  else if (billing.refund_status === 'not_required') {
201
204
  lines.push('The billing record reports no account balance refund required. Check the recorded charge before requesting another generation.');
202
205
  }
206
+ else if (status === 'failed' && billing.charge_status !== 'charged') {
207
+ lines.push(FAILED_TASK_BILLING);
208
+ structured.billing_note = FAILED_TASK_BILLING;
209
+ verify = '';
210
+ }
203
211
  else {
204
212
  lines.push('Charge and refund completion cannot be verified from the available billing evidence. Query this task again or contact EvoLink support.');
205
213
  }
206
- const next = `${info.suggestion} Query get_task again to verify billing. Do not generate again automatically. Another generation is a separately paid task: obtain a fresh estimate and explicit user approval first.`;
214
+ const next = `${info.suggestion}${verify} Do not generate again automatically. Another generation is a separately paid task: obtain a fresh estimate and explicit user approval first.`;
207
215
  lines.push(`Next step: ${next}`);
208
216
  structured.error = { ...info, suggestion: next };
209
217
  }
@@ -1,4 +1,4 @@
1
1
  // Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
2
2
  // Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
3
3
  /** Version reported in serverInfo and in the X-Evo-Client-Version header. */
4
- export const MCP_VERSION = '1.7.0';
4
+ export const MCP_VERSION = '1.8.1';
@@ -2,7 +2,7 @@
2
2
  "schema_version": 1,
3
3
  "repository": "Evolink-AI/evolink-mcp",
4
4
  "baseline": "acc9fd43b945e3917b47809fc94f85ba26c7c8db",
5
- "source_sha256": "7cde53442ad7bed3408a9ab63647b66df928f457b0460321189eddc926a05b0b",
5
+ "source_sha256": "06544727011f3fadb4a75ab4af35ee097e80802ba7ee085b3c48a68d630965d6",
6
6
  "files": {
7
7
  "packages/core/src/branding.ts": "534b944a1370f210a3858c1a85b1a23071aca8e26b7a3e70e4d859ba5b152ff7",
8
8
  "packages/core/src/config.ts": "208496230e22f43817cfb9b3805cde279fcce61a82227dfbd9f63485a33d33c7",
@@ -11,11 +11,11 @@
11
11
  "packages/core/src/data/model-params.ts": "d387d10b7d888059df9c1bd2177e336a497981b63ecbac57009f399f4e1fd858",
12
12
  "packages/core/src/platform-client.ts": "d272d1fbd7939acd69482207f1a75550e4ff8f584deee8f6d0c8ace86e453b6d",
13
13
  "packages/core/src/platform-operations.ts": "3239283b4cff2490dd42ac006d03165ef2843eb05cfaece3572d1aacde2e7e32",
14
- "packages/core/src/request-context.ts": "c78d28379609779305aa2ebbf3c9cc503a98ed7f144eed48103ab518c9ef5539",
15
- "packages/core/src/server.ts": "d7eb164ccee69cb8f5409e27260b92b0215ce52fbad48eb3ed3de72e7c7ceefc",
14
+ "packages/core/src/request-context.ts": "f62856e8281207449724a672312f7ea444af10317a0ce93590e2fd2a26fef03e",
15
+ "packages/core/src/server.ts": "1d6d7a46fcd0fd96526e02ab766f6379a750bc550cca054bd088c4a5993292e2",
16
16
  "packages/core/src/services/api-client.ts": "fb750cb37d4bce367851b1b659fd335894dda98b3ce46b14227a0150e1ef0773",
17
17
  "packages/core/src/services/catalog-client.ts": "c2bcfb0f2780112bcddf6a42537cf9f6264717d0b3685c896790339b0f9bb7df",
18
- "packages/core/src/services/error-handler.ts": "9d46cf411eff9a477653cff67e764788b68c3dca163b5ebef99e60209c4f2173",
18
+ "packages/core/src/services/error-handler.ts": "fd07d5dbd4cad3b4e75d7192c4d49623d92666fef40bd688646e0f756c208d5a",
19
19
  "packages/core/src/services/file-client.ts": "9bd94da9a0719fba0050be261fb5210397be4e8b9e6ebc8a2e916fcc185fd2d2",
20
20
  "packages/core/src/services/http-policy.ts": "f8cc029627655718d52b30dadaaa503fa6d4597846a13c802b7558d9797ea6bd",
21
21
  "packages/core/src/services/media-preview.ts": "89410d8eb9a02e6fb9d9bc0de8a69b48bec7a06039e54569b9fea7e35527b6c4",
@@ -25,10 +25,10 @@
25
25
  "packages/core/src/services/param-validator.ts": "506e6d6f6a1ad170024d6a24ffcd2434c73e7ac855a89bbba9fdbb81653416fb",
26
26
  "packages/core/src/services/preview-download.ts": "719e100e05f7632f633551773159ba7202f755c6d6ff5ecf364b40eeb26bee7b",
27
27
  "packages/core/src/services/pricing-client.ts": "2e8d1107bac56c7e6fd47dbdd79f35b446af283f3f85a18c8bedeca60b822d98",
28
- "packages/core/src/services/pricing-quote-client.ts": "cca03e45d2f5f152b1a6112ce9edd5cdeb7d11f99eec531d4754c437e781d6d0",
28
+ "packages/core/src/services/pricing-quote-client.ts": "a4537ce5ba83d9a8859ce6fb72223353443b67a42a0525b0cfad2abb93d0649a",
29
29
  "packages/core/src/services/pricing-rules-client.ts": "a7d86718ae4f654425304dd8e5f263dad369475cb06c920b8885b1060f0cee60",
30
- "packages/core/src/services/pricing-rules-estimate.ts": "1aaf6935e549ceeb7ebf493ffe0fe430a6aabd59c00198b2b640df9d9a5cb827",
31
- "packages/core/src/services/public-error.ts": "01cf744413fd5ba8206e63fb184356f557a5a76d36506f52fc2540f2480217d9",
30
+ "packages/core/src/services/pricing-rules-estimate.ts": "18b9115ffe4b7d04abd7c6fa2252cfe79a31a412567742ff9e8ea7237c59da21",
31
+ "packages/core/src/services/public-error.ts": "b706d2b5ccef1542c8f13e8cd41bfe844a590221e29053376f045680a912c54d",
32
32
  "packages/core/src/services/upload-policy.ts": "2dc36716a3b9e78b078c618b029499bf6e27448dd44900b6f917dda5f8046ce3",
33
33
  "packages/core/src/services/upload-slots.ts": "80da2511394daf61e3b8ed3b9fbed06c28fec7d4d5b1c3d68585bd89fa816096",
34
34
  "packages/core/src/services/utm.ts": "adb224e91531b0db809b5de086ddc97bb5a383184458554dcdf784a65cd941a5",
@@ -40,15 +40,15 @@
40
40
  "packages/core/src/tools/get-model.ts": "bd727644aa554c7aa9d0246cbcb427d5063fb4b86fa33561af73f54eed2d1aa6",
41
41
  "packages/core/src/tools/get-pricing-rules.ts": "a8325792565a74c3368067918544ab94766ce2f440ee2c10dcb3e4987687d21f",
42
42
  "packages/core/src/tools/get-task.ts": "937a5ad4454956dd000abfd11149523d135527018d4d643ede600950d69e6205",
43
- "packages/core/src/tools/list-tasks.ts": "22e5ac19bbe210fb11ea39afe12fa7f92fb40ffc0560c7bee3d1f9354fc78395",
43
+ "packages/core/src/tools/list-tasks.ts": "c430f7c06b5aef88a3c386cf68d8462c7bf7371063cbfa85fa2511495ba9d69c",
44
44
  "packages/core/src/tools/prepare-upload.ts": "c58cfb04725cc660e34f68391727e99f726e355f9329d91ced56878212294d40",
45
45
  "packages/core/src/tools/search-models.ts": "3b950140240ac6c5f0dfdc0264cb4b66d0583e05e220c67245b6e8a7616fc55e",
46
46
  "packages/core/src/tools/shared.ts": "4edde666dc31af730460cbecf5520cc56626bc2b17f951f849130f3d7d4ccbef",
47
47
  "packages/core/src/tools/task-billing.ts": "cfb18355e44caa41ea278b4156bd15e6c3ebca13411c7cf043d7225c5532dcce",
48
- "packages/core/src/tools/task-format.ts": "d9d367086db95034a04e6f1639fc1bdbced719b046233b0da905d06fd421f595",
48
+ "packages/core/src/tools/task-format.ts": "05179cb238263817d4e67c711ef939d8b086246937698d0bd47b406eaf17a430",
49
49
  "packages/core/src/tools/task-usage.ts": "ba05d054e1d60d67f6ab75cc6d9169f453c87e0e89c17a2c1be5fc429e8f9f47",
50
50
  "packages/core/src/tools/upload-file.ts": "da6f239d1b1e6a13a7b418d24e738ebabf9823b2656111eeaa70eb247421ad40",
51
- "packages/core/src/version.ts": "c74733c45af0187c90e4e873d13ae686c690f66df33c5ecbcd0b4e74fc98bca1"
51
+ "packages/core/src/version.ts": "44364e6dbbb8893b6ca5fa77822acfe34bf9cda775ce072427f4a7f755fb8096"
52
52
  },
53
53
  "artifacts": {
54
54
  "core/src/config.js": "e5f001e6bb30fa3ca49ca1383b3deb83ea495d20079adefad6d0451f5bbee0e3",
@@ -60,7 +60,7 @@
60
60
  "core/src/request-context.js": "ed22b79db1fc8b20c57f0a58e938ff4a833bb6a75a16d2246f732a41256c21e8",
61
61
  "core/src/services/api-client.js": "9c3bbaba17c53f7560b56d344086834cb602ced0a540db18f1755e74fad0d36d",
62
62
  "core/src/services/catalog-client.js": "f438fdb13fa9e9ddbf539b265bfcbb77c4d5024835130cbade3b83e9952893cf",
63
- "core/src/services/error-handler.js": "150b2cc39a16b9cf7f51c2ad9db4f7d66ea677e11b63efc06363949709425fc6",
63
+ "core/src/services/error-handler.js": "edea48a8eaf90b4193a503c0418ba7157acabfe89833a39c1d41bbf568de8355",
64
64
  "core/src/services/file-client.js": "d11798bfddc6637727a874532ad218b5deac58d6bca8f20abcd2c30b132210e4",
65
65
  "core/src/services/http-policy.js": "322892ddb21f15cb3111a36b006b3ab62bea7a9d13b05d970ded62bae3ca32cd",
66
66
  "core/src/services/model-capabilities.js": "2ad86bc08c82cce82964b18d6187632fc738f8cd17d03de1ef04f27b1e35cfe1",
@@ -68,10 +68,10 @@
68
68
  "core/src/services/model-recommendations.js": "f330f941d26aa9fc127c2f7479cb2be026d6111a3f3066e89442ff29ec33803a",
69
69
  "core/src/services/param-validator.js": "9e3fba916a39140614851689fcf47f1aa644a30b6192b6126af4d78695f88b10",
70
70
  "core/src/services/pricing-client.js": "2f0f74f7769442e4edf8c3f37a66bb1c6c099253189e9b2079ad265d1327225d",
71
- "core/src/services/pricing-quote-client.js": "11206fa2936f7c380cd36ccf510259dbc31440ddb586746a8a3281616e27781a",
71
+ "core/src/services/pricing-quote-client.js": "6107815eb757036470fac21f9d79da3a3862f583c3b2f0c1d9f56761fa9fc9f6",
72
72
  "core/src/services/pricing-rules-client.js": "133ee1c47b8f8e8ff7fe32e952a0a5ae87e75ab75a5403cb06827e08f119c7f0",
73
- "core/src/services/pricing-rules-estimate.js": "ed6ae4fedaa68a952cc2b511bec8da30d3eb0a3c36efa5cb293c266b6dfd978f",
74
- "core/src/services/public-error.js": "3982fd6ecf2600f708aa9d9e86efd72885dd4e2f701dd7880b9fa447e8367e08",
73
+ "core/src/services/pricing-rules-estimate.js": "c7288e2f76b4de7116c88f7b443ed835d0e0af21387d6e1e389ad13a1c71f506",
74
+ "core/src/services/public-error.js": "306665fb8ac54beb911a8e908755e49c3a9aec64f3b9a5dee1a28eb64e8a2681",
75
75
  "core/src/services/utm.js": "8aa328ddb92c3ef65568fab60226cb5fa2e940449d7ac3d6c2e35b6f9bcf835d",
76
76
  "core/src/tool-guidance.js": "a9ebc5bc761738e9f603ba0111f35328237925a18107a342db589cd35655f1b6",
77
77
  "core/src/tools/check-balance.js": "75baa61e57e289fd61a45251665df599967ba0beb4b33cc3976280a9d89421bf",
@@ -81,12 +81,12 @@
81
81
  "core/src/tools/get-model.js": "32bbba590e8f0fb632dab0e517f761cddcc7b64a8eb76f1d9ae571e6f80bf08d",
82
82
  "core/src/tools/get-pricing-rules.js": "6562bd6a765379823305612e93b2f03c789affcc92f75ccf603b4bc64630472e",
83
83
  "core/src/tools/get-task.js": "1ef62167c629c7ad859d1d31cd8779eb98e3a22c8bb754b2c355e58515b308f0",
84
- "core/src/tools/list-tasks.js": "e795aeebed047d3ba72c87d699f3bb1306bc626d04c69db2a2667607abce586e",
84
+ "core/src/tools/list-tasks.js": "73de0c3c7ecfff6f99202d17c1db53f2c394b15d01781199cc38f9c3eb80c6a5",
85
85
  "core/src/tools/search-models.js": "9850b7d2d74a1d69229400d465b21ecb9ede79c75dddeb41787668f418c5bd06",
86
86
  "core/src/tools/shared.js": "77d54bced4e05b3712a2bb44b6075d792d6dde18212aa0e615bf83af1b36bf79",
87
87
  "core/src/tools/task-billing.js": "f49b252afcaf4a6275f5db6ebc8e6380387b2406bd5fc91e7367e3523025af8b",
88
- "core/src/tools/task-format.js": "2daefc0f34ff14f0be38eb65b6e91dacd0c3f111a474e424a25906c9d8122338",
88
+ "core/src/tools/task-format.js": "fd409b11bf24826d7669fcf8a0994e23d244034ae88fdc4d931444d7d12ce0fa",
89
89
  "core/src/tools/task-usage.js": "3aae5d7807efc2c762bf604cf9ecfecf8f9008185bcef584e6d4243404418dc5",
90
- "core/src/version.js": "3a11740ee61119d3c9fd6dc0dd4e72b0e7771a92177e68129434fbd514e7251d"
90
+ "core/src/version.js": "9d5854d50c035b9ecbd6406ebe4fcc05c944798534d3c3201dc2666abc7bca96"
91
91
  }
92
92
  }
package/src/setup.mjs CHANGED
@@ -2,16 +2,19 @@ import { prerequisites, verifyModels } from './doctor.mjs';
2
2
  import { installSkill, skillStatus, validateAgent } from './skills.mjs';
3
3
  import { CliError, errorView, requireThat } from './errors.mjs';
4
4
  import { CLI_VERSION } from './version.mjs';
5
+ import { updateAdvice } from './update.mjs';
5
6
 
6
7
  const LOGIN_ERRORS = new Set(['login_required', 'invalid_session', 'login_expired']);
7
8
 
8
9
  export async function setup({ state, server, credentials, client, mcp = client, agent = 'all', skillHome, noBrowser = false,
9
- timeout = 180_000, signal, progress = () => {}, version, platform }) {
10
+ timeout = 180_000, signal, progress = () => {}, version, platform, update }) {
10
11
  client = mcp;
11
12
  validateAgent(agent);
12
13
  return state.lock('setup', async () => {
14
+ // The registry request runs alongside setup and never changes its outcome.
15
+ const updating = update?.().catch(() => undefined);
13
16
  const steps = [];
14
- let phase = 'preflight', connected = false, models = false, skills, authorization;
17
+ let phase = 'preflight', connected = false, models = false, skills, authorization, result;
15
18
  const recovery = () => `evolink setup --agent ${agent}${noBrowser ? ' --no-browser' : ''}`;
16
19
  try {
17
20
  progress('Setup: checking runtime, local state and secure credential storage.');
@@ -58,16 +61,24 @@ export async function setup({ state, server, credentials, client, mcp = client,
58
61
  const status = await skillStatus({ home: skillHome, agent });
59
62
  requireThat(status.current, 'skill_changed', 'The skill changed during setup. Check evolink skills status before continuing.');
60
63
  progress('Setup: CLI connection, models and skill files verified. Ask your assistant to confirm skill discovery.');
61
- return { ok: true, setup_complete: true, cli_version: CLI_VERSION, agent, server: server.href,
64
+ result = { ok: true, setup_complete: true, cli_version: CLI_VERSION, agent, server: server.href,
62
65
  connection_verified: connected, model_discovery_verified: models, skills, steps,
63
66
  ...(authorization ? { authorization } : {}), ...(client.apiUrl ? { transport: 'rest', api_origin: client.apiUrl.origin } : {}),
64
67
  assistant_discovery: 'not_checked', next_step: skills.next_step };
65
68
  } catch (error) {
66
69
  const view = errorView(error);
67
70
  steps.push({ name: phase, status: 'failed', error: view });
68
- return { ok: false, setup_complete: false, cli_version: CLI_VERSION, agent, phase,
71
+ result = { ok: false, setup_complete: false, cli_version: CLI_VERSION, agent, phase,
69
72
  connection_verified: connected, model_discovery_verified: models, assistant_discovery: 'not_checked',
70
73
  ...(skills ? { skills } : {}), steps, error: view, recovery: recovery() };
71
74
  }
75
+ const updateInfo = await updating;
76
+ if (updateInfo) {
77
+ // An outdated release explains stale behaviour; report it with either outcome.
78
+ result.update = updateInfo;
79
+ const advice = updateAdvice(updateInfo);
80
+ if (advice) progress(advice);
81
+ }
82
+ return result;
72
83
  });
73
84
  }
package/src/update.mjs ADDED
@@ -0,0 +1,163 @@
1
+ import { CliError, requireThat } from './errors.mjs';
2
+ import { USER_AGENT, loopback } from './network.mjs';
3
+ import { CLI_VERSION } from './version.mjs';
4
+
5
+ export const UPDATE_PACKAGE = '@evolinkai/cli';
6
+ // The registry's dist-tags document is a few bytes and needs no login.
7
+ export const UPDATE_URL = 'https://registry.npmjs.org/-/package/@evolinkai%2Fcli/dist-tags';
8
+ export const UPDATE_COMMAND = 'npm install -g @evolinkai/cli@latest';
9
+ export const UPDATE_CHECK_ENV = 'EVOLINK_CLI_UPDATE_CHECK';
10
+ export const UPDATE_INTERVAL = 24 * 60 * 60 * 1000;
11
+ export const UPDATE_TIMEOUT = 3_000;
12
+ const CLOCK_SKEW = 5 * 60 * 1000;
13
+ const MAX_BODY = 16 * 1024;
14
+ const CACHE = ['update-check', 'npm'];
15
+ const OFF = ['0', 'false', 'no', 'off'];
16
+ // Numeric parts stay within exact Number precision.
17
+ const NUMBER = '0|[1-9]\\d{0,14}';
18
+ const IDENTIFIER = `(?:${NUMBER}|\\d*[A-Za-z-][0-9A-Za-z-]*)`;
19
+ const SEMVER = new RegExp(`^(${NUMBER})\\.(${NUMBER})\\.(${NUMBER})(?:-(${IDENTIFIER}(?:\\.${IDENTIFIER})*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$`);
20
+
21
+ export function parseVersion(value) {
22
+ const match = typeof value === 'string' && value.length <= 128 ? SEMVER.exec(value) : null;
23
+ return match ? { core: match.slice(1, 4).map(Number), prerelease: match[4] ? match[4].split('.') : [] } : undefined;
24
+ }
25
+ const stable = value => parseVersion(value)?.prerelease.length === 0;
26
+
27
+ // Semantic Versioning 2.0.0 precedence; build metadata is ignored. Invalid input returns undefined.
28
+ export function compareVersions(left, right) {
29
+ const a = parseVersion(left), b = parseVersion(right);
30
+ if (!a || !b) return undefined;
31
+ for (let i = 0; i < 3; i++) if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
32
+ if (!a.prerelease.length || !b.prerelease.length) return Math.sign(b.prerelease.length - a.prerelease.length);
33
+ for (let i = 0; i < Math.min(a.prerelease.length, b.prerelease.length); i++) {
34
+ const x = a.prerelease[i], y = b.prerelease[i];
35
+ if (x === y) continue;
36
+ const xNumeric = /^\d+$/.test(x), yNumeric = /^\d+$/.test(y);
37
+ if (xNumeric && yNumeric) return Number(x) < Number(y) ? -1 : 1;
38
+ if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
39
+ return x < y ? -1 : 1;
40
+ }
41
+ return Math.sign(a.prerelease.length - b.prerelease.length);
42
+ }
43
+
44
+ const normalized = value => typeof value === 'string' ? value.trim().toLowerCase() : '';
45
+ /** Why update checks are off, if they are: EVOLINK_CLI_UPDATE_CHECK=0, NO_UPDATE_NOTIFIER with any value (the
46
+ * update-notifier convention), a CI variable that is not 0/false, or a loopback test resource. */
47
+ export function updateCheckDisabled(env = process.env, server) {
48
+ if (OFF.includes(normalized(env[UPDATE_CHECK_ENV]))) return UPDATE_CHECK_ENV;
49
+ if (env.NO_UPDATE_NOTIFIER !== undefined) return 'NO_UPDATE_NOTIFIER';
50
+ if (normalized(env.CI) && !OFF.includes(normalized(env.CI))) return 'CI';
51
+ if (server && loopback(server)) return 'loopback_server';
52
+ return undefined;
53
+ }
54
+
55
+ async function readLimited(response) {
56
+ const chunks = [];
57
+ let size = 0;
58
+ for await (const chunk of response.body ?? []) {
59
+ size += chunk.byteLength;
60
+ requireThat(size <= MAX_BODY, 'update_check_failed', 'The npm registry response was too large.');
61
+ chunks.push(chunk);
62
+ }
63
+ return Buffer.concat(chunks).toString('utf8');
64
+ }
65
+
66
+ let abandoned = 0;
67
+ /** Requests given up at the deadline or on interrupt. fetch keeps their sockets open after the abort (10 seconds
68
+ * without an answer, minutes through a proxy that never answers CONNECT), so the entry point exits instead. */
69
+ export const abandonedUpdateChecks = () => abandoned;
70
+
71
+ export async function fetchLatestVersion({ fetchFn = fetch, timeout = UPDATE_TIMEOUT, signal } = {}) {
72
+ requireThat(!signal?.aborted, 'interrupted', 'The update check was interrupted.');
73
+ const controller = new AbortController();
74
+ let timer, stop, settled = false;
75
+ // The deadline does not depend on the transport honoring its abort signal.
76
+ const deadline = new Promise((_, reject) => {
77
+ stop = () => {
78
+ if (!settled) abandoned++;
79
+ controller.abort(); reject(new CliError('update_check_failed', 'The npm registry did not answer in time.'));
80
+ };
81
+ timer = setTimeout(stop, timeout);
82
+ signal?.addEventListener('abort', stop, { once: true });
83
+ });
84
+ const request = async () => {
85
+ const response = await fetchFn(UPDATE_URL, { headers: { Accept: 'application/json', 'User-Agent': USER_AGENT }, redirect: 'error', signal: controller.signal });
86
+ if (!response.ok) {
87
+ await response.body?.cancel();
88
+ throw new CliError('update_check_failed', `The npm registry returned HTTP ${response.status}.`);
89
+ }
90
+ let latest;
91
+ try { latest = JSON.parse(await readLimited(response))?.latest; }
92
+ catch (error) { if (error instanceof CliError) throw error; }
93
+ requireThat(stable(latest), 'update_check_failed', 'The npm registry returned no stable latest version.');
94
+ return latest;
95
+ };
96
+ try { return await Promise.race([deadline, request().finally(() => { settled = true; })]); }
97
+ finally { clearTimeout(timer); signal?.removeEventListener('abort', stop); }
98
+ }
99
+
100
+ // Damaged or foreign records are ignored; they only delay a notice until the next check.
101
+ function record(value) {
102
+ const base = { schema_version: 1, package: UPDATE_PACKAGE };
103
+ if (value?.schema_version !== 1 || value.package !== UPDATE_PACKAGE) return base;
104
+ return Object.assign(base, ...['checked_at', 'latest_version', 'latest_checked_at', 'notified_version', 'notified_at']
105
+ .filter(key => typeof value[key] === 'string').map(key => ({ [key]: value[key] })));
106
+ }
107
+ async function readRecord(state) {
108
+ try { return record(await state.read(...CACHE)); } catch { return record(); }
109
+ }
110
+ // Read again just before writing: another command may have recorded a newer answer or notice meanwhile.
111
+ // A damaged record reads as empty, so the write also repairs it.
112
+ async function saveRecord(state, fields) {
113
+ await state.write(...CACHE, { ...(await readRecord(state)), ...fields });
114
+ }
115
+ function recent(value, time) {
116
+ const at = Date.parse(value);
117
+ return Number.isFinite(at) && at <= time + CLOCK_SKEW && time - at < UPDATE_INTERVAL;
118
+ }
119
+
120
+ /** Compare the running CLI with the latest stable npm release. Never throws, and never waits longer than the
121
+ * timeout. Without force, a registry answer from the last 24 hours is reused. */
122
+ export async function checkForUpdate({ state, server, env = process.env, fetchFn, now = Date.now, current = CLI_VERSION, force = false, timeout, signal } = {}) {
123
+ const view = (status, latest, extra) => ({ status, update_available: status === 'available', current_version: current,
124
+ latest_version: latest ?? null, ...extra, command: UPDATE_COMMAND });
125
+ const disabled = updateCheckDisabled(env, server);
126
+ if (disabled) return view('disabled', null, { reason: disabled });
127
+ const time = now();
128
+ let saved = await readRecord(state), failed = false;
129
+ if (force || !recent(saved.checked_at, time)) {
130
+ // Record the attempt before the request: offline and concurrent runs wait for the next interval, and an
131
+ // unwritable state directory never leads to repeated network checks. setup, doctor and login always ask.
132
+ const checked_at = new Date(time).toISOString();
133
+ try { await saveRecord(state, { checked_at }); }
134
+ catch { if (!force) return view('unknown', null, { reason: 'state_unavailable' }); }
135
+ try {
136
+ saved = { ...saved, latest_version: await fetchLatestVersion({ fetchFn, timeout, signal }), latest_checked_at: checked_at };
137
+ await saveRecord(state, { checked_at, latest_version: saved.latest_version, latest_checked_at: checked_at }).catch(() => {});
138
+ } catch { failed = true; }
139
+ }
140
+ // A failed request keeps the last verified registry answer.
141
+ const latest = stable(saved.latest_version) ? saved.latest_version : undefined;
142
+ if (!latest) return view('unknown', null, { reason: 'registry_unavailable' });
143
+ return view(compareVersions(latest, current) > 0 ? 'available' : 'current', latest,
144
+ { ...(saved.latest_checked_at ? { checked_at: saved.latest_checked_at } : {}), ...(failed ? { reason: 'registry_unavailable' } : {}) });
145
+ }
146
+
147
+ export const updateMessage = ({ latest_version, current_version }) =>
148
+ `EvoLink CLI ${latest_version} is available (installed ${current_version}). Update with ${UPDATE_COMMAND}, then run evolink skills install.`;
149
+
150
+ /** One sentence for progress output and guidance when a newer release exists. */
151
+ export const updateAdvice = update => update?.update_available ? updateMessage(update) : undefined;
152
+
153
+ /** One stderr line for other commands, at most once per interval for the same release. */
154
+ export async function updateNotice(options) {
155
+ const result = await checkForUpdate(options);
156
+ if (result.status !== 'available' || options.signal?.aborted) return undefined;
157
+ const time = (options.now || Date.now)();
158
+ const saved = await readRecord(options.state);
159
+ if (saved.notified_version === result.latest_version && recent(saved.notified_at, time)) return undefined;
160
+ try { await saveRecord(options.state, { notified_version: result.latest_version, notified_at: new Date(time).toISOString() }); }
161
+ catch { return undefined; }
162
+ return updateMessage(result);
163
+ }