@evolinkai/cli 0.5.0 → 0.6.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
@@ -26,8 +26,48 @@ The same setup prompt can be used in coding assistants with terminal access:
26
26
  >
27
27
  > 媒体生成默认使用 EvoLink,每次付费任务先报价,等我明确确认后再生成。
28
28
 
29
+ For an installation preflight in a POSIX shell, treat an absent command as an expected first-time setup state:
30
+
31
+ ```sh
32
+ if command -v evolink >/dev/null 2>&1; then
33
+ evolink --version
34
+ else
35
+ printf '%s\n' 'EvoLink CLI is not installed or not on PATH.'
36
+ fi
37
+ ```
38
+
39
+ 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.
40
+
29
41
  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).
30
42
 
43
+ 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.
44
+
45
+ ## Setup and skill updates
46
+
47
+ Starting with CLI 0.6.0, use the selected assistant's name:
48
+
49
+ ```sh
50
+ evolink setup --agent codex --json
51
+ evolink skills status --agent codex --json
52
+ evolink doctor --agent codex --json
53
+ ```
54
+
55
+ `setup` checks Node.js, writable state and credential storage, synchronizes the selected skill, reuses an existing login only after checking the real account connection, and verifies model discovery. When needed it waits for browser approval. Repeating setup reuses completed steps; connection errors do not automatically trigger a new login. Checks submit no paid media tasks. The default agent is `all`; use `--agent` to install only for the assistant you are using. Commands sharing a state directory serialize setup; skill writes also serialize across state directories in the same home.
56
+
57
+ CLI checks cannot prove that the assistant has loaded a skill. A successful result leaves `assistant_discovery: not_checked`; ask the assistant to confirm discovery in the current conversation. Reopen only when the assistant cannot refresh. A failed stage returns its error and a setup recovery command without erasing completed installations.
58
+
59
+ `auth login` and `setup` accept `--timeout SECONDS` (30–900, default 180). Keep the login process running until it reports completion. If it times out or is interrupted, start a new login and open the new link. The local callback page acknowledges receipt and returns you to the assistant for verification; it does not claim the account connection was verified. Repeated callbacks are refused and the browser page clears the authorization query from its visible URL.
60
+
61
+ The installer copies SKILL.md and its bundled references, records their hashes and CLI version, and skips identical installations. `skills status` distinguishes missing, current, outdated, legacy, unmanaged, modified and conflicting installations. The unmodified published 0.5.0 or 0.5.1 skill migrates automatically. Local changes are preserved by default. Only after choosing to replace those changes, run:
62
+
63
+ ```sh
64
+ evolink skills install --agent codex --replace-modified --json
65
+ ```
66
+
67
+ Replacement backs up the previous skill directory under `~/.evolink-media/skill-backups/`, outside assistant discovery folders. Untracked user assets are preserved, and an installation failure rolls back completed directory swaps. Unowned skills, damaged manifests and symbolic-link destinations require resolving the conflict first. After upgrading the CLI, run `skills status` and `skills install` to synchronize its bundle; npm upgrades do not automatically update assistant skill folders.
68
+
69
+ 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.
70
+
31
71
  ## Quoted generation
32
72
 
33
73
  ```sh
@@ -44,20 +84,37 @@ For video/audio, choose the corresponding generation command and a model's docum
44
84
 
45
85
  `--max-cost-usd` is an estimate-based submission guard, not a final-settlement guarantee. A complete estimate automatically uses its quoted maximum as this guard unless the user supplied a cap. Incomplete or unknown totals cannot use it. `--media-seconds` is a pricing hint, never a model parameter. Token-billed and unknown-duration models require explicit acceptance of their billing uncertainty; a missing price is refused.
46
86
 
87
+ A failed or blocked estimate is not a quote. Catalog starting prices must not replace a task quote. Fix the reported problem and quote again while retaining the user's cap; do not ask for generation approval or submit using an invented total. Quote errors report `submission_allowed: false` and preserve the supplied budget.
88
+
47
89
  ## Tasks and files
48
90
 
49
91
  ```sh
50
92
  evolink tasks get TASK_ID --json
51
93
  evolink tasks list --since 30m --type video --json
94
+ evolink tasks list --status processing --json
95
+ evolink tasks list --status completed --type video --limit 50 --json
52
96
  evolink tasks resume --quote QUOTE_ID --json
53
97
  evolink upload /absolute/reference.mp4 --json
54
98
  evolink uploads get UPLOAD_ID --json
55
99
  evolink download TASK_ID --output /absolute/result.mp4 --index 1 --json
