@evolinkai/cli 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
@@ -177,7 +195,7 @@ Final task/workflow budgets require authoritative server-side reservation and se
177
195
 
178
196
  ## Authentication and state
179
197
 
180
- Login discovers Passport directly and uses a native public OAuth client, PKCE, a loopback callback and `mcp offline_access` on the existing Passport service. Dynamically registered clients currently appear as unverified on the consent page. Device-code login is not included in this release.
198
+ Login discovers Passport directly and uses a native public OAuth client, PKCE, a loopback callback and `mcp offline_access` on the existing Passport service. After the approval, the loopback callback hands the browser on to the EvoLink MCP page (`?login=cli`), where the site picks the language; the authorization code is never part of that URL. Dynamically registered clients currently appear as unverified on the consent page. Device-code login is not included in this release.
181
199
 
182
200
  Tokens are stored only in the OS credential store. Linux requires a running Secret Service keyring; the CLI does not silently fall back to an in-memory kernel store or plaintext credential files. A one-command OAuth access token can be passed through stdin with `--token-stdin`, never as a command argument. `auth logout` revokes this session and preserves the account's shared MCP key.
183
201
 
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.0",
3
+ "version": "0.10.0",
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.
@@ -79,7 +81,7 @@ Use `generate` for the first submission of an approved quote. `tasks resume` is
79
81
 
80
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. 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,8 +2,9 @@ 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
- import { authFetch, ISSUER, SERVER } from './network.mjs';
7
+ import { authFetch, ISSUER, SERVER, SITE } from './network.mjs';
7
8
  import { CliError, requireThat } from './errors.mjs';
8
9
 
9
10
  export class Vault {
@@ -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; }
@@ -82,6 +85,13 @@ export function openBrowser(url, onFailure = () => {}) {
82
85
  child.unref();
83
86
  }
84
87
 
88
+ /** Where the browser goes once it has handed the authorization code to the CLI. The site picks the
89
+ * page language itself (its saved choice, then the browser language, English otherwise). */
90
+ export const LOGIN_LANDING_URL = `${SITE}/mcp?login=cli`;
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
+
85
95
  export async function callbackListener({ state, issuer, timeout = 180_000, signal }) {
86
96
  let settled = false;
87
97
  let resolveCode, rejectCode;
@@ -105,12 +115,16 @@ export async function callbackListener({ state, issuer, timeout = 180_000, signa
105
115
  const value = url.searchParams.get('code');
106
116
  if (!value) { res.writeHead(400); res.end('Missing login code.'); return; }
107
117
  settled = true;
118
+ // The browser has delivered the code. Hand it on to the EvoLink site, which confirms the
119
+ // approval in the right language; the code is not part of that URL. The English text
120
+ // below is only seen if the site cannot be reached.
108
121
  const nonce = randomBytes(16).toString('base64url');
109
122
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
110
123
  res.setHeader('Content-Security-Policy', `default-src 'none'; script-src 'nonce-${nonce}'; frame-ancestors 'none'; base-uri 'none'`);
111
124
  res.writeHead(200);
112
- res.end(`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>EvoLink approval received</title><script nonce="${nonce}">history.replaceState(null, '', '/oauth/callback');</script><h1>EvoLink approval received</h1><p>Return to your assistant to finish checking the connection. You can close this window.</p><p>授权已收到。请返回助手完成连接检查,然后关闭此窗口。</p></html>`);
125
+ res.end(`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="refresh" content="0;url=${LOGIN_LANDING_URL}"><title>EvoLink approval received</title><script nonce="${nonce}">history.replaceState(null, '', '/oauth/callback');location.replace('${LOGIN_LANDING_URL}');</script><h1>EvoLink approval received</h1><p>Return to your assistant to finish checking the connection. <a href="${LOGIN_LANDING_URL}">Continue to EvoLink</a></p></html>`);
113
126
  resolveCode(value);
127
+ return;
114
128
  });
115
129
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
116
130
  const timer = setTimeout(() => { settled = true; rejectCode(new CliError('login_timeout', 'Login timed out. Start a new login and use its new browser link.', { recovery: 'evolink auth login', timeout_seconds: timeout / 1000 })); }, timeout);
@@ -147,10 +161,12 @@ export class Credentials {
147
161
  return { access_token: saved.tokens.access_token, binding: saved.binding };
148
162
  });
149
163
  }
150
- async login({ noBrowser = false, timeout = 180_000, progress = () => {}, browser = openBrowser, signal } = {}) {
164
+ async login({ noBrowser = false, timeout = 180_000, progress = () => {}, browser = openBrowser, signal, update } = {}) {
151
165
  requireThat(!this.token, 'invalid_option', 'auth login cannot use --token-stdin.');
152
166
  requireThat(Number.isInteger(timeout) && timeout >= 30_000 && timeout <= 900_000, 'invalid_option', 'Login timeout must be between 30 and 900 seconds.');
153
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);
154
170
  progress('Login: preparing browser authorization.');
155
171
  await this.vault.read();
156
172
  const provider = this.provider();
@@ -178,14 +194,34 @@ export class Credentials {
178
194
  }
179
195
  requireThat(result === 'AUTHORIZED', 'login_failed', 'Login could not finish.');
180
196
  progress('Login: complete. Verify the connection with evolink balance --json.');
181
- 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;
182
211
  } finally { await listener.close(); }
183
212
  });
184
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. */
185
216
  async status() {
186
217
  if (this.token) return { authenticated: true, credential_storage: 'stdin', server: this.server.href };
187
218
  const saved = await this.vault.read();
188
- 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}` };
189
225
  }
190
226
  async logout() {
191
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/network.mjs CHANGED
@@ -9,6 +9,7 @@ export const SERVER = 'https://mcp.evolink.ai/mcp';
9
9
  export const ISSUER = 'https://passport.evolink.ai';
10
10
  export const API = 'https://api.evolink.ai';
11
11
  export const FILES = 'https://files-api.evolink.ai';
12
+ export const SITE = 'https://evolink.ai';
12
13
  export const USER_AGENT = `EvoLinkCLI/${CLI_VERSION}`;
13
14
  export const loopback = url => url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname);
14
15
 
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
+ }