@evolinkai/cli 0.5.1 → 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 +33 -1
- package/package.json +1 -1
- package/skills/evolink-cli/SKILL.md +19 -2
- package/skills/evolink-cli/references/media-workflows.md +25 -0
- package/src/auth.mjs +28 -9
- package/src/cli.mjs +38 -21
- package/src/doctor.mjs +66 -0
- package/src/errors.mjs +25 -1
- package/src/files.mjs +26 -7
- package/src/mcp.mjs +2 -1
- package/src/media-content.mjs +31 -0
- package/src/media.mjs +40 -10
- package/src/network.mjs +55 -17
- package/src/setup.mjs +69 -0
- package/src/skills.mjs +159 -22
- package/src/state.mjs +64 -25
- package/src/version.mjs +3 -0
package/README.md
CHANGED
|
@@ -42,6 +42,32 @@ The skill is bundled with the package. By default it installs into `~/.agents/sk
|
|
|
42
42
|
|
|
43
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
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
|
+
|
|
45
71
|
## Quoted generation
|
|
46
72
|
|
|
47
73
|
```sh
|
|
@@ -58,6 +84,8 @@ For video/audio, choose the corresponding generation command and a model's docum
|
|
|
58
84
|
|
|
59
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.
|
|
60
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
|
+
|
|
61
89
|
## Tasks and files
|
|
62
90
|
|
|
63
91
|
```sh
|
|
@@ -86,7 +114,7 @@ An invalid status is rejected locally before login or an MCP request. The `inval
|
|
|
86
114
|
|
|
87
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.
|
|
88
116
|
|
|
89
|
-
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.
|
|
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.
|
|
90
118
|
|
|
91
119
|
## Authentication and state
|
|
92
120
|
|
|
@@ -94,6 +122,10 @@ Login uses a native public OAuth client, PKCE, a loopback callback and `mcp offl
|
|
|
94
122
|
|
|
95
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.
|
|
96
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
|
+
|
|
97
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.
|
|
98
130
|
|
|
99
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
|
@@ -7,6 +7,12 @@ 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
18
|
First check whether the command is available. In a POSIX shell, use a conditional so first-time absence is a normal setup result:
|
|
@@ -21,19 +27,25 @@ fi
|
|
|
21
27
|
|
|
22
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`.
|
|
23
29
|
|
|
24
|
-
|
|
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.
|
|
25
31
|
|
|
26
|
-
|
|
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.
|
|
27
35
|
|
|
28
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.
|
|
29
37
|
|
|
30
38
|
## Prepare and quote
|
|
31
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
|
+
|
|
32
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.
|
|
33
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.
|
|
34
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.
|
|
35
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.
|
|
36
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
|
+
|
|
37
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.
|
|
38
50
|
|
|
39
51
|
## Submit after approval
|
|
@@ -51,6 +63,11 @@ The saved model and input are the submitted model and input. A changed or expire
|
|
|
51
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.
|
|
52
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.
|
|
53
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.
|
|
54
67
|
- Downloading or compositing must not silently change the generated content. Further paid variations or regeneration require a new quote and approval.
|
|
55
68
|
|
|
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
|
+
|
|
56
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
|
-
|
|
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.
|
|
108
|
-
const abort = () => rejectCode(new CliError('interrupted', 'Login interrupted.',
|
|
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
|
-
|
|
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
|
-
|
|
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,8 +6,11 @@ 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 {
|
|
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
15
|
const TASK_STATUS_FILTERS = Object.freeze(['processing', 'completed', 'failed', 'cancelled']);
|
|
13
16
|
const TASK_STATUS_HELP = `Allowed task status filters: ${TASK_STATUS_FILTERS.join(', ')}.
|
|
@@ -38,9 +41,12 @@ Examples:
|
|
|
38
41
|
evolink tasks list --since 30m --json
|
|
39
42
|
`;
|
|
40
43
|
|
|
41
|
-
const HELP = `EvoLink CLI
|
|
44
|
+
const HELP = `EvoLink CLI ${CLI_VERSION} (Node.js 22+)
|
|
42
45
|
|
|
43
|
-
|
|
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
|
|
44
50
|
auth status | auth logout Check or revoke this CLI session
|
|
45
51
|
balance Verify connection and account balance (free)
|
|
46
52
|
models search [--query TEXT] [--type image|video|audio|all] [--limit N]
|
|
@@ -53,8 +59,10 @@ const HELP = `EvoLink CLI 0.5.1 (Node.js 22+)
|
|
|
53
59
|
upload FILE [--upload-path FOLDER]
|
|
54
60
|
uploads get ID Recover a lost upload result (free)
|
|
55
61
|
download TASK_ID --output FILE [--index N]
|
|
56
|
-
skills install [--agent NAME]
|
|
57
|
-
|
|
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)
|
|
58
66
|
|
|
59
67
|
Options: --json, --server URL, --token-stdin, --help, --version
|
|
60
68
|
Agents: all (default), codex, claude-code, cursor, gemini, opencode, copilot,
|
|
@@ -65,6 +73,9 @@ Task list types: image, video, audio; omit --type to include all types.
|
|
|
65
73
|
Task list example: evolink tasks list --status processing --json
|
|
66
74
|
Run evolink tasks list --help for filter details and recovery caveats.
|
|
67
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.
|
|
68
79
|
Quotes expire in 15 minutes. --confirm is only for an already approved quote.
|
|
69
80
|
Spending caps protect the estimate at submission, not final settlement.
|
|
70
81
|
Ctrl-C stops local waiting; submitted tasks continue on EvoLink.
|
|
@@ -72,7 +83,7 @@ Ctrl-C stops local waiting; submitted tasks continue on EvoLink.
|
|
|
72
83
|
|
|
73
84
|
const OPTIONS = Object.fromEntries(['server', 'query', 'type', 'limit', 'model', 'input', 'input-file', 'prompt', 'media-seconds',
|
|
74
85
|
'max-cost-usd', 'quote', 'timeout', 'status', 'since', 'output', 'index', 'upload-path', 'agent'].map(k => [k, { type: 'string' }]));
|
|
75
|
-
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' };
|
|
76
87
|
|
|
77
88
|
function number(value, name, min, max, integer = false) {
|
|
78
89
|
if (value === undefined) return undefined;
|
|
@@ -84,18 +95,23 @@ function number(value, name, min, max, integer = false) {
|
|
|
84
95
|
export function validateCommand(args, options) {
|
|
85
96
|
const [command, action] = args;
|
|
86
97
|
const routes = {
|
|
87
|
-
|
|
98
|
+
setup: [1, 'agent', 'no-browser', 'timeout'],
|
|
99
|
+
'auth login': [2, 'no-browser', 'timeout'], 'auth status': [2], 'auth logout': [2], balance: [1],
|
|
88
100
|
'models search': [2, 'query', 'type', 'limit'], 'models show': [3],
|
|
89
101
|
estimate: [1, 'model', 'input', 'input-file', 'prompt', 'media-seconds', 'max-cost-usd'],
|
|
90
102
|
'generate image': [2, 'quote', 'confirm', 'wait', 'timeout'], 'generate video': [2, 'quote', 'confirm', 'wait', 'timeout'], 'generate audio': [2, 'quote', 'confirm', 'wait', 'timeout'],
|
|
91
103
|
'tasks get': [3], 'tasks wait': [3, 'timeout'], 'tasks list': [2, 'type', 'status', 'since', 'limit'], 'tasks resume': [2, 'quote'],
|
|
92
|
-
upload: [2, 'upload-path'], 'uploads get': [3], download: [2, 'output', 'index'],
|
|
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'],
|
|
93
106
|
};
|
|
94
107
|
const route = routes[`${command} ${action}`] || routes[command];
|
|
95
108
|
requireThat(route && args.length === route[0], 'unknown_command', 'Unknown command or argument count. Run evolink --help.');
|
|
96
109
|
const allowed = new Set(['json', 'server', 'token-stdin', ...route.slice(1)]);
|
|
97
110
|
requireThat(Object.keys(options).every(k => allowed.has(k)), 'invalid_option', 'An option does not apply to this command. Run evolink --help.');
|
|
98
|
-
if (options.
|
|
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.');
|
|
99
115
|
if (options.type !== undefined) requireThat(['image', 'video', 'audio', ...(command === 'models' ? ['all'] : [])].includes(options.type), 'invalid_type', 'Unsupported media type.');
|
|
100
116
|
if (options.status !== undefined) requireThat(TASK_STATUS_FILTERS.includes(options.status), 'invalid_status',
|
|
101
117
|
`Unsupported task status filter. ${TASK_STATUS_HELP}`, {
|
|
@@ -109,8 +125,9 @@ async function estimateArgs(options) {
|
|
|
109
125
|
requireThat(options.model, 'missing_model', 'Pass --model.');
|
|
110
126
|
requireThat(!(options.input && options['input-file']), 'invalid_input', 'Choose --input or --input-file.');
|
|
111
127
|
let input = {};
|
|
112
|
-
|
|
113
|
-
|
|
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.'); }
|
|
114
131
|
requireThat(input && typeof input === 'object' && !Array.isArray(input), 'invalid_input', 'The model input must be a JSON object.');
|
|
115
132
|
if (options.prompt !== undefined) {
|
|
116
133
|
requireThat(input.prompt === undefined || input.prompt === options.prompt, 'invalid_input', 'prompt was supplied twice with different values.');
|
|
@@ -125,7 +142,7 @@ export async function dispatch(positionals, options, { state, server, credential
|
|
|
125
142
|
const [command, action, id] = positionals;
|
|
126
143
|
const media = new Media({ mcp, state, server });
|
|
127
144
|
if (command === 'auth') {
|
|
128
|
-
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 });
|
|
129
146
|
if (action === 'status') return credentials.status();
|
|
130
147
|
if (action === 'logout') return credentials.logout();
|
|
131
148
|
}
|
|
@@ -162,12 +179,11 @@ export async function dispatch(positionals, options, { state, server, credential
|
|
|
162
179
|
requireThat(options.output, 'missing_output', 'Pass --output with a new local file path.');
|
|
163
180
|
return download(action, options.output, { mcp, server, signal, index: number(options.index, 'index', 1, 50, true) || 1 });
|
|
164
181
|
}
|
|
165
|
-
if (command === 'skills' && action === 'install') return installSkill({ home: skillHome, agent: options.agent });
|
|
166
|
-
if (command === '
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
}
|
|
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 });
|
|
171
187
|
throw new CliError('unknown_command', 'Unknown command or missing argument. Run evolink --help.');
|
|
172
188
|
}
|
|
173
189
|
|
|
@@ -196,7 +212,7 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
|
|
|
196
212
|
let positionals;
|
|
197
213
|
try { ({ values: options, positionals } = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true })); }
|
|
198
214
|
catch { throw new CliError('invalid_option', 'Invalid command option. Run evolink --help.'); }
|
|
199
|
-
if (options.version) { io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, version:
|
|
215
|
+
if (options.version) { io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, version: CLI_VERSION }) + '\n' : CLI_VERSION + '\n'); return; }
|
|
200
216
|
if (options.help || !positionals.length) {
|
|
201
217
|
const help = options.help && positionals.length === 2 && positionals[0] === 'tasks' && positionals[1] === 'list' ? TASKS_LIST_HELP : HELP;
|
|
202
218
|
io.stdout.write(options.json ? JSON.stringify({ schema_version: 1, ok: true, help }) + '\n' : help); return;
|
|
@@ -208,8 +224,9 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
|
|
|
208
224
|
const credentials = new Credentials({ server, state, token });
|
|
209
225
|
const mcp = new Mcp(credentials, { signal: controller.signal });
|
|
210
226
|
const result = publicView(await dispatch(positionals, options, { state, server, credentials, mcp, signal: controller.signal, progress: message => io.stderr.write(message + '\n') }));
|
|
211
|
-
const view = { schema_version: 1, ...result, ok:
|
|
227
|
+
const view = { schema_version: 1, ...result, ok: result.ok !== false };
|
|
212
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;
|
|
213
230
|
} catch (error) {
|
|
214
231
|
const view = { schema_version: 1, ok: false, error: errorView(error) };
|
|
215
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
|
+
}
|
package/src/errors.mjs
CHANGED
|
@@ -11,15 +11,39 @@ export function requireThat(condition, code, message, details) {
|
|
|
11
11
|
if (!condition) throw new CliError(code, message, details);
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
export function fileError(error, { file, missing = 'file_not_found' } = {}) {
|
|
15
|
+
if (error instanceof CliError) return error;
|
|
16
|
+
const messages = {
|
|
17
|
+
ENOENT: [missing, missing === 'output_directory_missing' ? 'The output directory does not exist. Create it or choose an existing directory.' : 'The local file does not exist. Check the path.'],
|
|
18
|
+
ENOTDIR: ['path_not_directory', 'A parent path is not a directory. Choose a valid file path.'],
|
|
19
|
+
EACCES: ['file_permission_denied', 'Permission to access the local file or directory was denied. Choose a location you can read or write.'],
|
|
20
|
+
EPERM: ['file_permission_denied', 'Permission to access the local file or directory was denied. Choose a location you can read or write.'],
|
|
21
|
+
EROFS: ['filesystem_read_only', 'The filesystem is read-only. Choose a writable location.'],
|
|
22
|
+
ENOSPC: ['disk_full', 'The filesystem has no free space. Free space or choose another disk, then retry.'],
|
|
23
|
+
EDQUOT: ['disk_full', 'The filesystem quota is exhausted. Free space or choose another disk, then retry.'],
|
|
24
|
+
EEXIST: ['file_exists', 'The output file already exists. Choose another path.'],
|
|
25
|
+
EISDIR: ['invalid_file', 'The path is a directory. Choose a regular file.'],
|
|
26
|
+
};
|
|
27
|
+
const mapped = messages[error?.code];
|
|
28
|
+
return mapped ? new CliError(...mapped, file ? { path: file } : undefined) : error;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function localFile(action, context) {
|
|
32
|
+
try { return await action(); }
|
|
33
|
+
catch (error) { throw fileError(error, context); }
|
|
34
|
+
}
|
|
35
|
+
|
|
14
36
|
export function safeMessage(message) {
|
|
15
37
|
return String(message)
|
|
16
38
|
.replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')
|
|
17
39
|
.replace(/\b(?:sk-|evup_)[a-zA-Z0-9_-]+/g, '[redacted]')
|
|
18
40
|
.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '[redacted]')
|
|
41
|
+
.replace(/([?&](?:token|access_token|refresh_token|api_key|key|client_secret|code|code_verifier)=)[^\s&#"'<>]+/gi, '$1[redacted]')
|
|
19
42
|
.slice(0, 2000);
|
|
20
43
|
}
|
|
21
44
|
|
|
22
45
|
export function errorView(error) {
|
|
46
|
+
error = fileError(error);
|
|
23
47
|
if (!(error instanceof CliError)) {
|
|
24
48
|
return { code: 'request_failed', message: 'The operation failed. Retry free queries; use the saved quote to recover a submission.' };
|
|
25
49
|
}
|
|
@@ -30,7 +54,7 @@ function safeDetails(value) {
|
|
|
30
54
|
if (typeof value === 'string') return safeMessage(value);
|
|
31
55
|
if (Array.isArray(value)) return value.map(safeDetails);
|
|
32
56
|
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value)
|
|
33
|
-
.filter(([key]) => !key.startsWith('_') && !/^(access_token|refresh_token|client_secret|code_verifier|authorization|upload_url)$/i.test(key))
|
|
57
|
+
.filter(([key]) => !key.startsWith('_') && !/^(access_token|refresh_token|client_secret|code_verifier|authorization|upload_url|api_key|apiKey|x-api-key|x-goog-api-key|token|secret|password)$/i.test(key))
|
|
34
58
|
.map(([key, nested]) => [key, safeDetails(nested)]));
|
|
35
59
|
return value;
|
|
36
60
|
}
|
package/src/files.mjs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import * as fs from 'node:fs/promises';
|
|
2
|
-
import { createReadStream, createWriteStream } from 'node:fs';
|
|
2
|
+
import { createReadStream, createWriteStream, constants } from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { randomUUID, createHash } from 'node:crypto';
|
|
5
5
|
import { Readable, Transform } from 'node:stream';
|
|
6
6
|
import { pipeline } from 'node:stream/promises';
|
|
7
7
|
import { resultFetch, USER_AGENT, loopback } from './network.mjs';
|
|
8
|
-
import { CliError, requireThat } from './errors.mjs';
|
|
8
|
+
import { CliError, requireThat, localFile, fileError } from './errors.mjs';
|
|
9
|
+
import { checkContentType, checkMediaPrefix } from './media-content.mjs';
|
|
9
10
|
|
|
10
11
|
const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp',
|
|
11
12
|
'.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.aac': 'audio/aac', '.flac': 'audio/flac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg',
|
|
@@ -13,10 +14,11 @@ const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
|
|
|
13
14
|
|
|
14
15
|
export async function upload(file, { mcp, state, server, signal, upload_path, fetchFn = fetch }) {
|
|
15
16
|
const full = path.resolve(file);
|
|
16
|
-
const stat = await fs.stat(full);
|
|
17
|
+
const stat = await localFile(() => fs.stat(full), { file: full });
|
|
17
18
|
requireThat(stat.isFile() && stat.size > 0 && stat.size <= 95 * 1024 * 1024, 'invalid_file', 'Uploads must be regular files between 1 byte and 95 MB.');
|
|
18
19
|
const type = MIME[path.extname(full).toLowerCase()];
|
|
19
20
|
requireThat(type, 'unsupported_file', 'This file format is not supported. Use JPEG, PNG, GIF, WebP, supported audio, MP4, MOV or WebM.');
|
|
21
|
+
await localFile(() => fs.access(full, constants.R_OK), { file: full });
|
|
20
22
|
const prepared = await mcp.call('prepare_upload', { file_name: path.basename(full), ...(upload_path ? { upload_path } : {}) });
|
|
21
23
|
requireThat(stat.size <= prepared.max_bytes, 'file_too_large', 'This file exceeds the upload limit.');
|
|
22
24
|
const destination = new URL(prepared.upload_url);
|
|
@@ -44,24 +46,40 @@ export async function upload(file, { mcp, state, server, signal, upload_path, fe
|
|
|
44
46
|
}
|
|
45
47
|
|
|
46
48
|
export async function download(taskId, output, { mcp, server, index = 1, signal, maxBytes = 1024 ** 3, fetchFn }) {
|
|
49
|
+
const target = path.resolve(output);
|
|
50
|
+
const parent = await localFile(() => fs.stat(path.dirname(target)), { file: target, missing: 'output_directory_missing' });
|
|
51
|
+
requireThat(parent.isDirectory(), 'path_not_directory', 'The output parent is not a directory. Choose a valid file path.');
|
|
52
|
+
await localFile(() => fs.access(path.dirname(target), constants.W_OK), { file: target });
|
|
53
|
+
try { await fs.lstat(target); throw new CliError('file_exists', 'The output file already exists. Choose another path.'); }
|
|
54
|
+
catch (e) { if (e.code !== 'ENOENT') throw fileError(e, { file: target }); }
|
|
47
55
|
const task = await mcp.call('get_task', { task_id: taskId, wait_seconds: 0 });
|
|
48
56
|
requireThat(task.status === 'completed', 'task_not_ready', 'Wait for the task to complete before downloading.');
|
|
49
57
|
const result = task.results?.[index - 1];
|
|
50
58
|
requireThat(Number.isInteger(index) && index > 0 && result?.url, 'result_not_found', 'The requested result index does not exist.');
|
|
51
|
-
const target = path.resolve(output);
|
|
52
59
|
const temp = `${target}.${randomUUID()}.part`;
|
|
53
60
|
let bytes = 0;
|
|
61
|
+
let prefix = Buffer.alloc(0), inspected = false, contentType;
|
|
54
62
|
const digest = createHash('sha256');
|
|
55
63
|
const guard = new Transform({ transform(chunk, encoding, callback) {
|
|
56
64
|
bytes += chunk.length;
|
|
57
65
|
if (bytes > maxBytes) { callback(new CliError('download_too_large', 'The download exceeded the size limit.')); return; }
|
|
66
|
+
if (!inspected) {
|
|
67
|
+
prefix = Buffer.concat([prefix, chunk.subarray(0, 512 - prefix.length)]);
|
|
68
|
+
if (prefix.length === 512) {
|
|
69
|
+
try { checkMediaPrefix(prefix, result.kind, contentType); inspected = true; }
|
|
70
|
+
catch (error) { callback(error); return; }
|
|
71
|
+
}
|
|
72
|
+
}
|
|
58
73
|
digest.update(chunk); callback(null, chunk);
|
|
74
|
+
}, flush(callback) {
|
|
75
|
+
try { if (!inspected && bytes > 0) checkMediaPrefix(prefix, result.kind, contentType); callback(); }
|
|
76
|
+
catch (error) { callback(error); }
|
|
59
77
|
} });
|
|
60
78
|
const timeoutSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(600_000)]) : AbortSignal.timeout(600_000);
|
|
61
79
|
try {
|
|
62
|
-
try { await fs.access(target); throw new CliError('file_exists', 'The output file already exists. Choose another path.'); }
|
|
63
|
-
catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
64
80
|
const response = await resultFetch(result.url, { testOrigin: loopback(server) ? server.origin : undefined, signal: timeoutSignal, fetchFn });
|
|
81
|
+
try { contentType = checkContentType(response.headers.get('content-type'), result.kind); }
|
|
82
|
+
catch (error) { await response.body?.cancel(); throw error; }
|
|
65
83
|
const length = Number(response.headers.get('content-length'));
|
|
66
84
|
if (Number.isFinite(length) && length > maxBytes) {
|
|
67
85
|
await response.body?.cancel();
|
|
@@ -72,5 +90,6 @@ export async function download(taskId, output, { mcp, server, index = 1, signal,
|
|
|
72
90
|
requireThat(bytes > 0, 'download_failed', 'The file service returned an empty file.');
|
|
73
91
|
await fs.link(temp, target);
|
|
74
92
|
return { task_id: taskId, result_index: index, path: target, size_bytes: bytes, sha256: digest.digest('hex'), kind: result.kind };
|
|
75
|
-
}
|
|
93
|
+
} catch (error) { throw fileError(error, { file: target, missing: 'output_directory_missing' }); }
|
|
94
|
+
finally { await fs.unlink(temp).catch(() => {}); }
|
|
76
95
|
}
|