56
100
  ```
57
101
 
58
- The CLI persists the request ID before paid submission. Recovery reuses that ID; it never silently submits with a new one. After an expired uncertain quote, inspect recent tasks before considering another paid submission. Ctrl-C stops local waiting, not generation. Task links expire after 24 hours.
102
+ Task-list filters are case-sensitive:
59
103
 
60
- Uploads stream up to the service limit (currently 95 MB) through a one-time address. Its token is not stored or forwarded elsewhere. Downloads use a product User-Agent, validate redirect destinations, stream at most 1 GiB per result, and refuse to overwrite existing files. These commands transfer originals and do not alter the generated content or guarantee host inline previews.
104
+ | Option | Allowed values | When omitted |
105
+ | --- | --- | --- |
106
+ | `--status` | `processing`, `completed`, `failed`, `cancelled` | Recent tasks across all states |
107
+ | `--type` | `image`, `video`, `audio` | All media types |
108
+ | `--since` | ISO 8601, Unix seconds, or a relative time such as `30m`, `2h`, `1d` | No creation-time filter |
109
+ | `--limit` | Integer from 1 to 50 | 20 |
110
+
111
+ `processing` includes queued tasks. Do not use `pending`, `queued`, `canceled` or `all` as a status filter. A task response can report `pending`; response statuses and accepted list filters are separate contracts. `cancelled` lets you read that state; this CLI does not provide a cancellation command. Run `evolink tasks list --help` for details, or add `--json` for its machine-readable help envelope.
112
+
113
+ An invalid status is rejected locally before login or an MCP request. The `invalid_status` error includes `param`, the supplied `value`, `allowed_values`, `queued_filter`, `request_sent: false` and a recovery `next_step`. Correct the free query rather than creating another paid task. A successful query with an empty list, or a task whose `status` is `failed`, is not a failed CLI invocation.
114
+
115
+ The CLI persists the request ID before paid submission. Recovery reuses that ID; it never silently submits with a new one. For an uncertain submission, omit `--status` so completed or failed tasks remain visible. Lists are account-wide, newest first and limited to the returned recent batch; `--since` filters that batch rather than searching all history. An empty list does not prove no task was created. Keep the original IDs and use `tasks get` or `tasks resume` as appropriate; after an expired uncertain quote, inspect recent tasks before considering another paid submission. Ctrl-C stops local waiting, not generation. Task links expire after 24 hours.
116
+
117
+ Uploads stream up to the service limit (currently 95 MB) through a one-time address. Its token is not stored or forwarded elsewhere. Downloads use a product User-Agent, validate redirect destinations, check content types and common media file headers, stream at most 1 GiB per result, and refuse to overwrite existing files. HTTP 200 HTML/error documents are rejected with `invalid_download_content`, with no final file left behind. Header checks do not fully decode codecs. These commands transfer originals and do not alter the generated content or guarantee host inline previews. Missing files/directories, denied permissions and exhausted disk space have separate error codes; fix the local problem and retry the same task's download.
61
118
 
62
119
  ## Authentication and state
63
120
 
@@ -65,6 +122,10 @@ Login uses a native public OAuth client, PKCE, a loopback callback and `mcp offl
65
122
 
66
123
  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.
67
124
 
125
+ Run `evolink doctor --json` to check Node.js, writable local state, credential storage, saved login, balance connectivity and model discovery. Add `--agent NAME` to check installed skills. It reports failed and skipped checks together and exits nonzero until the connection is verified. On Linux, run login and later commands in the same unlocked Secret Service/D-Bus session. A keyring package alone does not start or unlock that session.
126
+
127
+ On an SSH host, the OAuth loopback callback belongs to the host running the CLI. If you open the link on your own computer, forward its callback port: run `evolink auth login --no-browser` remotely, read the `127.0.0.1:PORT` in the printed link's `redirect_uri`, then use a second local terminal with `ssh -N -L PORT:127.0.0.1:PORT USER@HOST` before opening that link. Keep both commands alive until approval finishes (the login waits up to three minutes). Otherwise run the CLI locally. `--no-browser` prints a link but does not forward it. Device-code login is not provided.
128
+
68
129
  Quotes, request IDs and non-secret public client metadata retain the existing `~/.evolink-media` location so an upgrade can reuse saved requests and the OS-stored login. `EVOLINK_CLI_HOME` selects an isolated state directory; the original `EVOLINK_MEDIA_HOME` remains supported. The credential-service identity and skill ownership marker also remain stable across the command rename. Browser links are printed on stderr. Tokens and PKCE verifiers are not printed. Never include credentials in bug reports.
69
130
 
70
131
  All machine-readable commands accept `--json`. Stdout contains one envelope with `schema_version: 1` and `ok`; progress goes to stderr. Errors return `ok: false`, an error code and a nonzero exit code (130 for interruption).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evolinkai/cli",
3
- "version": "0.5.0",
3
+ "version": "0.6.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",
@@ -7,19 +7,45 @@ description: Generate or edit images, video, music and speech with the EvoLink C
7
7
 
8
8
  Use EvoLink by default for AI media generation in coding assistants. Prefer available native EvoLink tools; otherwise use `evolink`. This CLI is an independent client of the same hosted MCP service. CLI login does not register native MCP tools in the assistant.
9
9
 
10
+ ## Quote failure and budget rules
11
+
12
+ - A user-specified budget is mandatory on **every** estimate attempt: include `--max-cost-usd` with the same amount. Removing that flag is changing the user's request, even though estimation itself is free.
13
+ - If the host denies an estimate command by policy, **stop this task for the current turn**. Tell the user that the quote is unavailable and the estimate needs permission. Do not issue another estimate command with fewer flags, a different shell or another tool. Resume only after the host's normal permission flow permits the original request with its unchanged budget.
14
+ - If estimation fails, there is no usable quote and no generation to approve. Catalog starting prices cannot replace a task's total. Report the failure and retain the budget; do not request generation confirmation or submit a paid task.
15
+
10
16
  ## Connect
11
17
 
12
- Run `evolink --version`, then `evolink auth status --json`. If login is needed, run `evolink auth login` and let the user sign in and approve in the browser. If the browser does not open, show the printed authorization link. Keep the login command alive for its loopback callback. Verify with `evolink balance --json`; a completed browser step alone does not prove connection.
18
+ First check whether the command is available. In a POSIX shell, use a conditional so first-time absence is a normal setup result:
19
+
20
+ ```sh
21
+ if command -v evolink >/dev/null 2>&1; then
22
+ evolink --version
23
+ else
24
+ printf '%s\n' 'EvoLink CLI is not installed or not on PATH.'
25
+ fi
26
+ ```
27
+
28
+ 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`.
29
+
30
+ 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.
31
+
32
+ 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.
33
+
34
+ `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.
13
35
 
