@evolinkai/cli 0.11.0 → 0.13.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 +6 -3
- package/package.json +2 -2
- package/skills/evolink-cli/SKILL.md +5 -3
- package/skills/evolink-cli/references/usage-and-budget.md +3 -1
- package/src/api.mjs +7 -6
- package/src/auth.mjs +14 -3
- package/src/cli.mjs +21 -6
- package/src/media.mjs +149 -16
- package/src/platform/core/src/data/model-constraints.js +9 -0
- package/src/platform/core/src/data/model-params.overrides.generated.js +1 -1
- package/src/platform/core/src/platform-operations.js +1 -1
- package/src/platform/core/src/services/api-client.js +56 -18
- package/src/platform/core/src/services/catalog-client.js +28 -2
- package/src/platform/core/src/services/http-policy.js +39 -11
- package/src/platform/core/src/services/mj-prompt.js +18 -0
- package/src/platform/core/src/services/model-capabilities.js +2 -1
- package/src/platform/core/src/services/pricing-call-limit.js +40 -0
- package/src/platform/core/src/services/pricing-derived.js +59 -0
- package/src/platform/core/src/services/pricing-quote-client.js +30 -7
- package/src/platform/core/src/services/pricing-rules-client.js +38 -3
- package/src/platform/core/src/services/pricing-rules-estimate.js +128 -10
- package/src/platform/core/src/tools/estimate-cost.js +26 -10
- package/src/platform/core/src/tools/generate.js +27 -12
- package/src/platform/core/src/tools/get-model.js +16 -0
- package/src/platform/core/src/tools/get-pricing-rules.js +13 -4
- package/src/platform/core/src/tools/get-task.js +37 -13
- package/src/platform/core/src/tools/list-tasks.js +47 -10
- package/src/platform/core/src/tools/search-models.js +4 -1
- package/src/platform/core/src/tools/shared.js +15 -1
- package/src/platform/core/src/tools/task-format.js +58 -9
- package/src/platform/core/src/version.js +1 -1
- package/src/platform/source.json +51 -45
- package/src/state.mjs +12 -1
package/README.md
CHANGED
|
@@ -260,9 +260,9 @@ See [Gemini trusted folders](https://geminicli.com/docs/cli/trusted-folders/) an
|
|
|
260
260
|
|
|
261
261
|
Generation errors preserve the saved quote and request ID when acceptance or charging is uncertain. `charged: no` alone does not authorize a new request: `submission_state` must also establish `not_submitted` or `rejected`. Recover uncertain submissions with the original quote, and query a known task. A new generation needs a fresh estimate and user approval.
|
|
262
262
|
|
|
263
|
-
Task queries verify the requested ID and the public states `pending`, `processing`, `completed`, `failed`, `cancelled`. Invalid bodies, mismatched IDs and unknown states return `task_response_invalid`, `task_identity_mismatch` or `task_status_unknown`, with the original task ID and `status_check: unverified`. Retry the free query; this does not establish task failure, a zero charge or a refund. Accepted submissions retain their ID even if a follow-up query fails; resume queries that ID without creating another task. Optional fields vary by model: missing progress or costs are not zero, and completed voice/persona tasks may return reusable identifiers without download links. Invalid optional fields are omitted with `response_warnings`.
|
|
263
|
+
Task queries verify the requested ID and the public states `pending`, `processing`, `completed`, `failed`, `cancelled`. Invalid bodies, mismatched IDs and unknown states return `task_response_invalid`, `task_identity_mismatch` or `task_status_unknown`, with the original task ID and `status_check: unverified`. Retry the free query; this does not establish task failure, a zero charge or a refund. `tasks wait --timeout` is one limit for every read, retry and pause: at the limit it exits with `wait_timeout`, the task ID, the last verified status and its `read_at` (or `status_check: unverified` when the latest status could not be read), and the task keeps running. `tasks get` reads once without waiting; that read can still take up to 15 s. Accepted submissions retain their ID even if a follow-up query fails; resume queries that ID without creating another task. Optional fields vary by model: missing progress or costs are not zero, and completed voice/persona tasks may return reusable identifiers without download links. Invalid optional fields are omitted with `response_warnings`.
|
|
264
264
|
|
|
265
|
-
`tasks batch` retains independently verified tasks and marks `partial`, `missing` and `issues` when other rows are absent, invalid or duplicated. `tasks list` keeps the verified base page if detail enrichment fails, marking `details_missing` and affected rows with `details_available: false`. An unavailable detail is not proof that the task never existed. Follow `next_page` and query the original missing IDs; do not interpret partial results as a complete usage total or regenerate to repair a read.
|
|
265
|
+
`tasks batch` retains independently verified tasks and marks `partial`, `missing` and `issues` when other rows are absent, invalid or duplicated. `tasks list` keeps the verified base page if detail enrichment fails, marking `details_missing` and affected rows with `details_available: false` and a `details_reason` (`read_failed`, `invalid` or `not_returned`); `details_status` summarizes the read. Retry `details_retry_task_ids` with `tasks batch --ids` (free) and check `not_returned` rows with `tasks get`. `last_page` names the last page; an empty page past it is not an empty account. An unavailable detail is not proof that the task never existed. Follow `next_page` and query the original missing IDs; do not interpret partial results as a complete usage total or regenerate to repair a read.
|
|
266
266
|
|
|
267
267
|
Customer-facing notices, link labels and related guidance default to English unless the user explicitly requests another language. For uncertain task status, missing results, execution failure or incomplete lists, use the returned `dashboard_url` and English `dashboard_guidance`: [Open EvoLink Dashboard](https://evolink.ai/dashboard). Sign in with the same EvoLink account and keep the original task ID; this link does not establish task completion, charges or refunds.
|
|
268
268
|
|
|
@@ -280,7 +280,10 @@ shared MCP key, quota and permissions remain.
|
|
|
280
280
|
|
|
281
281
|
Use `evolink estimate --refresh-quote ID` for an unsubmitted approval. It preserves
|
|
282
282
|
input and an explicit user budget, creates a new local approval and requires user
|
|
283
|
-
confirmation again.
|
|
283
|
+
confirmation again. The new quote replaces the old one, which can no longer be
|
|
284
|
+
submitted (`quote_superseded` names the current quote), and keeps its request ID;
|
|
285
|
+
if a submission or another refresh finishes first, no new quote is saved.
|
|
286
|
+
Unknown recovery keeps the original input and request ID;
|
|
284
287
|
a failed replay cannot prove the first submission was free. Known tasks remain
|
|
285
288
|
readable after expiry; check the original task before preparing another request.
|
|
286
289
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@evolinkai/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.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",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@napi-rs/keyring": "2.1.0",
|
|
36
|
-
"zod": "
|
|
36
|
+
"zod": "4.6.7"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@modelcontextprotocol/sdk": "1.32.1"
|
|
@@ -76,7 +76,7 @@ The saved model and input are the submitted model and input. A changed or expire
|
|
|
76
76
|
- 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.
|
|
77
77
|
- `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.
|
|
78
78
|
- 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 selected page, not the entire history. Use `--page` and follow `next_page`; `--model` and `--until` narrow results. `total` is before time filtering. 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.
|
|
79
|
-
- Poll with `tasks get TASK_ID --json` or `tasks wait TASK_ID --json`. Never poll with `generate`. Ctrl-C
|
|
79
|
+
- Poll with `tasks get TASK_ID --json` or `tasks wait TASK_ID --json`. Never poll with `generate`. Ctrl-C and the `tasks wait --timeout` limit stop only local waiting; they do not cancel the paid task. A `wait_timeout` error reports `status_check`: `verified` gives the last read `last_status` and its `read_at`, not a live status; `unverified` means the latest status could not be read. Continue with the returned `recovery` command, never with a new generation.
|
|
80
80
|
- 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.
|
|
81
81
|
- For several original results, read [Discovery and delivery extensions](references/capabilities.md), then use `download TASK_ID --all --output-dir DIR --json`. Partial delivery is a command error even though generation completed. Resume only downloads with the same task/directory/template and `--resume`; verify saved files and never generate again to repair delivery.
|
|
82
82
|
- When the user asks for spending or usage, read [Usage and budget boundaries](references/usage-and-budget.md). Task summaries are not invoices or refund ledgers; missing costs and incomplete coverage must remain visible. An estimate guard is not a final settlement cap.
|
|
@@ -87,7 +87,7 @@ Use `generate` for the first submission of an approved quote. `tasks resume` is
|
|
|
87
87
|
|
|
88
88
|
Use `--json` for commands consumed by the assistant. Progress is on stderr; stdout is one JSON envelope with `schema_version: 1`. `ok: false` and a nonzero exit code indicate a command error; a successful task query reporting `status: failed` is a task outcome, not a failed CLI invocation. Tell the user its `error.code` and `error.message` (EvoLink's explanation). A failed task is not charged; the credits reserved at submission are returned automatically (`billing_note`). Read the error's recovery details before retrying. For `invalid_status`, use `error.details.allowed_values` and correct only the free query; local status validation occurs before a platform request. Never guess an enum, interpret an empty list as a service failure, or resubmit a paid task to fix a query error. Run `evolink --help` for the maintained command reference and `evolink tasks list --help` for task filters.
|
|
89
89
|
|
|
90
|
-
For `task_response_invalid`, `task_identity_mismatch`, `task_status_unknown` or `status_check: unverified`, keep the original task and request IDs. Tell the user the latest state could not be verified; retry only the free query. This is not evidence of failed generation, no charge or a completed refund. `submission_state: accepted` proves a task was accepted even when status is unavailable; use `tasks get` or the saved quote's `tasks resume`, never a new generation. Missing optional progress or costs are not zero; inspect `response_warnings`. Completed resource tasks may return reusable voice/persona IDs instead of result links. For `partial: true`, retain verified tasks and the base page, disclose missing coverage, and query `missing` or `details_missing` original IDs
|
|
90
|
+
For `task_response_invalid`, `task_identity_mismatch`, `task_status_unknown`, `task_query_timeout` or `status_check: unverified`, keep the original task and request IDs. Tell the user the latest state could not be verified; retry only the free query. This is not evidence of failed generation, no charge or a completed refund. `submission_state: accepted` proves a task was accepted even when status is unavailable; use `tasks get` or the saved quote's `tasks resume`, never a new generation. Missing optional progress or costs are not zero; inspect `response_warnings`. Completed resource tasks may return reusable voice/persona IDs instead of result links. For `partial: true`, retain verified tasks and the base page, disclose missing coverage, and query `missing` or `details_missing` original IDs: retry `details_retry_task_ids` with `tasks batch --ids`, and check rows whose `details_reason` is `not_returned` with `tasks get`. Never use incomplete results as a full usage total.
|
|
91
91
|
|
|
92
92
|
For setup problems, run `evolink doctor --agent NAME --json` if the installed version supports the agent option; otherwise use `doctor --json`. Read every failed or skipped check and every `guidance` entry; without `--agent`, outdated or modified skill copies appear in `guidance` and `skills` without failing the check. On Linux, login and later commands need the same unlocked Secret Service/D-Bus session. On SSH hosts, opening the link on another computer requires forwarding the loopback callback port; `--no-browser` does not solve callback routing. Report connection, model discovery and assistant skill discovery separately.
|
|
93
93
|
|
|
@@ -95,7 +95,9 @@ For setup problems, run `evolink doctor --agent NAME --json` if the installed ve
|
|
|
95
95
|
Estimates use published full pricing rules and show public default prices, excluding
|
|
96
96
|
personal discounts. Local approvals last up to 30 minutes; submission verifies fresh rules.
|
|
97
97
|
Use `evolink estimate --refresh-quote ID` only for an unsubmitted approval; preserve
|
|
98
|
-
the input and explicit user budget and obtain approval again.
|
|
98
|
+
the input and explicit user budget and obtain approval again. The refreshed quote
|
|
99
|
+
replaces the old one and keeps its request ID: submit only the newest quote, which
|
|
100
|
+
`quote_superseded` names. Supply missing billing
|
|
99
101
|
usage with `--pricing-parameters JSON`; never invent unknown token counts or media
|
|
100
102
|
lengths. Partial subtotals cannot check a budget. If rules are unavailable or change,
|
|
101
103
|
pause and preserve the budget. Actual usage can change the final charge; final
|
|
@@ -20,7 +20,9 @@ A final task/workflow cap requires server-side reservation and settlement enforc
|
|
|
20
20
|
Estimates use published full pricing rules and show public default prices, excluding
|
|
21
21
|
personal discounts. Local approvals last up to 30 minutes; submission verifies fresh rules.
|
|
22
22
|
Use `evolink estimate --refresh-quote ID` only for an unsubmitted approval; preserve
|
|
23
|
-
the input and explicit user budget and obtain approval again.
|
|
23
|
+
the input and explicit user budget and obtain approval again. The refreshed quote
|
|
24
|
+
replaces the old one and keeps its request ID: submit only the newest quote, which
|
|
25
|
+
`quote_superseded` names. Supply missing billing
|
|
24
26
|
usage with `--pricing-parameters JSON`; never invent unknown token counts or media
|
|
25
27
|
lengths. Partial subtotals cannot check a budget. If rules are unavailable or change,
|
|
26
28
|
pause and preserve the budget. Actual usage can change the final charge; final
|
package/src/api.mjs
CHANGED
|
@@ -22,13 +22,14 @@ export class Api {
|
|
|
22
22
|
return fetchFn(input, { ...options, redirect: 'error', credentials: 'omit' });
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
|
-
context(access, name) {
|
|
25
|
+
context(access, name, deadline) {
|
|
26
26
|
// linkCampaign: site links the CLI shows are tagged utm_campaign=cli, not as the local MCP package.
|
|
27
|
+
// deadline (performance.now() ms): the local wait's own limit, which shared task reads never run past.
|
|
27
28
|
return { serviceChannel: { accessToken: access.access_token }, clientName: 'EvoLink CLI', linkCampaign: 'cli',
|
|
28
29
|
http: { fetch: this.fetchFn, signal: this.signal, userAgent: USER_AGENT, client: 'cli', version: CLI_VERSION,
|
|
29
|
-
controlBaseUrl: this.apiUrl.origin, filesBaseUrl: this.filesUrl.origin } };
|
|
30
|
+
controlBaseUrl: this.apiUrl.origin, filesBaseUrl: this.filesUrl.origin, ...(deadline !== undefined ? { deadline } : {}) } };
|
|
30
31
|
}
|
|
31
|
-
async call(name, args = {}, { requireCapability = false, requiredInputs = [] } = {}) {
|
|
32
|
+
async call(name, args = {}, { requireCapability = false, requiredInputs = [], deadline } = {}) {
|
|
32
33
|
if (requireCapability) requireThat(this.platform.supports(name, requiredInputs),
|
|
33
34
|
'capability_unavailable', 'This CLI does not contain the requested platform capability. Update the CLI; no request was sent.',
|
|
34
35
|
{ tool: name, required_inputs: requiredInputs, request_sent: false });
|
|
@@ -46,13 +47,13 @@ export class Api {
|
|
|
46
47
|
return { ...data, text };
|
|
47
48
|
}
|
|
48
49
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
49
|
-
const access = await this.credentials.access(attempt > 0);
|
|
50
|
-
const result = await this.platform.call(name, args, this.context(access, name));
|
|
50
|
+
const access = await this.credentials.access(attempt > 0, { deadline });
|
|
51
|
+
const result = await this.platform.call(name, args, this.context(access, name, deadline));
|
|
51
52
|
const data = result.structuredContent;
|
|
52
53
|
const text = (result.content ?? []).filter(item => item.type === 'text').map(item => item.text).join('\n');
|
|
53
54
|
if (result.isError || data?.ok === false) {
|
|
54
55
|
if (attempt === 0 && data?.error?.status === 401 && data?.charged !== 'unknown') continue;
|
|
55
|
-
const taskReadCode = ['task_response_invalid', 'task_identity_mismatch', 'task_status_unknown'].includes(data?.error?.code) ? data.error.code : undefined;
|
|
56
|
+
const taskReadCode = ['task_response_invalid', 'task_identity_mismatch', 'task_status_unknown', 'task_query_timeout'].includes(data?.error?.code) ? data.error.code : undefined;
|
|
56
57
|
throw new CliError(this.signal?.aborted ? 'interrupted' : taskReadCode || data?.error?.category || 'api_failed',
|
|
57
58
|
safeMessage(data?.error?.message || text || 'The EvoLink request was refused.'), { ...data, text: safeMessage(text) }, this.signal?.aborted ? 130 : 1);
|
|
58
59
|
}
|
package/src/auth.mjs
CHANGED
|
@@ -7,6 +7,9 @@ import { hash } from './state.mjs';
|
|
|
7
7
|
import { authFetch, ISSUER, SERVER, SITE } from './network.mjs';
|
|
8
8
|
import { CliError, requireThat } from './errors.mjs';
|
|
9
9
|
|
|
10
|
+
/** A local wait with less time left than this does not start a token renewal. */
|
|
11
|
+
export const REFRESH_MIN_MS = 3_000;
|
|
12
|
+
|
|
10
13
|
export class Vault {
|
|
11
14
|
constructor(server, state) { this.account = hash({ server: server.href, home: state.home }); }
|
|
12
15
|
async entry() {
|
|
@@ -143,7 +146,7 @@ export class Credentials {
|
|
|
143
146
|
}
|
|
144
147
|
lock(fn) { return this.state.lock(`auth-${hash(this.server.href)}`, fn); }
|
|
145
148
|
provider() { return new OAuthProvider({ server: this.server, state: this.state, vault: this.vault, redirectUrl: 'http://127.0.0.1:1/oauth/callback' }); }
|
|
146
|
-
async access(force = false) {
|
|
149
|
+
async access(force = false, { deadline } = {}) {
|
|
147
150
|
if (this.token) {
|
|
148
151
|
// The hash binds quotes to this temporary credential without writing it to disk.
|
|
149
152
|
return { access_token: this.token, binding: hash(this.token) };
|
|
@@ -152,8 +155,16 @@ export class Credentials {
|
|
|
152
155
|
let saved = await this.vault.read();
|
|
153
156
|
requireThat(saved?.tokens, 'login_required', 'Run evolink auth login.');
|
|
154
157
|
if (force || saved.expires_at <= Date.now() + 60_000) {
|
|
155
|
-
|
|
156
|
-
|
|
158
|
+
// Near a wait's deadline, a token still valid past it is used as is, and a renewal that could not
|
|
159
|
+
// finish in time is not started. A renewal that has started is never cut short: its new token must be saved.
|
|
160
|
+
const left = deadline === undefined ? Infinity : Math.max(0, deadline - performance.now());
|
|
161
|
+
const coversWait = !force && Number.isFinite(left) && saved.expires_at > Date.now() + left + 1_000;
|
|
162
|
+
if (!coversWait) {
|
|
163
|
+
if (left < REFRESH_MIN_MS) throw new CliError('wait_deadline_reached',
|
|
164
|
+
'The wait limit was reached before the login could be renewed. Stopping this wait does not cancel the task.');
|
|
165
|
+
await refresh(this.provider(), this.fetchFn);
|
|
166
|
+
saved = await this.vault.read();
|
|
167
|
+
}
|
|
157
168
|
}
|
|
158
169
|
const issuer = this.server.href === SERVER ? ISSUER : this.server.origin;
|
|
159
170
|
requireThat(saved?.tokens?.issuer === issuer && saved.tokens.access_token, 'login_required', 'This login belongs to a different service. Run auth login.');
|
package/src/cli.mjs
CHANGED
|
@@ -204,7 +204,7 @@ async function estimateArgs(options) {
|
|
|
204
204
|
return { model: options.model, input, ...(pricingParameters !== undefined ? { pricing_parameters: pricingParameters } : {}), ...(options['pricing-source'] ? { pricing_source: options['pricing-source'] } : {}), ...(media !== undefined ? { media_seconds: media } : {}), ...(cap !== undefined ? { max_cost_usd: cap } : {}) };
|
|
205
205
|
}
|
|
206
206
|
|
|
207
|
-
export async function dispatch(positionals, options, { state, server, credentials, client, mcp = client, signal, progress, skillHome, updates }) {
|
|
207
|
+
export async function dispatch(positionals, options, { state, server, credentials, client, mcp = client, signal, progress, skillHome, updates, budget }) {
|
|
208
208
|
// login, setup and doctor always ask the registry and report the outcome, including a disabled check;
|
|
209
209
|
// loopback test resources never contact it.
|
|
210
210
|
const update = () => checkForUpdate({ state, server, force: true, signal, ...updates });
|
|
@@ -254,14 +254,14 @@ export async function dispatch(positionals, options, { state, server, credential
|
|
|
254
254
|
requireThat(!['model', 'input', 'input-file', 'prompt', 'max-cost-usd', 'media-seconds'].some(k => options[k] !== undefined), 'quote_changed', 'Generation uses the saved quote. Change inputs by preparing a new estimate.');
|
|
255
255
|
const result = await media.generate(action, options.quote, { confirmed: options.confirm });
|
|
256
256
|
if (options.wait && result.task_id && result.status !== 'completed') {
|
|
257
|
-
const task = await media.wait(result.task_id, { timeout: number(options.timeout, 'timeout', 1, 86400, true) || 1800, signal, progress });
|
|
257
|
+
const task = await media.wait(result.task_id, { timeout: number(options.timeout, 'timeout', 1, 86400, true) || 1800, signal, progress, budget });
|
|
258
258
|
return { ...task, quote_id: options.quote, client_request_id: result.client_request_id };
|
|
259
259
|
}
|
|
260
260
|
return result;
|
|
261
261
|
}
|
|
262
262
|
if (command === 'tasks') {
|
|
263
263
|
if (action === 'get' && id) return client.call('get_task', { task_id: id, wait_seconds: 0 });
|
|
264
|
-
if (action === 'wait' && id) return media.wait(id, { timeout: number(options.timeout, 'timeout', 1, 86400, true) || 1800, signal, progress });
|
|
264
|
+
if (action === 'wait' && id) return media.wait(id, { timeout: number(options.timeout, 'timeout', 1, 86400, true) || 1800, signal, progress, budget });
|
|
265
265
|
if (action === 'resume' && options.quote) return media.resume(options.quote);
|
|
266
266
|
if (action === 'batch') return client.call('list_tasks', { task_ids: taskIds(options.ids) });
|
|
267
267
|
if (action === 'list') {
|
|
@@ -306,6 +306,15 @@ async function stdinToken(stream) {
|
|
|
306
306
|
return token;
|
|
307
307
|
}
|
|
308
308
|
|
|
309
|
+
/** Resolves with the promise's value, or undefined once the deadline (performance.now() ms) passes. */
|
|
310
|
+
export async function beforeDeadline(promise, deadline) {
|
|
311
|
+
const left = deadline - performance.now();
|
|
312
|
+
if (left <= 0) return undefined;
|
|
313
|
+
let timer;
|
|
314
|
+
try { return await Promise.race([promise, new Promise(resolve => { timer = setTimeout(resolve, left); })]); }
|
|
315
|
+
finally { clearTimeout(timer); }
|
|
316
|
+
}
|
|
317
|
+
|
|
309
318
|
export async function main(argv = process.argv.slice(2), io = { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin },
|
|
310
319
|
{ env = process.env, fetchFn, now, timeout, updateState } = {}) {
|
|
311
320
|
let options = { json: argv.includes('--json') };
|
|
@@ -315,10 +324,14 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
|
|
|
315
324
|
process.once('SIGTERM', interrupt);
|
|
316
325
|
// The update notice follows the command's own output on stderr; stdout stays one envelope.
|
|
317
326
|
let update;
|
|
327
|
+
const budget = {};
|
|
328
|
+
// Ctrl-C stops the update check; so does a local wait that reached its limit, so the process can exit at once.
|
|
329
|
+
const updateCheck = new AbortController();
|
|
330
|
+
controller.signal.addEventListener('abort', () => updateCheck.abort(), { once: true });
|
|
318
331
|
const updates = { env, fetchFn, now, timeout };
|
|
319
332
|
const checkUpdate = server => {
|
|
320
333
|
// Building the state path can throw (for example without a home directory); that never fails the command.
|
|
321
|
-
update = Promise.resolve().then(() => updateNotice({ state: updateState || new State(), server, signal:
|
|
334
|
+
update = Promise.resolve().then(() => updateNotice({ state: updateState || new State(), server, signal: updateCheck.signal, ...updates }))
|
|
322
335
|
.catch(() => undefined);
|
|
323
336
|
};
|
|
324
337
|
try {
|
|
@@ -342,7 +355,7 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
|
|
|
342
355
|
const client = new Api(credentials, { signal: controller.signal, apiUrl: options['api-url'], filesUrl: options['files-url'] });
|
|
343
356
|
// Only a fully validated command checks: invalid tokens and service URLs fail without contacting npm.
|
|
344
357
|
if (!NO_UPDATE_NOTICE.has(positionals[0]) && !NO_UPDATE_NOTICE.has(positionals.slice(0, 2).join(' '))) checkUpdate(server);
|
|
345
|
-
const result = publicView(await dispatch(positionals, options, { state, server, credentials, client, signal: controller.signal, progress: message => io.stderr.write(message + '\n'), updates }));
|
|
358
|
+
const result = publicView(await dispatch(positionals, options, { state, server, credentials, client, signal: controller.signal, progress: message => io.stderr.write(message + '\n'), updates, budget }));
|
|
346
359
|
const view = { schema_version: 1, ...result, ok: result.ok !== false };
|
|
347
360
|
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` : ''}`);
|
|
348
361
|
if (!view.ok) process.exitCode = view.error?.code === 'interrupted' ? 130 : 1;
|
|
@@ -352,7 +365,9 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
|
|
|
352
365
|
process.exitCode = error.exitCode || (controller.signal.aborted ? 130 : 1);
|
|
353
366
|
} finally {
|
|
354
367
|
// Ctrl-C while the check finishes stops the check, not the completed command.
|
|
355
|
-
|
|
368
|
+
// A local wait that reached its limit does not wait longer for the optional update notice.
|
|
369
|
+
const notice = budget.deadline === undefined ? await update : await beforeDeadline(update, budget.deadline);
|
|
370
|
+
if (budget.deadline !== undefined && notice === undefined) updateCheck.abort();
|
|
356
371
|
process.removeListener('SIGINT', interrupt); process.removeListener('SIGTERM', interrupt);
|
|
357
372
|
if (notice && !controller.signal.aborted) io.stderr.write(notice + '\n');
|
|
358
373
|
}
|
package/src/media.mjs
CHANGED
|
@@ -4,6 +4,41 @@ import { CliError, requireThat, fileError } from './errors.mjs';
|
|
|
4
4
|
import { APPROVAL_TTL_MS, rulesBudgetExceeded } from './platform/core/src/services/pricing-rules-estimate.js';
|
|
5
5
|
import { compareDecimal } from './platform/core/src/services/pricing-quote-client.js';
|
|
6
6
|
import { DASHBOARD_URL } from './platform/core/src/services/http-policy.js';
|
|
7
|
+
import { dashboardCheck } from './platform/core/src/tools/shared.js';
|
|
8
|
+
import { NEXT_READ_MIN_MS, pollIntervalMs } from './platform/core/src/tools/task-format.js';
|
|
9
|
+
|
|
10
|
+
/** Longest single get_task round inside a local wait; each round shares the wait's one deadline. */
|
|
11
|
+
const WAIT_ROUND_SECONDS = 30;
|
|
12
|
+
const ROUND_PAUSE_MS = 500;
|
|
13
|
+
/** The first round starts with at least this much of the wait left; a later round needs the shared core's NEXT_READ_MIN_MS. */
|
|
14
|
+
const MIN_ROUND_MS = 300;
|
|
15
|
+
/** Drift ignored when the time left becomes whole seconds; the shared core still ends each round at the deadline. */
|
|
16
|
+
const ROUND_DRIFT_MS = 50;
|
|
17
|
+
const WAIT_STOPS_LOCAL = 'Stopping does not cancel the task.';
|
|
18
|
+
|
|
19
|
+
function interrupted(taskId) {
|
|
20
|
+
return new CliError('interrupted', 'Stopped waiting locally. The EvoLink task continues.', { task_id: taskId }, 130);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** At the local limit, report what was last verified instead of claiming the task is still running. */
|
|
24
|
+
function waitTimeout(taskId, last) {
|
|
25
|
+
const verified = last?.status_check === 'verified' && last.status;
|
|
26
|
+
return new CliError('wait_timeout', verified
|
|
27
|
+
? `Stopped waiting at the timeout. ${WAIT_STOPS_LOCAL} Last verified status: ${last.status}${last.read_at ? ` (read at ${last.read_at})` : ''}. Continue with evolink tasks wait ${taskId}.`
|
|
28
|
+
: `Stopped waiting at the timeout. ${WAIT_STOPS_LOCAL} Its latest status could not be verified${last?.status ? ` (last verified: ${last.status})` : ''}. Query it with evolink tasks get ${taskId}.`,
|
|
29
|
+
{ task_id: taskId, status_check: verified ? 'verified' : 'unverified',
|
|
30
|
+
...(last?.status ? { last_status: last.status } : {}), ...(last?.read_at ? { read_at: last.read_at } : {}),
|
|
31
|
+
...(verified ? {} : dashboardCheck()), recovery: `evolink tasks wait ${taskId}` });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function pause(ms, signal) {
|
|
35
|
+
return new Promise(resolve => {
|
|
36
|
+
const timer = setTimeout(done, Math.max(0, ms));
|
|
37
|
+
function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); }
|
|
38
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
39
|
+
if (signal?.aborted) done();
|
|
40
|
+
});
|
|
41
|
+
}
|
|
7
42
|
|
|
8
43
|
function quoteError(error, cap) {
|
|
9
44
|
const cause = fileError(error);
|
|
@@ -47,12 +82,24 @@ export function checkEstimate(quote, cap) {
|
|
|
47
82
|
: quote.estimate.max_usd <= cap;
|
|
48
83
|
requireThat(withinBudget, 'cost_exceeds_cap', 'The estimated cost exceeds max-cost-usd.', { estimate: quote.estimate, max_cost_usd: cap });
|
|
49
84
|
}
|
|
85
|
+
// The core names each missing usage in MCP terms; say once how they map to CLI options.
|
|
86
|
+
requireThat(quote.estimate?.status !== 'needs_input' || !quote.estimate.usage_help?.length, 'estimate_unavailable', [
|
|
87
|
+
'The total cannot be estimated yet, so no quote was saved. It depends on:', ...(quote.estimate?.usage_help ?? []).map(line => `- ${line}`),
|
|
88
|
+
'In the CLI, media_seconds is --media-seconds and pricing_parameters is --pricing-parameters (a JSON object).'].join('\n'),
|
|
89
|
+
// A copy: the redaction of error details shows an object it has already printed as "[truncated]".
|
|
90
|
+
{ estimate: quote.estimate, missing_usage: [...(quote.estimate?.missing_usage ?? [])] });
|
|
50
91
|
requireThat(['estimated', 'partial', 'token_billed'].includes(quote.estimate?.status), 'estimate_unavailable', 'Complete the estimate input or choose a model with pricing before submission.', { estimate: quote.estimate });
|
|
51
92
|
}
|
|
52
93
|
|
|
53
94
|
export class Media {
|
|
54
95
|
constructor({ client, mcp = client, state, server, now = Date.now }) { this.client = mcp; this.state = state; this.server = server.href; this.now = now; }
|
|
55
96
|
async estimate(args) {
|
|
97
|
+
const { stored, view } = await this.prepareQuote(args);
|
|
98
|
+
await this.state.write('quotes', stored.id, stored);
|
|
99
|
+
return view;
|
|
100
|
+
}
|
|
101
|
+
/** Obtains and checks an estimate and builds its quote record; nothing is saved. */
|
|
102
|
+
async prepareQuote(args) {
|
|
56
103
|
const { max_cost_usd, ...input } = args;
|
|
57
104
|
let quote;
|
|
58
105
|
try {
|
|
@@ -74,16 +121,69 @@ export class Media {
|
|
|
74
121
|
...(quote.effective_input ? { effective_input: quote.effective_input, defaults_applied: quote.defaults_applied } : {}),
|
|
75
122
|
created_at: this.now(), expires_at: expires, ...(quote.account_quote ? { backend_estimate_id: quote.account_quote.quote.estimate_id,
|
|
76
123
|
server_expires_at: serverExpiry, account_quote: quote.account_quote } : {}), state: 'quoted', client_request_id: `cli-${randomUUID()}` };
|
|
77
|
-
|
|
78
|
-
return { ...quote, quote_id: id, input: input.input || {}, ...(max_cost_usd !== undefined ? { max_cost_usd, cap_source: 'user' } : {}), expires_at: new Date(stored.expires_at).toISOString(),
|
|
124
|
+
const view = { ...quote, quote_id: id, input: input.input || {}, ...(max_cost_usd !== undefined ? { max_cost_usd, cap_source: 'user' } : {}), expires_at: new Date(stored.expires_at).toISOString(),
|
|
79
125
|
requires_confirmation: true, next_step: `After the user approves, run evolink generate ${quote.type} --quote ${id} --confirm.` };
|
|
126
|
+
return { stored, view };
|
|
80
127
|
}
|
|
128
|
+
/**
|
|
129
|
+
* One generation per estimate. A refresh gives it a new quote but keeps its request ID, and moves a single pointer
|
|
130
|
+
* (intents/<first quote ID>) to the new quote, which is saved first; only the quote that pointer names can be submitted.
|
|
131
|
+
* A quote never refreshed is its own generation and has no pointer, as in earlier releases.
|
|
132
|
+
*/
|
|
133
|
+
intentOf(quote) { return quote.intent_id ?? quote.id; }
|
|
81
134
|
async refresh(id) {
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
135
|
+
const intentId = this.intentOf(await this.load(id));
|
|
136
|
+
const lock = `quote-${intentId}`;
|
|
137
|
+
// Checked before and again after the estimate, under the lock that submission and recovery share: a submission
|
|
138
|
+
// or another refresh while the estimate ran means no new submittable quote is saved.
|
|
139
|
+
const before = await this.state.lock(lock, () => this.refreshable(intentId));
|
|
140
|
+
const { account_quote, pricing_quote, ...args } = before.args;
|
|
141
|
+
const { stored, view } = await this.prepareQuote(args);
|
|
142
|
+
return this.state.lock(lock, async () => {
|
|
143
|
+
const current = await this.refreshable(intentId);
|
|
144
|
+
requireThat(current.id === before.id, 'quote_refresh_conflict',
|
|
145
|
+
`Another refresh already replaced this quote with quote ${current.id}. Show the user that quote and obtain approval for it.`,
|
|
146
|
+
{ quote_id: id, active_quote_id: current.id, client_request_id: current.client_request_id, submission_allowed: false });
|
|
147
|
+
// Nothing was ever submitted with this request ID, so the refreshed quote keeps it.
|
|
148
|
+
const next = { ...stored, intent_id: intentId, client_request_id: current.client_request_id, refreshed_from: current.id };
|
|
149
|
+
await this.state.write('quotes', next.id, next);
|
|
150
|
+
const intent = await this.state.read('intents', intentId);
|
|
151
|
+
await this.state.write('intents', intentId, { id: intentId, client_request_id: next.client_request_id, active_quote_id: next.id,
|
|
152
|
+
quotes: [...(intent?.quotes ?? [intentId]), next.id], updated_at: this.now() });
|
|
153
|
+
// The pointer above decides; marking the replaced quote only explains it.
|
|
154
|
+
await this.state.write('quotes', current.id, { ...current, state: 'superseded', superseded_by: next.id });
|
|
155
|
+
return { ...view, refreshed_from: id, superseded_quote_id: current.id, client_request_id: next.client_request_id };
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/** The generation's current quote, which must not have started a submission. */
|
|
159
|
+
async refreshable(intentId) {
|
|
160
|
+
const intent = await this.state.read('intents', intentId);
|
|
161
|
+
const active = await this.load(intent?.active_quote_id ?? intentId);
|
|
162
|
+
requireThat(active.state === 'quoted' && !active.task_id, 'submission_already_started',
|
|
163
|
+
'This submission has started. Recover its original task instead of refreshing its quote.', {
|
|
164
|
+
quote_id: active.id, client_request_id: active.client_request_id, submission_allowed: false,
|
|
165
|
+
...(active.task_id ? { task_id: active.task_id, recovery: `evolink tasks get ${active.task_id}` }
|
|
166
|
+
: ['submitting', 'outcome_unknown'].includes(active.state) ? { recovery: `evolink tasks resume --quote ${active.id}` } : {}) });
|
|
167
|
+
return active;
|
|
168
|
+
}
|
|
169
|
+
/** Only the generation's current quote may be submitted or recovered; any other names the current one or its task. */
|
|
170
|
+
async requireActive(quote, kind) {
|
|
171
|
+
const intentId = this.intentOf(quote);
|
|
172
|
+
const intent = await this.state.read('intents', intentId);
|
|
173
|
+
const activeId = intent?.active_quote_id ?? intentId;
|
|
174
|
+
if (activeId === quote.id) return;
|
|
175
|
+
const details = { quote_id: quote.id, active_quote_id: activeId, client_request_id: quote.client_request_id, submission_allowed: false };
|
|
176
|
+
if (!intent) throw new CliError('quote_refresh_incomplete',
|
|
177
|
+
`This refreshed quote was not saved completely and cannot be submitted. Use quote ${activeId} or refresh it again.`, details);
|
|
178
|
+
const active = await this.state.read('quotes', activeId);
|
|
179
|
+
if (active?.task_id) throw new CliError('quote_superseded',
|
|
180
|
+
`This quote was replaced by quote ${activeId}, which was already submitted as task ${active.task_id}. Do not generate again.`,
|
|
181
|
+
{ ...details, task_id: active.task_id, recovery: `evolink tasks get ${active.task_id}` });
|
|
182
|
+
if (['submitting', 'outcome_unknown'].includes(active?.state)) throw new CliError('quote_superseded',
|
|
183
|
+
`This quote was replaced by quote ${activeId}, whose submission is unverified. Recover that quote; do not create a new request.`,
|
|
184
|
+
{ ...details, recovery: `evolink tasks resume --quote ${activeId}` });
|
|
185
|
+
throw new CliError('quote_superseded', `This quote was replaced by quote ${activeId}. Show the user that quote and obtain approval for it.`,
|
|
186
|
+
{ ...details, next_step: `After the user approves, run evolink generate ${kind} --quote ${activeId} --confirm.` });
|
|
87
187
|
}
|
|
88
188
|
async load(id) {
|
|
89
189
|
const quote = await this.state.read('quotes', id);
|
|
@@ -96,10 +196,13 @@ export class Media {
|
|
|
96
196
|
async generate(kind, id, { confirmed = false, resume = false } = {}) {
|
|
97
197
|
requireThat(['image', 'video', 'audio'].includes(kind), 'invalid_type', 'Choose image, video or audio.');
|
|
98
198
|
requireThat(confirmed || resume, 'confirmation_required', 'Show the quote to the user and obtain approval before adding --confirm.');
|
|
99
|
-
|
|
199
|
+
// Submission, recovery and refresh of one generation share its lock; the quote is validated inside it.
|
|
200
|
+
const intentId = this.intentOf((await this.state.read('quotes', id)) ?? { id });
|
|
201
|
+
return this.state.lock(`quote-${intentId}`, async () => {
|
|
100
202
|
const quote = await this.load(id);
|
|
101
203
|
requireThat(quote.type === kind, 'quote_type_mismatch', 'Use the media type shown in the saved quote.');
|
|
102
204
|
if (quote.task_id) return { ...await this.client.call('get_task', { task_id: quote.task_id, wait_seconds: 0 }), quote_id: id, recovered: true };
|
|
205
|
+
await this.requireActive(quote, kind);
|
|
103
206
|
requireThat(quote.state !== 'refused', 'submission_refused',
|
|
104
207
|
'EvoLink refused this submission and reported no charge. Resolve the original error, estimate again with the same budget, and obtain approval for the new quote.',
|
|
105
208
|
{ quote_id: id, client_request_id: quote.client_request_id, charged: 'no', submission_allowed: false });
|
|
@@ -169,21 +272,51 @@ export class Media {
|
|
|
169
272
|
const quote = await this.load(id);
|
|
170
273
|
return this.generate(quote.type, id, { resume: true });
|
|
171
274
|
}
|
|
172
|
-
|
|
173
|
-
|
|
275
|
+
/**
|
|
276
|
+
* Waits locally for one task. A single monotonic deadline bounds every round, read, retry and pause; a round asks
|
|
277
|
+
* only for the whole seconds left. budget.deadline lets the command keep optional work (the update notice) inside it.
|
|
278
|
+
*/
|
|
279
|
+
async wait(taskId, { timeout = 1800, signal, progress = () => {}, budget } = {}) {
|
|
280
|
+
const deadline = performance.now() + timeout * 1000;
|
|
281
|
+
if (budget) budget.deadline = deadline;
|
|
282
|
+
let last, rounds = 0;
|
|
174
283
|
for (;;) {
|
|
175
|
-
if (signal?.aborted) throw
|
|
176
|
-
const
|
|
177
|
-
|
|
284
|
+
if (signal?.aborted) throw interrupted(taskId);
|
|
285
|
+
const left = deadline - performance.now();
|
|
286
|
+
// Too little time for another round: report the last verified state as it is. Like a later read in the shared
|
|
287
|
+
// core, a later round needs time to finish; started with less, it would only turn a verified status unverified.
|
|
288
|
+
if (left < (rounds === 0 ? MIN_ROUND_MS : NEXT_READ_MIN_MS)) throw waitTimeout(taskId, last);
|
|
289
|
+
rounds += 1;
|
|
290
|
+
let task;
|
|
291
|
+
try {
|
|
292
|
+
task = await this.client.call('get_task', { task_id: taskId, wait_seconds: Math.min(WAIT_ROUND_SECONDS, Math.floor((left + ROUND_DRIFT_MS) / 1000)) }, { deadline });
|
|
293
|
+
} catch (error) {
|
|
294
|
+
if (signal?.aborted) throw interrupted(taskId);
|
|
295
|
+
// A round that ran out of time is not a task outcome; continue while the wait itself has time left.
|
|
296
|
+
if (!['task_query_timeout', 'wait_deadline_reached'].includes(error.code)) throw error;
|
|
297
|
+
last = { ...last, status_check: 'unverified' };
|
|
298
|
+
const rest = deadline - performance.now();
|
|
299
|
+
if (rest < NEXT_READ_MIN_MS) throw waitTimeout(taskId, last);
|
|
300
|
+
progress(`${taskId}: latest status unverified${last.status ? ` (last verified: ${last.status})` : ''}`);
|
|
301
|
+
await pause(Math.min(ROUND_PAUSE_MS, rest), signal);
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
178
304
|
if (task.status === 'completed') return task;
|
|
179
305
|
// task.error.code is the shared core's user-facing code, the one the API reports.
|
|
180
306
|
if (['failed', 'cancelled'].includes(task.status)) {
|
|
181
307
|
throw new CliError('task_failed', `The generation task ${task.status === 'failed' ? 'failed' : 'was cancelled'}${
|
|
182
308
|
task.error?.code ? ` with error code ${task.error.code}` : ''}.`, { task });
|
|
183
309
|
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
310
|
+
last = task.status ? { status: task.status, read_at: task.read_at, status_check: 'verified' }
|
|
311
|
+
: { status: task.last_known_status ?? last?.status, read_at: task.read_at ?? last?.read_at, status_check: 'unverified' };
|
|
312
|
+
progress(task.status ? `${task.task_id}: ${task.status}${task.progress !== undefined ? ` (${task.progress}%)` : ''}`
|
|
313
|
+
: `${taskId}: latest status unverified${last.status ? ` (last verified: ${last.status})` : ''}`);
|
|
314
|
+
const rest = deadline - performance.now();
|
|
315
|
+
if (rest <= 0) throw waitTimeout(taskId, last);
|
|
316
|
+
// Rounds keep the shared polling rhythm for the task type: a short round does not mean reading more often.
|
|
317
|
+
const readMs = Date.parse(task.read_at);
|
|
318
|
+
const sinceRead = Number.isFinite(readMs) ? Math.max(0, Date.now() - readMs) : 0;
|
|
319
|
+
await pause(Math.min(Math.max(ROUND_PAUSE_MS, pollIntervalMs(task.type) - sinceRead), rest), signal);
|
|
187
320
|
}
|
|
188
321
|
}
|
|
189
322
|
}
|
|
@@ -41,6 +41,15 @@ export function withModelConstraints(model) {
|
|
|
41
41
|
if (properties)
|
|
42
42
|
properties.duration = { type: 'integer', anyOf: model.params.duration.anyOf, description: model.params.duration.description, default: model.params.duration.default };
|
|
43
43
|
}
|
|
44
|
+
// mintlify-docs kling-v4-video-edit.json: duration is 3-30 seconds or "auto" (as long as the input video);
|
|
45
|
+
// the generated index keeps the range but leaves any string open.
|
|
46
|
+
if (model.model === 'kling-v4-video-edit') {
|
|
47
|
+
const anyOf = [{ type: 'integer', minimum: 3, maximum: 30 }, { type: 'string', enum: ['auto'] }];
|
|
48
|
+
model.params.duration = { ...model.params.duration, anyOf };
|
|
49
|
+
const properties = model.inputSchema?.schema.properties;
|
|
50
|
+
if (properties)
|
|
51
|
+
properties.duration = { anyOf, description: model.params.duration.description, default: model.params.duration.default };
|
|
52
|
+
}
|
|
44
53
|
if (['gpt-image-2', 'gpt-image-2.5-flare', 'gpt-image-2.5-sunburst', 'gpt-image-2-beta'].includes(model.model)) {
|
|
45
54
|
model.constraints = { ...model.constraints, imageSize: {
|
|
46
55
|
param: 'size', allowed: ['auto', '1:1', '1:2', '2:1', '1:3', '3:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '9:21', '21:9'],
|