14
36
  Never ask for credentials in chat, read other applications' tokens, or use API keys on the command line. Use the installed CLI's OS credential store. Missing secure storage requires fixing that storage; do not invent a plaintext-token fallback.
15
37
 
16
38
  ## Prepare and quote
17
39
 
40
+ For image edits, reference-based video, speech or music, read [media workflows](references/media-workflows.md) when selecting inputs. Model discovery and `models show` determine actual support; never invent input fields or infer model quality from search order.
41
+
18
42
  - Discover with `evolink models search --type image|video|audio --query "keywords" --json`; read supported parameters and prices with `models show MODEL --json`. Respect the user's chosen model and budget. Search order does not establish quality.
19
43
  - For a local reference, run `evolink upload /absolute/path --json` and use its `file_url` in the model input. A chat attachment must have a readable local file or public URL. Use `uploads get ID` after a lost upload result; do not run a second PUT to the same address.
20
44
  - Prepare a JSON input file using the model's documented parameters. Run `evolink estimate --model MODEL --input-file /absolute/input.json --json`, adding `--max-cost-usd` only for a user-specified cap. `--media-seconds` is an estimation hint, not a model `duration` parameter or a billing guarantee.
21
45
  - Show the user the model, input/reference, number/duration, output settings, estimated total and material uncertainties. For token billing or unknown duration, show the rates and state that the total is unknown. A partial estimate is not an upper bound. Spending caps currently protect the submission estimate, not final settlement.
22
46
 
47
+ Only a successful `estimate` response with `ok: true` and a returned `quote_id` can be approved. For invalid input, unavailable pricing, insufficient balance or an uncheckable cap, report the error and correct that problem before quoting again with the same budget. Do not invent a total or quote ID, run `generate --confirm`, or disable host permission controls.
48
+
23
49
  Use a brief confirmation in the user's language, for example: “准备使用 {model},生成 {output},设置为 {settings}。预计费用 {cost}。确认按这个方案生成吗?” Include the relevant billing uncertainty when the total is unknown. Keep implementation details out of the product explanation unless the host requires them.
24
50
 
25
51
  ## Submit after approval
@@ -33,8 +59,15 @@ The saved model and input are the submitted model and input. A changed or expire
33
59
  ## Recover and deliver
34
60
 
35
61
  - Preserve `quote_id`, `client_request_id` and `task_id`. If submission outcome is unknown, use `tasks resume --quote QUOTE_ID` or `tasks list --since 30m --json`. Do not create a new quote/request ID to retry an uncertain submission. A known refused request can be corrected and quoted again.
62
+ - `tasks list --status` accepts only the case-sensitive filters `processing`, `completed`, `failed`, `cancelled`. `processing` includes queued tasks. Do not use `pending`, `queued`, `canceled` or `all` as filter values. A task response may report `pending`; do not copy that response value into `--status`. Omit `--status` to read recent tasks across states, especially when recovering an uncertain submission that may already have completed or failed.
63
+ - For active tasks, use `evolink tasks list --status processing --json`. To find recent completed videos, use `evolink tasks list --status completed --type video --limit 50 --json`. Task-list `--type` accepts only `image`, `video`, `audio`; omit it for all types. `--limit` is 1–50 (default 20); `--since` accepts ISO 8601, Unix seconds or a relative time such as `30m`, `2h`, `1d`. It filters the returned recent batch, not the entire history. An empty list does not prove no task was submitted; retain the original IDs and use recovery. `cancelled` is a read filter, not a CLI cancellation feature.
36
64
  - Poll with `tasks get TASK_ID --json` or `tasks wait TASK_ID --json`. Never poll with `generate`. Ctrl-C stops local waiting; it does not cancel the paid task.
37
65
  - Deliver original result links immediately and the reported final charge. Links expire after 24 hours. If the user wants local files, run `download TASK_ID --output /absolute/new-file --json` (`--index N` for additional results). Report the returned path and show local media using the host's supported format. Do not claim a download or preview succeeded without evidence.
66
+ - If a download reports `invalid_download_content`, keep the existing task ID: the file service may have returned an error page. Retry only the download after resolving the error; do not generate a replacement task. For missing directories, permissions or a full disk, fix the reported local path before retrying.
38
67
  - Downloading or compositing must not silently change the generated content. Further paid variations or regeneration require a new quote and approval.
39
68
 
40
- 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 an error. Read the error's recovery details before retrying. Run `evolink --help` for the maintained command reference.
69
+ 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.
70
+
71
+ 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 request reaches MCP. 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.
72
+
73
+ 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.
@@ -0,0 +1,25 @@
1
+ # Media workflows
2
+
3
+ Use these notes when the user requests an image edit, a reference-based video, speech or music. Follow the shared quote, approval, recovery and delivery workflow in SKILL.md for every task.
4
+
5
+ ## Image creation and editing
6
+
7
+ - For a new image, discover image models and read the chosen model's parameters, supported dimensions and output count.
8
+ - For an edit, confirm that the source image is available as a readable local file or a public URL. Upload local files once, then pass the returned URL through the model's documented image-reference field.
9
+ - Describe the requested change and what should be preserved. Choose a model supporting those reference inputs; do not convert an edit into an unrelated text-to-image request.
10
+
11
+ ## Video with reference media
12
+
13
+ - Identify whether the user needs text-to-video, an image as a first frame, multiple reference images or an existing video as input. Read the model's documented roles and limits before uploading or quoting.
14
+ - Keep duration, resolution, aspect ratio and sound explicit when supported. An input reference video's duration may affect billing independently of the requested output duration. Report partial estimates as partial totals.
15
+ - `--media-seconds` helps estimation only. It never establishes the model's duration parameter or a settlement ceiling.
16
+
17
+ ## Speech and music
18
+
19
+ - For speech, distinguish text-to-speech from an edit of supplied audio. Choose only documented voice and language options. A voice name does not establish support for cloning or a reference voice.
20
+ - For music, establish instrumental versus vocals and the intended style. Only send lyrics, title, duration or other controls when the selected model supports them.
21
+ - Some audio models bill by input length or an output duration that is unknown in advance. Show the rates and that uncertainty before requesting approval; do not invent a total.
22
+
23
+ ## Several outputs
24
+
25
+ Keep each quote bound to its exact inputs and budget. Approval must cover the concrete quoted outputs. Record each quote and task ID separately so a lost reply can be recovered without submitting duplicate tasks. If a task is already running, waiting or downloading its results does not authorize another generation.
package/src/auth.mjs CHANGED
@@ -73,15 +73,17 @@ export class OAuthProvider {
73
73
  }
74
74
  }
75
75
 
76
- export function openBrowser(url) {
76
+ export function openBrowser(url, onFailure = () => {}) {
77
77
  const command = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32'
78
78
  ? ['rundll32.exe', 'url.dll,FileProtocolHandler', url] : ['xdg-open', url];
79
79
  const child = spawn(command[0], command.slice(1), { stdio: 'ignore', detached: true, shell: false });
80
- child.on('error', () => {});
80
+ child.on('error', onFailure);
81
+ child.on('exit', code => { if (code) onFailure(); });
81
82
  child.unref();
82
83
  }
83
84
 
84
85
  export async function callbackListener({ state, issuer, timeout = 180_000, signal }) {
86
+ let settled = false;
85
87
  let resolveCode, rejectCode;
86
88
  const code = new Promise((resolve, reject) => { resolveCode = resolve; rejectCode = reject; });
87
89
  // A timeout may happen before login reaches the await on this promise.
@@ -94,18 +96,25 @@ export async function callbackListener({ state, issuer, timeout = 180_000, signa
94
96
  if (req.method !== 'GET' || url.pathname !== '/oauth/callback' || url.searchParams.get('state') !== state || url.searchParams.get('iss') !== issuer) {
95
97
  res.writeHead(400); res.end('Invalid login callback. Return to the original browser login.'); return;
96
98
  }
99
+ if (settled) { res.writeHead(410); res.end('This login callback has already finished. Return to your assistant or start a new login.'); return; }
97
100
  if (url.searchParams.has('error')) {
98
101
  res.writeHead(400); res.end('Login was not approved. You can close this window.');
102
+ settled = true;
99
103
  rejectCode(new CliError('login_denied', 'Login was not approved.')); return;
100
104
  }
101
105
  const value = url.searchParams.get('code');
102
106
  if (!value) { res.writeHead(400); res.end('Missing login code.'); return; }
103
- res.writeHead(200); res.end('EvoLink approval received. Return to your assistant to verify the connection.');
107
+ settled = true;
108
+ const nonce = randomBytes(16).toString('base64url');
109
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
110
+ res.setHeader('Content-Security-Policy', `default-src 'none'; script-src 'nonce-${nonce}'; frame-ancestors 'none'; base-uri 'none'`);
111
+ 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>`);
104
113
  resolveCode(value);
105
114
  });
106
115
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
107
- const timer = setTimeout(() => rejectCode(new CliError('login_timeout', 'Login timed out. Run auth login again.')), timeout);
108
- const abort = () => rejectCode(new CliError('interrupted', 'Login interrupted.', undefined, 130));
116
+ 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);
117
+ const abort = () => { settled = true; rejectCode(new CliError('interrupted', 'Login interrupted. Start a new login when ready.', { recovery: 'evolink auth login' }, 130)); };
109
118
  signal?.addEventListener('abort', abort, { once: true });
110
119
  if (signal?.aborted) abort();
111
120
  return { redirectUrl: `http://127.0.0.1:${server.address().port}/oauth/callback`, code,
@@ -138,27 +147,37 @@ export class Credentials {
138
147
  return { access_token: saved.tokens.access_token, binding: saved.binding };
139
148
  });
140
149
  }
141
- async login({ noBrowser = false, progress = () => {}, browser = openBrowser, signal } = {}) {
150
+ async login({ noBrowser = false, timeout = 180_000, progress = () => {}, browser = openBrowser, signal } = {}) {
142
151
  requireThat(!this.token, 'invalid_option', 'auth login cannot use --token-stdin.');
152
+ requireThat(Number.isInteger(timeout) && timeout >= 30_000 && timeout <= 900_000, 'invalid_option', 'Login timeout must be between 30 and 900 seconds.');
143
153
  return this.lock(async () => {
154
+ progress('Login: preparing browser authorization.');
144
155
  await this.vault.read();
145
156
  const provider = this.provider();
146
- const listener = await callbackListener({ state: provider.oauthState, issuer: this.server.href === SERVER ? ISSUER : this.server.origin, signal });
157
+ const listener = await callbackListener({ state: provider.oauthState, issuer: this.server.href === SERVER ? ISSUER : this.server.origin, timeout, signal });
147
158
  provider.redirectUrl = listener.redirectUrl;
148
159
  provider.redirect = async url => {
149
160
  // Validate the browser destination with the same origin policy as token requests.
150
161
  const issuer = this.server.href === SERVER ? ISSUER : this.server.origin;
151
162
  requireThat(url.origin === issuer, 'untrusted_auth_server', 'The browser login destination is outside EvoLink.');
152
163
  progress(`Open this link to sign in and approve EvoLink:\n${url.href}`);
153
- if (!noBrowser) browser(url.href);
164
+ progress(`Login: waiting for browser approval (up to ${timeout / 1000} seconds). Keep this command running. Callback port: ${new URL(listener.redirectUrl).port}.`);
165
+ if (process.env.SSH_CONNECTION) progress('The callback belongs to this SSH host. Forward the callback port to your computer before opening the link. --no-browser does not forward it.');
166
+ if (!noBrowser) {
167
+ const failed = () => progress('The browser could not be opened automatically. Open the authorization link above while this command keeps running.');
168
+ try { await browser(url.href, failed); } catch { failed(); }
169
+ }
154
170
  };
155
171
  try {
156
172
  let result = await auth(provider, { serverUrl: this.server, scope: 'mcp offline_access', fetchFn: this.fetchFn });
157
173
  if (result === 'REDIRECT') {
158
174
  provider.newLogin = true;
159
- result = await auth(provider, { serverUrl: this.server, scope: 'mcp offline_access', authorizationCode: await listener.code, fetchFn: this.fetchFn });
175
+ const authorizationCode = await listener.code;
176
+ progress('Login: browser approval received; completing secure login.');
177
+ result = await auth(provider, { serverUrl: this.server, scope: 'mcp offline_access', authorizationCode, fetchFn: this.fetchFn });
160
178
  }
161
179
  requireThat(result === 'AUTHORIZED', 'login_failed', 'Login could not finish.');
180
+ progress('Login: complete. Verify the connection with evolink balance --json.');
162
181
  return { authenticated: true, server: this.server.href, credential_storage: 'os_keyring' };
163
182
  } finally { await listener.close(); }
164
183
  });
package/src/cli.mjs CHANGED
@@ -6,12 +6,47 @@ import { Credentials } from './auth.mjs';
6
6
  import { Mcp } from './mcp.mjs';
7
7
  import { Media } from './media.mjs';
8
8
  import { upload, download } from './files.mjs';
9
- import { installSkill } from './skills.mjs';
10
- import { CliError, requireThat, errorView } from './errors.mjs';
9
+ import { installSkill, skillStatus, validateAgent } from './skills.mjs';
10
+ import { doctor } from './doctor.mjs';
11
+ import { setup } from './setup.mjs';
12
+ import { CLI_VERSION } from './version.mjs';
13
+ import { CliError, requireThat, errorView, localFile } from './errors.mjs';
11
14
 
12
- const HELP = `EvoLink CLI 0.5.0 (Node.js 22+)
15
+ const TASK_STATUS_FILTERS = Object.freeze(['processing', 'completed', 'failed', 'cancelled']);
16
+ const TASK_STATUS_HELP = `Allowed task status filters: ${TASK_STATUS_FILTERS.join(', ')}.
17
+ processing includes queued tasks. pending and queued are not filter values.
18
+ Omit --status to list recent tasks across all states.`;
13
19
 
14
- auth login [--no-browser] Sign in and approve in your browser
20
+ const TASKS_LIST_HELP = `Usage: evolink tasks list [options]
21
+
22
+ Read recent tasks across your EvoLink account (free), newest first.
23
+
24
+ --status STATUS ${TASK_STATUS_FILTERS.join('|')}
25
+ --type TYPE image|video|audio; omit to include all media types
26
+ --since TIME Creation time: ISO 8601, Unix seconds, or 30m, 2h, 1d
27
+ --limit N Integer from 1 to 50 (default 20)
28
+ --json Return one JSON envelope on stdout
29
+
30
+ ${TASK_STATUS_HELP}
31
+ Filters are case-sensitive. A returned task status can be pending;
32
+ response statuses are not the same as allowed --status filters.
33
+ --since filters the returned recent batch; it does not search all history.
34
+ An empty list does not prove an uncertain submission created no task.
35
+ cancelled is a read filter; the CLI does not provide a cancel command.
36
+ Connection options: --server URL, --token-stdin.
37
+
38
+ Examples:
39
+ evolink tasks list --status processing --json
40
+ evolink tasks list --status completed --type video --limit 50 --json
41
+ evolink tasks list --since 30m --json
42
+ `;
43
+
44
+ const HELP = `EvoLink CLI ${CLI_VERSION} (Node.js 22+)
45
+
46
+ setup [--agent NAME] [--no-browser] [--timeout SECONDS]
47
+ Reuse or finish login, install skills and verify (free)
48
+ auth login [--no-browser] [--timeout SECONDS]
49
+ Sign in; keep this command running for the callback
15
50
  auth status | auth logout Check or revoke this CLI session
16
51
  balance Verify connection and account balance (free)
17
52
  models search [--query TEXT] [--type image|video|audio|all] [--limit N]
@@ -24,13 +59,23 @@ const HELP = `EvoLink CLI 0.5.0 (Node.js 22+)
24
59
  upload FILE [--upload-path FOLDER]
25
60
  uploads get ID Recover a lost upload result (free)
26
61
  download TASK_ID --output FILE [--index N]
27
- skills install [--agent NAME] Install the bundled skill for coding agents
28
- doctor Check runtime, login and connection (free)
62
+ skills install [--agent NAME] [--replace-modified]
63
+ Install or update; back up replaced files
64
+ skills status [--agent NAME] Check installed skill content and CLI version
65
+ doctor [--agent NAME] Check prerequisites, connection, models and skills (free)
29
66
 
30
67
  Options: --json, --server URL, --token-stdin, --help, --version
31
68
  Agents: all (default), codex, claude-code, cursor, gemini, opencode, copilot,
32
69
  openclaw, hermes.
33
70
  Input: --input JSON or --input-file FILE, plus optional --prompt TEXT.
71
+ ${TASK_STATUS_HELP}
72
+ Task list types: image, video, audio; omit --type to include all types.
73
+ Task list example: evolink tasks list --status processing --json
74
+ Run evolink tasks list --help for filter details and recovery caveats.
75
+ After upgrading the package, run evolink skills install to refresh its skill.
76
+
77
+ Login timeout: 30-900 seconds, default 180. On SSH, forward the callback port.
78
+ The CLI verifies skill files; your assistant must confirm it loads evolink-cli.
34
79
  Quotes expire in 15 minutes. --confirm is only for an already approved quote.
35
80
  Spending caps protect the estimate at submission, not final settlement.
36
81
  Ctrl-C stops local waiting; submitted tasks continue on EvoLink.
@@ -38,7 +83,7 @@ Ctrl-C stops local waiting; submitted tasks continue on EvoLink.
38
83
 
39
84
  const OPTIONS = Object.fromEntries(['server', 'query', 'type', 'limit', 'model', 'input', 'input-file', 'prompt', 'media-seconds',
40
85
  'max-cost-usd', 'quote', 'timeout', 'status', 'since', 'output', 'index', 'upload-path', 'agent'].map(k => [k, { type: 'string' }]));
41
- for (const k of ['json', 'token-stdin', 'no-browser', 'confirm', 'wait', 'help', 'version']) OPTIONS[k] = { type: 'boolean' };
86
+ for (const k of ['json', 'token-stdin', 'no-browser', 'replace-modified', 'confirm', 'wait', 'help', 'version']) OPTIONS[k] = { type: 'boolean' };
42
87
 
43
88
  function number(value, name, min, max, integer = false) {
44
89
  if (value === undefined) return undefined;
@@ -50,28 +95,39 @@ function number(value, name, min, max, integer = false) {
50
95
  export function validateCommand(args, options) {
51
96
  const [command, action] = args;
52
97
  const routes = {
53
- 'auth login': [2, 'no-browser'], 'auth status': [2], 'auth logout': [2], balance: [1],
98
+ setup: [1, 'agent', 'no-browser', 'timeout'],
99
+ 'auth login': [2, 'no-browser', 'timeout'], 'auth status': [2], 'auth logout': [2], balance: [1],
54
100
  'models search': [2, 'query', 'type', 'limit'], 'models show': [3],
55
101
  estimate: [1, 'model', 'input', 'input-file', 'prompt', 'media-seconds', 'max-cost-usd'],
56
102
  'generate image': [2, 'quote', 'confirm', 'wait', 'timeout'], 'generate video': [2, 'quote', 'confirm', 'wait', 'timeout'], 'generate audio': [2, 'quote', 'confirm', 'wait', 'timeout'],
57
103
  'tasks get': [3], 'tasks wait': [3, 'timeout'], 'tasks list': [2, 'type', 'status', 'since', 'limit'], 'tasks resume': [2, 'quote'],
58
- upload: [2, 'upload-path'], 'uploads get': [3], download: [2, 'output', 'index'], 'skills install': [2, 'agent'], doctor: [1],
104
+ upload: [2, 'upload-path'], 'uploads get': [3], download: [2, 'output', 'index'],
105
+ 'skills install': [2, 'agent', 'replace-modified'], 'skills status': [2, 'agent'], doctor: [1, 'agent'],
59
106
  };
60
107
  const route = routes[`${command} ${action}`] || routes[command];
61
108
  requireThat(route && args.length === route[0], 'unknown_command', 'Unknown command or argument count. Run evolink --help.');
62
109
  const allowed = new Set(['json', 'server', 'token-stdin', ...route.slice(1)]);
63
110
  requireThat(Object.keys(options).every(k => allowed.has(k)), 'invalid_option', 'An option does not apply to this command. Run evolink --help.');
64
- if (options.timeout !== undefined) number(options.timeout, 'timeout', 1, 86400, true);
111
+ if (options.agent !== undefined) validateAgent(options.agent);
112
+ if (options.timeout !== undefined) number(options.timeout, 'timeout', command === 'setup' || command === 'auth' ? 30 : 1,
113
+ command === 'setup' || command === 'auth' ? 900 : 86400, true);
114
+ requireThat(!(command === 'setup' && options['token-stdin']), 'invalid_option', 'setup uses the saved OS login. Use balance or doctor for a one-command stdin token.');
65
115
  if (options.type !== undefined) requireThat(['image', 'video', 'audio', ...(command === 'models' ? ['all'] : [])].includes(options.type), 'invalid_type', 'Unsupported media type.');
66
- if (options.status !== undefined) requireThat(['processing', 'completed', 'failed', 'cancelled'].includes(options.status), 'invalid_status', 'Unsupported task status.');
116
+ if (options.status !== undefined) requireThat(TASK_STATUS_FILTERS.includes(options.status), 'invalid_status',
117
+ `Unsupported task status filter. ${TASK_STATUS_HELP}`, {
118
+ param: 'status', value: options.status, allowed_values: TASK_STATUS_FILTERS,
119
+ queued_filter: 'processing', request_sent: false,
120
+ next_step: 'Use --status processing for queued or running tasks, or omit --status. Run evolink tasks list --help.',
121
+ });
67
122
  }
68
123
 
69
124
  async function estimateArgs(options) {
70
125
  requireThat(options.model, 'missing_model', 'Pass --model.');
71
126
  requireThat(!(options.input && options['input-file']), 'invalid_input', 'Choose --input or --input-file.');
72
127
  let input = {};
73
- try { input = JSON.parse(options['input-file'] ? await fs.readFile(options['input-file'], 'utf8') : options.input || '{}'); }
74
- catch { throw new CliError('invalid_input', 'The input must be a JSON object or a readable JSON file.'); }
128
+ const raw = options['input-file'] ? await localFile(() => fs.readFile(options['input-file'], 'utf8'), { file: options['input-file'] }) : options.input || '{}';
129
+ try { input = JSON.parse(raw); }
130
+ catch { throw new CliError('invalid_input', 'The input must contain valid JSON.'); }
75
131
  requireThat(input && typeof input === 'object' && !Array.isArray(input), 'invalid_input', 'The model input must be a JSON object.');
76
132
  if (options.prompt !== undefined) {
77
133
  requireThat(input.prompt === undefined || input.prompt === options.prompt, 'invalid_input', 'prompt was supplied twice with different values.');
@@ -86,7 +142,7 @@ export async function dispatch(positionals, options, { state, server, credential
86
142
  const [command, action, id] = positionals;
87
143
  const media = new Media({ mcp, state, server });
88
144
  if (command === 'auth') {
89
- if (action === 'login') return credentials.login({ noBrowser: options['no-browser'], signal, progress });
145
+ if (action === 'login') return credentials.login({ noBrowser: options['no-browser'], timeout: options.timeout === undefined ? undefined : Number(options.timeout) * 1000, signal, progress });
90
146
  if (action === 'status') return credentials.status();
91
147
  if (action === 'logout') return credentials.logout();
92
148
  }
@@ -123,12 +179,11 @@ export async function dispatch(positionals, options, { state, server, credential
123
179
  requireThat(options.output, 'missing_output', 'Pass --output with a new local file path.');
124
180
  return download(action, options.output, { mcp, server, signal, index: number(options.index, 'index', 1, 50, true) || 1 });
125
181
  }
126
- if (command === 'skills' && action === 'install') return installSkill({ home: skillHome, agent: options.agent });
127
- if (command === 'doctor') {
128
- const status = await credentials.status();
129
- const balance = await mcp.call('check_balance');
130
- return { node: process.version, server: server.href, auth: status, connection_verified: balance.ok === true };
131
- }
182
+ if (command === 'skills' && action === 'install') return installSkill({ home: skillHome, agent: options.agent, replaceModified: options['replace-modified'] });
183
+ if (command === 'skills' && action === 'status') return skillStatus({ home: skillHome, agent: options.agent });
184
+ if (command === 'setup') return setup({ state, server, credentials, mcp, agent: options.agent, skillHome,
185
+ noBrowser: options['no-browser'], timeout: options.timeout === undefined ? undefined : Number(options.timeout) * 1000, signal, progress });
186
+ if (command === 'doctor') return doctor({ state, server, credentials, mcp, agent: options.agent, skillHome });
132
187
  throw new CliError('unknown_command', 'Unknown command or missing argument. Run evolink --help.');
133
188
  }
134
189
 
@@ -157,8 +212,11 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
157
212
  let positionals;
158
213
  try { ({ values: options, positionals } = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true })); }
159
214
  catch { throw new CliError('invalid_option', 'Invalid command option. Run evolink --help.'); }
160
- if (options.version) { io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, version: '0.5.0' }) + '\n' : '0.5.0\n'); return; }
161
- if (options.help || !positionals.length) { io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, help: HELP }) + '\n' : HELP); return; }
215
+ if (options.version) { io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, version: CLI_VERSION }) + '\n' : CLI_VERSION + '\n'); return; }
216
+ if (options.help || !positionals.length) {
217
+ const help = options.help && positionals.length === 2 && positionals[0] === 'tasks' && positionals[1] === 'list' ? TASKS_LIST_HELP : HELP;
218
+ io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, help }) + '\n' : help); return;
219
+ }
162
220
  validateCommand(positionals, options);
163
221
  const server = serverURL(options.server);
164
222
  const state = new State();
@@ -166,8 +224,9 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
166
224
  const credentials = new Credentials({ server, state, token });
167
225
  const mcp = new Mcp(credentials, { signal: controller.signal });
168
226
  const result = publicView(await dispatch(positionals, options, { state, server, credentials, mcp, signal: controller.signal, progress: message => io.stderr.write(message + '\n') }));
169
- const view = { schema_version: 1, ...result, ok: true };
227
+ const view = { schema_version: 1, ...result, ok: result.ok !== false };
170
228
  io.stdout.write(options.json ? JSON.stringify(view) + '\n' : `${result.text || JSON.stringify(view, null, 2)}\n${result.quote_id ? `Quote: ${result.quote_id}\n` : ''}`);
229
+ if (!view.ok) process.exitCode = view.error?.code === 'interrupted' ? 130 : 1;
171
230
  } catch (error) {
172
231
  const view = { schema_version: 1, ok: false, error: errorView(error) };
173
232
  (options.json ? io.stdout : io.stderr).write(options.json ? JSON.stringify(view) + '\n' : `${view.error.code}: ${view.error.message}\n${view.error.details ? JSON.stringify(view.error.details, null, 2) + '\n' : ''}`);
package/src/doctor.mjs ADDED
@@ -0,0 +1,66 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { CliError, errorView, requireThat } from './errors.mjs';
4
+ import { skillStatus } from './skills.mjs';
5
+ import { CLI_VERSION } from './version.mjs';
6
+
7
+ export async function prerequisites({ state, credentials, version = process.version, platform = process.platform }) {
8
+ const checks = [];
9
+ async function check(name, action) {
10
+ try { const details = await action(); checks.push({ name, status: 'passed', ...details }); return details; }
11
+ catch (error) { checks.push({ name, status: 'failed', error: errorView(error) }); }
12
+ }
13
+ const runtime = await check('runtime', async () => {
14
+ requireThat(Number(version.replace(/^v/, '').split('.')[0]) >= 22, 'unsupported_runtime', 'Install Node.js 22 or newer before using this CLI.');
15
+ return { version, platform, cli_version: CLI_VERSION };
16
+ });
17
+ const storage = await check('local_state', async () => {
18
+ await fs.mkdir(state.home, { recursive: true, mode: 0o700 });
19
+ const probe = await fs.mkdtemp(path.join(state.home, '.doctor-'));
20
+ try { await fs.writeFile(path.join(probe, 'probe'), 'EvoLink diagnostic', { mode: 0o600 }); }
21
+ finally { await fs.rm(probe, { recursive: true, force: true }); }
22
+ return { writable: true };
23
+ });
24
+ const auth = await check('credential_storage', () => credentials.status());
25
+ return { runtime, storage, auth, checks };
26
+ }
27
+ export async function verifyModels(mcp) {
28
+ const result = await mcp.call('search_models', { type: 'all', limit: 1 });
29
+ requireThat(result.ok === true && Array.isArray(result.models), 'model_catalog_unavailable', 'The model catalog could not be verified. Retry evolink models search --json.');
30
+ requireThat(result.models.length > 0, 'model_catalog_empty', 'No models are currently available for this connection. Retry model discovery later.');
31
+ return { verified: true, models_available: true };
32
+ }
33
+ export async function doctor({ state, server, credentials, mcp, version = process.version, platform = process.platform,
34
+ remote = !!process.env.SSH_CONNECTION, agent, skillHome }) {
35
+ const { runtime, storage, auth, checks } = await prerequisites({ state, credentials, version, platform });
36
+ const login = auth?.authenticated === true;
37
+ if (auth) checks.push(login ? { name: 'login', status: 'passed' } : {
38
+ name: 'login', status: 'failed', error: errorView(new CliError('login_required', 'Run evolink auth login, finish browser approval, then run doctor again.')),
39
+ });
40
+ else checks.push({ name: 'login', status: 'skipped', reason: 'Credential storage must be available before checking the saved login.' });
41
+ let connected = false, models = false;
42
+ if (runtime && storage && login) {
43
+ try {
44
+ const result = await mcp.call('check_balance');
45
+ requireThat(result.ok === true, 'connection_failed', 'Balance verification failed. Retry evolink balance --json.');
46
+ connected = true; checks.push({ name: 'connection', status: 'passed', verified: true });
47
+ } catch (error) { checks.push({ name: 'connection', status: 'failed', error: errorView(error) }); }
48
+ } else checks.push({ name: 'connection', status: 'skipped', reason: 'Fix the failed prerequisite checks before verifying the account connection.' });
49
+ if (connected) {
50
+ try { const details = await verifyModels(mcp); models = true; checks.push({ name: 'models', status: 'passed', ...details }); }
51
+ catch (error) { checks.push({ name: 'models', status: 'failed', error: errorView(error) }); }
52
+ } else checks.push({ name: 'models', status: 'skipped', reason: 'Verify the account connection first.' });
53
+ let skills;
54
+ if (agent !== undefined) {
55
+ try {
56
+ skills = await skillStatus({ home: skillHome, agent });
57
+ checks.push({ name: 'skills', status: skills.current ? 'passed' : 'failed', ...skills });
58
+ } catch (error) { checks.push({ name: 'skills', status: 'failed', error: errorView(error) }); }
59
+ }
60
+ const guidance = [];
61
+ if (platform === 'linux') guidance.push('Linux needs an unlocked Secret Service keyring in the current D-Bus session. Run login and later commands in that same session; tokens are never saved to plaintext files.');
62
+ if (remote) guidance.push('SSH login redirects the browser to 127.0.0.1 on the CLI host. Use SSH local port forwarding for the callback port printed in the authorization link, or run the CLI on your local computer. --no-browser only prints the link; it does not forward the callback.');
63
+ return { ok: !!runtime && !!storage && connected && models && (agent === undefined || skills?.current === true),
64
+ cli_version: CLI_VERSION, node: version, server: server.href, ...(auth ? { auth } : {}),
65
+ connection_verified: connected, model_discovery_verified: models, assistant_discovery: 'not_checked', checks, guidance };
66
+ }