@evolinkai/cli 0.8.0 → 0.9.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 +57 -5
- package/package.json +1 -1
- package/skills/evolink-cli/SKILL.md +15 -3
- package/skills/evolink-cli/references/usage-and-budget.md +11 -1
- package/src/api.mjs +19 -2
- package/src/cli.mjs +32 -6
- package/src/errors.mjs +21 -13
- package/src/files.mjs +14 -2
- package/src/help.mjs +8 -2
- package/src/media.mjs +54 -15
- package/src/oauth.mjs +11 -3
- package/src/platform/core/src/config.js +7 -4
- package/src/platform/core/src/platform-client.js +9 -3
- package/src/platform/core/src/platform-operations.js +2 -0
- package/src/platform/core/src/services/api-client.js +61 -29
- package/src/platform/core/src/services/error-handler.js +89 -34
- package/src/platform/core/src/services/file-client.js +32 -0
- package/src/platform/core/src/services/http-policy.js +62 -12
- package/src/platform/core/src/services/model-catalog.js +13 -7
- package/src/platform/core/src/services/pricing-quote-client.js +239 -0
- package/src/platform/core/src/services/pricing-rules-client.js +222 -0
- package/src/platform/core/src/services/pricing-rules-estimate.js +231 -0
- package/src/platform/core/src/services/public-error.js +63 -0
- package/src/platform/core/src/tool-guidance.js +2 -0
- package/src/platform/core/src/tools/estimate-cost.js +36 -11
- package/src/platform/core/src/tools/generate.js +31 -7
- package/src/platform/core/src/tools/get-model.js +3 -1
- package/src/platform/core/src/tools/get-pricing-rules.js +54 -0
- package/src/platform/core/src/tools/shared.js +39 -19
- package/src/platform/core/src/tools/task-billing.js +31 -0
- package/src/platform/core/src/tools/task-format.js +31 -12
- package/src/platform/core/src/version.js +1 -1
- package/src/platform/source.json +47 -35
package/README.md
CHANGED
|
@@ -4,7 +4,9 @@ Generate images, video, music and speech directly through the EvoLink platform A
|
|
|
4
4
|
|
|
5
5
|
The package calls the EvoLink platform API directly using the assistant's terminal. Requires Node.js 22+.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
The pricing-rules estimation changes described below are an unreleased candidate.
|
|
8
|
+
|
|
9
|
+
Estimates use the two published full pricing-rules endpoints and exact UC arithmetic, including resolution, tiers, minimum charges and rounding. Public default prices exclude personal discounts. A failed refresh cannot authorize a new submission. Final settlement caps still require GroAPI/Worker enforcement; responses report `final_budget_enforced: false`.
|
|
8
10
|
|
|
9
11
|
## Status and installation
|
|
10
12
|
|
|
@@ -75,16 +77,16 @@ For an idempotent installation prompt, check Node.js 22+ and `evolink --version`
|
|
|
75
77
|
```sh
|
|
76
78
|
evolink models search --type image --query seedream --json
|
|
77
79
|
evolink models show MODEL --json
|
|
78
|
-
evolink estimate --model MODEL --input-file input.json --
|
|
80
|
+
evolink estimate --model MODEL --input-file input.json --json
|
|
79
81
|
# After the user approves the returned quote:
|
|
80
82
|
evolink generate image --quote QUOTE_ID --confirm --json
|
|
81
83
|
evolink tasks wait TASK_ID --json
|
|
82
84
|
evolink download TASK_ID --output /absolute/result.png --json
|
|
83
85
|
```
|
|
84
86
|
|
|
85
|
-
For video/audio, choose the corresponding generation command and a model's documented input. `estimate` never submits a task. Quotes
|
|
87
|
+
For video/audio, choose the corresponding generation command and a model's documented input. `estimate` never submits a task. Quotes expire at the earlier of the backend expiry and 15 minutes, bind to the login and exact input, and are checked again before generation. A changed quote requires a new approval. `--confirm` conveys the user's approval; the CLI cannot verify a conversation by itself.
|
|
86
88
|
|
|
87
|
-
|
|
89
|
+
Show the estimated cost and ask the user to confirm the task. The CLI does not turn that estimate into a spending cap. If the user explicitly specifies a budget, compare the estimate with it; pause if it exceeds that budget or cannot be fully estimated. The legacy `--max-cost-usd` option remains compatible for this estimate comparison and does not limit the final charge. `--media-seconds` is a pricing hint, never a model parameter. Actual-usage billing requires explaining the relevant uncertainty; a missing price is refused.
|
|
88
90
|
|
|
89
91
|
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.
|
|
90
92
|
|
|
@@ -101,6 +103,20 @@ evolink uploads get UPLOAD_ID --json
|
|
|
101
103
|
evolink download TASK_ID --output /absolute/result.mp4 --index 1 --json
|
|
102
104
|
```
|
|
103
105
|
|
|
106
|
+
Uploads save a stable request ID before sending bytes. On connection loss, keep
|
|
107
|
+
that ID and run `evolink uploads get UPLOAD_ID --json`. With a compatible file
|
|
108
|
+
service this reads an account-owned receipt retained for up to 72 hours; it never
|
|
109
|
+
repeats the upload. Older services return an unknown outcome rather than a false
|
|
110
|
+
failure. Logout revokes future use of the scoped upload grant; an upload already
|
|
111
|
+
accepted before logout may still finish. Recovery retains the original login
|
|
112
|
+
binding and never copies OAuth credentials into MCP settings.
|
|
113
|
+
|
|
114
|
+
Passport can advertise `evolink_cli_mcp_supported: true`. New browser grants then
|
|
115
|
+
use the public official `evolink-cli` identity with PKCE, `mcp offline_access`, and
|
|
116
|
+
the configured MCP resource. Existing dynamic-client sessions refresh with their
|
|
117
|
+
original client ID. Earlier Passport deployments continue to use dynamic
|
|
118
|
+
registration. This does not change shared CLI/MCP account-Key limits or permissions.
|
|
119
|
+
|
|
104
120
|
Task-list filters are case-sensitive:
|
|
105
121
|
|
|
106
122
|
| Option | Allowed values | When omitted |
|
|
@@ -120,6 +136,15 @@ Uploads stream up to 95 MiB directly to the file service using a short-lived upl
|
|
|
120
136
|
|
|
121
137
|
## Discovery, task pages and all-result delivery
|
|
122
138
|
|
|
139
|
+
Read structured public configuration prices without logging in:
|
|
140
|
+
|
|
141
|
+
```sh
|
|
142
|
+
evolink models pricing --model gemini-2.5-pro --view full --json
|
|
143
|
+
evolink models pricing --modality text --lifecycle active --json
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
This uses `GET /v1/catalog/pricing-rules` (or the single-model route), preserves decimal-string amounts (including fractional UC rates), pricing versions, minimum charges and tier expressions, and revalidates bounded caches with ETag. Full media rules preserve signed parameter bounds, allowed `values`, lookup keys and multiplier tables, and nested expressions. `meta.price_selection=route_priority` identifies the web-aligned route-priority reference; absent metadata or `configured_minimum` means legacy lowest configuration prices. Public defaults can differ from account discounts and failover settlement; unavailable models still have reference prices. Coverage follows the returned published policies and supported legacy text adapters; empty results mean no matching public rules were returned. This command does not create a quote, calculate a bill or authorize a spending cap. Continue using `estimate` with the exact media input and keep its uncertainty and budget guards.
|
|
147
|
+
|
|
123
148
|
Every command supports local `--help --json`, with option enums, bounds and defaults. New discovery tools and page/model/until filters come from the bundled shared platform module. The CLI checks bundled operation capabilities and reports `capability_unavailable` before calling an unsupported tool or sending an unsupported filter.
|
|
124
149
|
|
|
125
150
|
```sh
|
|
@@ -172,7 +197,7 @@ Development starts in `deeplearning-goethe/evolink-cli`. After acceptance, repos
|
|
|
172
197
|
|
|
173
198
|
## Platform and MCP paths
|
|
174
199
|
|
|
175
|
-
The CLI uses REST and does not connect to the hosted MCP server. Browser chat clients continue to use remote MCP. Both paths currently share Passport resource permissions and the internal `EvoLink MCP (OAuth)` account limit. The authorization resource remains `https://mcp.evolink.ai/mcp`; it is distinct from the REST API destination. The gateway MCP emergency switch still applies to both paths. Total and daily limits, model permissions and pause apply to both clients; logging out revokes only the current OAuth session. Separate keys are optional when a project needs independent limits.
|
|
200
|
+
The CLI uses REST and does not connect to the hosted MCP server. Browser chat clients continue to use remote MCP. Both paths currently share Passport resource permissions and the internal `EvoLink MCP (OAuth)` account limit. The authorization resource remains `https://mcp.evolink.ai/mcp`; it is distinct from the REST API destination. The gateway MCP emergency switch still applies to both paths. Total and daily limits, model permissions and pause apply to both clients; logging out revokes only the current OAuth session. Separate keys are optional when a project needs independent limits. Backend parameterized media Quote and its OAuth route must be enabled for account estimates.
|
|
176
201
|
|
|
177
202
|
The CLI vendors the reviewed shared platform module from the MCP repository with a SHA-256 source/artifact manifest in `src/platform/source.json`. Refresh it on the test host using `scripts/sync-platform-client.mjs`; never edit generated files. The MCP SDK is a development dependency for compatibility fixtures only. No extra package or MCP plugin installation is needed by CLI users.
|
|
178
203
|
|
|
@@ -195,3 +220,30 @@ Run `gemini mcp list` from the intended project directory. If EvoLink is `Disabl
|
|
|
195
220
|
Headless mode exposes only tools permitted by its policy. In Gemini CLI 0.63.0, a scoped MCP rule uses `mcpName`, not `serverName`; allow only the tools needed for the chosen workflow. For example, a quote-only policy can allow `search_models`, `get_model`, `estimate_cost`, `check_balance` and `get_task` on `evolink`. Generation still requires the user's quote approval and the host's normal tool permission. Do not silently add a generation allow rule or treat a successful process exit without EvoLink tool calls as acceptance.
|
|
196
221
|
|
|
197
222
|
See [Gemini trusted folders](https://geminicli.com/docs/cli/trusted-folders/) and [Gemini MCP configuration and OAuth](https://geminicli.com/docs/tools/mcp-server/). A cloud terminal test does not prove desktop inline previews, browser handoff on another machine or permission defaults in every host.
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
Generation errors preserve the saved quote and request ID when acceptance or charging is uncertain. `charged: no` alone does not authorize a new request: `submission_state` must also establish `not_submitted` or `rejected`. Recover uncertain submissions with the original quote, and query a known task. A new generation needs a fresh estimate and user approval.
|
|
226
|
+
|
|
227
|
+
A failed/cancelled task does not establish a refund. `tasks get` can successfully return that task, while `tasks wait` exits nonzero with the same task and billing details. `billing.refund_status` reports account-balance evidence: `unknown`, `pending`, `failed`, `completed`, or `not_required`. A completed refund includes recorded credits and time; key-limit restoration remains unknown. Old gateways without billing fields retain unknown status, rather than claiming zero charge or a completed refund.
|
|
228
|
+
|
|
229
|
+
### Rules estimates and refresh
|
|
230
|
+
|
|
231
|
+
`evolink estimate` reads the published full pricing policy for the canonical model.
|
|
232
|
+
The local `quote_id` stores input binding, pricing fingerprint, integer UC subtotal
|
|
233
|
+
and expiry; there is no backend `estimate_id`. Approval expires at the earlier of
|
|
234
|
+
catalog freshness and 15 minutes. Before first submission, the CLI reads the rules
|
|
235
|
+
again and refuses changed prices, policy or usage until a new estimate is approved.
|
|
236
|
+
Neither backend Quote nor new OAuth quote access is required. Existing login,
|
|
237
|
+
shared MCP key, quota and permissions remain.
|
|
238
|
+
|
|
239
|
+
Use `evolink estimate --refresh-quote ID` for an unsubmitted approval. It preserves
|
|
240
|
+
input and an explicit user budget, creates a new local approval and requires user
|
|
241
|
+
confirmation again. Unknown recovery keeps the original input and request ID;
|
|
242
|
+
a failed replay cannot prove the first submission was free. Known tasks remain
|
|
243
|
+
readable after expiry; check the original task before preparing another request.
|
|
244
|
+
|
|
245
|
+
Supply required measured or expected billing usage with
|
|
246
|
+
`--pricing-parameters '{"input_seconds":5.77}'`. Default `--pricing-source pricing_rules`
|
|
247
|
+
and old `account`/`public_reference` aliases use the same published full rules.
|
|
248
|
+
Partial estimates name missing usage and cannot check a budget. Estimates exclude
|
|
249
|
+
personal discounts and do not reserve quota or guarantee the final charge.
|
package/package.json
CHANGED
|
@@ -11,9 +11,11 @@ After loading this skill, continue the requested workflow by executing its requi
|
|
|
11
11
|
|
|
12
12
|
## Quote failure and budget rules
|
|
13
13
|
|
|
14
|
-
-
|
|
14
|
+
- By default, show the estimated cost and ask for approval. Do not invent or display an additional spending cap, and never derive `max_cost_usd` from the quote.
|
|
15
|
+
- If the user explicitly specifies a budget, compare the estimate with it and preserve that budget on every attempt. The compatibility option `--max-cost-usd` carries this estimate comparison; it does not limit the final charge. Pause if the estimate exceeds the budget or is incomplete. If the user requires a guaranteed final maximum, explain that this client cannot enforce it before obtaining approval for any changed requirement.
|
|
15
16
|
- 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.
|
|
16
17
|
- 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.
|
|
18
|
+
- When supported, `models pricing --model MODEL --view full --json` reads public default rules without login. Coverage follows the returned published policies and legacy text adapters; missing rules do not mean free. Preserve fractional UC decimal strings, signed parameter bounds, allowed `values`, lookup keys and tables, nested expressions, minimum charges, tiers, price scope and validity. `meta.price_selection=route_priority` means a web-aligned reference; absent metadata means legacy minimum configuration prices. Public rates may differ from account prices and failover settlement. This response never replaces `estimate`, creates a quote or establishes a final spending cap.
|
|
17
19
|
|
|
18
20
|
## Connect
|
|
19
21
|
|
|
@@ -45,9 +47,9 @@ For image edits, reference-based video, speech or music, read [media workflows](
|
|
|
45
47
|
|
|
46
48
|
- 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.
|
|
47
49
|
- When comparing reference support, retrieving schemas or searching model documentation, read [Discovery and delivery extensions](references/capabilities.md). Use `models recommend`, `models schema` and `docs search` only when the installed CLI supports them. Keep the user's chosen model; recommendations explain alternatives, not automatic approval.
|
|
48
|
-
- 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. `uploads get ID` reads the saved receipt. If it returns `outcome_unknown` and `result_verified: false`, no result was
|
|
50
|
+
- 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. Keep the original `upload_id` if a response is lost. `uploads get ID` reads the saved receipt and, when supported by the file service, recovers a completed upload without resending bytes. If it returns `outcome_unknown` and `result_verified: false`, no result was verified; check the user's files before uploading again. A missing receipt from an older service does not prove the file failed to arrive. Legacy MCP upload slots require the older CLI version.
|
|
49
51
|
- 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.
|
|
50
|
-
- 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
|
|
52
|
+
- 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 a total. Do not add a separate cap to the default confirmation; if the user gave a budget, say whether the estimate fits it.
|
|
51
53
|
|
|
52
54
|
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.
|
|
53
55
|
|
|
@@ -78,3 +80,13 @@ Use `generate` for the first submission of an approved quote. `tasks resume` is
|
|
|
78
80
|
Use `--json` for commands consumed by the assistant. Progress is on stderr; stdout is one JSON envelope with `schema_version: 1`. `ok: false` and a nonzero exit code indicate a command error; a successful task query reporting `status: failed` is a task outcome, not a failed CLI invocation. Read the error's recovery details before retrying. For `invalid_status`, use `error.details.allowed_values` and correct only the free query; local status validation occurs before a platform request. Never guess an enum, interpret an empty list as a service failure, or resubmit a paid task to fix a query error. Run `evolink --help` for the maintained command reference and `evolink tasks list --help` for task filters.
|
|
79
81
|
|
|
80
82
|
For setup problems, run `evolink doctor --agent NAME --json` if the installed version supports the agent option; otherwise use `doctor --json`. Read every failed or skipped check. On Linux, login and later commands need the same unlocked Secret Service/D-Bus session. On SSH hosts, opening the link on another computer requires forwarding the loopback callback port; `--no-browser` does not solve callback routing. Report connection, model discovery and assistant skill discovery separately.
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
Estimates use published full pricing rules and show public default prices, excluding
|
|
86
|
+
personal discounts. The local approval expires no later than the rules' freshness.
|
|
87
|
+
Use `evolink estimate --refresh-quote ID` only for an unsubmitted approval; preserve
|
|
88
|
+
the input and explicit user budget and obtain approval again. Supply missing billing
|
|
89
|
+
usage with `--pricing-parameters JSON`; never invent unknown token counts or media
|
|
90
|
+
lengths. Partial subtotals cannot check a budget. If rules are unavailable or change,
|
|
91
|
+
pause and preserve the budget. Actual usage can change the final charge; final
|
|
92
|
+
settlement caps require gateway/Worker support.
|
|
@@ -12,6 +12,16 @@ evolink usage --since 2026-10-01T00:00:00Z --until 2026-10-09T00:00:00Z --model
|
|
|
12
12
|
|
|
13
13
|
Always show the interval, account-wide scope, completed-task cost, missing-cost count and coverage. `complete_for_retained_tasks` means all currently retained matching tasks were scanned under the observed pagination; historical retention and snapshot consistency are not guaranteed. `truncated`, invalid rows or detected concurrent changes prevent claiming a full total. Do not turn missing costs into zero or infer a refund from failed/cancelled task status. This summary excludes reservations, payments, refunds and non-task charges. It is not a bill, tax invoice or a transactions API.
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
The default flow shows the estimated cost and asks for approval; it creates no spending cap. When the user specifies a budget, compare the estimate with that budget and preserve it across retries. The compatibility option `--max-cost-usd` checks this estimate comparison, not the final charge. Unknown totals, token usage, generated audio duration or incompletely priced reference inputs can prevent a complete comparison. Pause if the estimate exceeds the budget or cannot be checked; explain the uncertainty before accepting any changed requirement.
|
|
16
16
|
|
|
17
17
|
A final task/workflow cap requires server-side reservation and settlement enforcement with an authoritative quote and ledger. This client cannot create that guarantee by polling, summing history or stopping local waiting. Do not label this version as supporting final settlement budgets or downloadable invoices.
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
Estimates use published full pricing rules and show public default prices, excluding
|
|
21
|
+
personal discounts. The local approval expires no later than the rules' freshness.
|
|
22
|
+
Use `evolink estimate --refresh-quote ID` only for an unsubmitted approval; preserve
|
|
23
|
+
the input and explicit user budget and obtain approval again. Supply missing billing
|
|
24
|
+
usage with `--pricing-parameters JSON`; never invent unknown token counts or media
|
|
25
|
+
lengths. Partial subtotals cannot check a budget. If rules are unavailable or change,
|
|
26
|
+
pause and preserve the budget. Actual usage can change the final charge; final
|
|
27
|
+
settlement caps require gateway/Worker support.
|
package/src/api.mjs
CHANGED
|
@@ -31,6 +31,19 @@ export class Api {
|
|
|
31
31
|
if (requireCapability) requireThat(this.platform.supports(name, requiredInputs),
|
|
32
32
|
'capability_unavailable', 'This CLI does not contain the requested platform capability. Update the CLI; no request was sent.',
|
|
33
33
|
{ tool: name, required_inputs: requiredInputs, request_sent: false });
|
|
34
|
+
// Public configuration rules do not require login, refresh or key access.
|
|
35
|
+
if (name === 'get_pricing_rules') {
|
|
36
|
+
const result = await this.platform.call(name, args, {
|
|
37
|
+
http: { fetch: this.fetchFn, signal: this.signal, userAgent: USER_AGENT, client: 'cli',
|
|
38
|
+
version: CLI_VERSION, controlBaseUrl: this.apiUrl.origin },
|
|
39
|
+
});
|
|
40
|
+
const data = result.structuredContent;
|
|
41
|
+
const text = (result.content ?? []).filter(item => item.type === 'text').map(item => item.text).join('\n');
|
|
42
|
+
if (result.isError || data?.ok === false) throw new CliError(this.signal?.aborted ? 'interrupted' : data?.error?.code || data?.error?.category || 'api_failed',
|
|
43
|
+
safeMessage(text || 'Public pricing rules could not be read.'), data, this.signal?.aborted ? 130 : 1);
|
|
44
|
+
requireThat(data?.ok === true, 'unsupported_response', 'EvoLink returned no structured pricing rules.');
|
|
45
|
+
return { ...data, text };
|
|
46
|
+
}
|
|
34
47
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
35
48
|
const access = await this.credentials.access(attempt > 0);
|
|
36
49
|
const result = await this.platform.call(name, args, this.context(access, name));
|
|
@@ -46,10 +59,14 @@ export class Api {
|
|
|
46
59
|
}
|
|
47
60
|
throw new CliError('login_required', 'The login expired. Run auth login.');
|
|
48
61
|
}
|
|
49
|
-
async uploadFile(source, size, mime, name, uploadPath) {
|
|
62
|
+
async uploadFile(source, size, mime, name, uploadPath, uploadId) {
|
|
50
63
|
const access = await this.credentials.access();
|
|
51
|
-
try { return await this.platform.upload(source, size, mime, name, this.context(access, 'upload_file'), uploadPath); }
|
|
64
|
+
try { return await this.platform.upload(source, size, mime, name, this.context(access, 'upload_file'), uploadPath, uploadId); }
|
|
52
65
|
catch (error) { throw new CliError(this.signal?.aborted ? 'interrupted' : error.info?.category || 'upload_unknown',
|
|
53
66
|
safeMessage(error.info?.message || 'The upload did not return a verified file result.'), undefined, this.signal?.aborted ? 130 : 1); }
|
|
54
67
|
}
|
|
68
|
+
async uploadReceipt(id) {
|
|
69
|
+
const access = await this.credentials.access();
|
|
70
|
+
return this.platform.uploadReceipt(id, this.context(access, 'get_upload'));
|
|
71
|
+
}
|
|
55
72
|
}
|
package/src/cli.mjs
CHANGED
|
@@ -56,10 +56,14 @@ const HELP = `EvoLink CLI ${CLI_VERSION} (Node.js 22+)
|
|
|
56
56
|
balance Verify connection and account balance (free)
|
|
57
57
|
models search [--query TEXT] [--type image|video|audio|all] [--limit N]
|
|
58
58
|
models show MODEL Read parameters and pricing (free)
|
|
59
|
+
models pricing [--model MODEL] [--modality TYPE] [--view summary|full]
|
|
60
|
+
Read public default rules; not a quote (no login)
|
|
59
61
|
models schema MODEL Read versioned input/submission schemas (free)
|
|
60
62
|
models recommend --type TYPE [--query TEXT] [--references image,video,audio]
|
|
61
63
|
docs search --query TEXT Search official model reference excerpts (free)
|
|
62
|
-
estimate --model MODEL --input-file FILE [--
|
|
64
|
+
estimate --model MODEL --input-file FILE [--media-seconds N]
|
|
65
|
+
[--pricing-parameters JSON] [--pricing-source pricing_rules]
|
|
66
|
+
estimate --refresh-quote ID Refresh saved input and budget; approval required
|
|
63
67
|
generate image|video|audio --quote ID --confirm [--wait] [--timeout SECONDS]
|
|
64
68
|
tasks get ID | tasks wait ID [--timeout SECONDS]
|
|
65
69
|
tasks list [--type TYPE] [--status STATUS] [--since TIME] [--limit N]
|
|
@@ -98,8 +102,8 @@ Spending caps protect the estimate at submission, not final settlement.
|
|
|
98
102
|
Ctrl-C stops local waiting; submitted tasks continue on EvoLink.
|
|
99
103
|
`;
|
|
100
104
|
|
|
101
|
-
const OPTIONS = Object.fromEntries(['server', 'api-url', 'files-url', 'query', 'type', 'limit', 'model', 'input', 'input-file', 'prompt', 'media-seconds',
|
|
102
|
-
'max-cost-usd', 'quote', 'timeout', 'status', 'since', 'until', 'page', 'ids', 'references', 'max-pages', 'output', 'output-dir', 'template', 'index', 'upload-path', 'agent'].map(k => [k, { type: 'string' }]));
|
|
105
|
+
const OPTIONS = Object.fromEntries(['server', 'api-url', 'files-url', 'query', 'type', 'limit', 'model', 'modality', 'view', 'product-id', 'operation', 'lifecycle', 'input', 'input-file', 'prompt', 'media-seconds',
|
|
106
|
+
'pricing-source', 'pricing-parameters', 'refresh-quote', 'max-cost-usd', 'quote', 'timeout', 'status', 'since', 'until', 'page', 'ids', 'references', 'max-pages', 'output', 'output-dir', 'template', 'index', 'upload-path', 'agent'].map(k => [k, { type: 'string' }]));
|
|
103
107
|
for (const k of ['json', 'token-stdin', 'no-browser', 'replace-modified', 'confirm', 'wait', 'all', 'resume', 'help', 'version']) OPTIONS[k] = { type: 'boolean' };
|
|
104
108
|
|
|
105
109
|
function number(value, name, min, max, integer = false) {
|
|
@@ -115,9 +119,10 @@ export function validateCommand(args, options) {
|
|
|
115
119
|
setup: [1, 'agent', 'no-browser', 'timeout'],
|
|
116
120
|
'auth login': [2, 'no-browser', 'timeout'], 'auth status': [2], 'auth logout': [2], balance: [1],
|
|
117
121
|
'models search': [2, 'query', 'type', 'limit', 'page'], 'models show': [3], 'models schema': [3],
|
|
122
|
+
'models pricing': [2, 'model', 'modality', 'view', 'product-id', 'operation', 'lifecycle'],
|
|
118
123
|
'models recommend': [2, 'type', 'query', 'references', 'limit'], 'docs search': [2, 'query', 'type', 'limit'],
|
|
119
124
|
usage: [1, 'since', 'until', 'type', 'model', 'max-pages'],
|
|
120
|
-
estimate: [1, 'model', 'input', 'input-file', 'prompt', 'media-seconds', 'max-cost-usd'],
|
|
125
|
+
estimate: [1, 'model', 'input', 'input-file', 'prompt', 'media-seconds', 'max-cost-usd', 'pricing-source', 'pricing-parameters', 'refresh-quote'],
|
|
121
126
|
'generate image': [2, 'quote', 'confirm', 'wait', 'timeout'], 'generate video': [2, 'quote', 'confirm', 'wait', 'timeout'], 'generate audio': [2, 'quote', 'confirm', 'wait', 'timeout'],
|
|
122
127
|
'tasks get': [3], 'tasks wait': [3, 'timeout'], 'tasks batch': [2, 'ids'], 'tasks list': [2, 'type', 'status', 'since', 'until', 'model', 'page', 'limit'], 'tasks resume': [2, 'quote'],
|
|
123
128
|
upload: [2, 'upload-path'], 'uploads get': [3], download: [2, 'output', 'index', 'all', 'output-dir', 'template', 'resume'],
|
|
@@ -179,9 +184,15 @@ async function estimateArgs(options) {
|
|
|
179
184
|
requireThat(input.prompt === undefined || input.prompt === options.prompt, 'invalid_input', 'prompt was supplied twice with different values.');
|
|
180
185
|
input.prompt = options.prompt;
|
|
181
186
|
}
|
|
187
|
+
let pricingParameters;
|
|
188
|
+
if (options['pricing-parameters'] !== undefined) {
|
|
189
|
+
try { pricingParameters = JSON.parse(options['pricing-parameters']); } catch { throw new CliError('invalid_input', 'pricing-parameters must contain valid JSON.'); }
|
|
190
|
+
requireThat(pricingParameters && typeof pricingParameters === 'object' && !Array.isArray(pricingParameters), 'invalid_input', 'pricing-parameters must be a JSON object.');
|
|
191
|
+
}
|
|
192
|
+
requireThat(options['pricing-source'] === undefined || ['pricing_rules', 'account', 'public_reference'].includes(options['pricing-source']), 'invalid_option', 'pricing-source must be pricing_rules (account/public_reference remain compatibility aliases).');
|
|
182
193
|
const media = number(options['media-seconds'], 'media-seconds', Number.MIN_VALUE, 3600);
|
|
183
194
|
const cap = number(options['max-cost-usd'], 'max-cost-usd', Number.MIN_VALUE, 10_000);
|
|
184
|
-
return { model: options.model, input, ...(media !== undefined ? { media_seconds: media } : {}), ...(cap !== undefined ? { max_cost_usd: cap } : {}) };
|
|
195
|
+
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 } : {}) };
|
|
185
196
|
}
|
|
186
197
|
|
|
187
198
|
export async function dispatch(positionals, options, { state, server, credentials, client, mcp = client, signal, progress, skillHome }) {
|
|
@@ -195,6 +206,14 @@ export async function dispatch(positionals, options, { state, server, credential
|
|
|
195
206
|
}
|
|
196
207
|
if (command === 'balance') return client.call('check_balance');
|
|
197
208
|
if (command === 'models') {
|
|
209
|
+
if (action === 'pricing') return client.call('get_pricing_rules', {
|
|
210
|
+
...(options.model !== undefined ? { model: options.model } : {}),
|
|
211
|
+
...(options.modality !== undefined ? { modality: options.modality } : {}),
|
|
212
|
+
...(options.view !== undefined ? { view: options.view } : {}),
|
|
213
|
+
...(options['product-id'] !== undefined ? { product_id: options['product-id'] } : {}),
|
|
214
|
+
...(options.operation !== undefined ? { operation: options.operation } : {}),
|
|
215
|
+
...(options.lifecycle !== undefined ? { lifecycle: options.lifecycle } : {}),
|
|
216
|
+
}, { requireCapability: true });
|
|
198
217
|
if (action === 'show' && id) return client.call('get_model', { model: id });
|
|
199
218
|
if (action === 'schema' && id) {
|
|
200
219
|
const model = await client.call('get_model', { model: id });
|
|
@@ -210,7 +229,14 @@ export async function dispatch(positionals, options, { state, server, credential
|
|
|
210
229
|
if (command === 'docs') return client.call('search_docs', { query: options.query, type: options.type || 'all', limit: number(options.limit, 'limit', 1, 20, true) || 5 }, { requireCapability: true });
|
|
211
230
|
if (command === 'usage') return client.call('get_task_usage', { since: options.since || '30d', until: options.until, model: options.model, type: options.type,
|
|
212
231
|
max_pages: number(options['max-pages'], 'max-pages', 1, 20, true) || 5 }, { requireCapability: true });
|
|
213
|
-
if (command === 'estimate')
|
|
232
|
+
if (command === 'estimate') {
|
|
233
|
+
if (options['refresh-quote']) {
|
|
234
|
+
requireThat(!['model', 'input', 'input-file', 'prompt', 'media-seconds', 'max-cost-usd', 'pricing-source', 'pricing-parameters'].some(key => options[key] !== undefined),
|
|
235
|
+
'invalid_option', 'refresh-quote reuses the saved input and budget; do not combine it with new estimate parameters.');
|
|
236
|
+
return media.refresh(options['refresh-quote']);
|
|
237
|
+
}
|
|
238
|
+
return media.estimate(await estimateArgs(options));
|
|
239
|
+
}
|
|
214
240
|
if (command === 'generate') {
|
|
215
241
|
requireThat(options.quote, 'missing_quote', 'Run estimate and obtain user approval before generation.');
|
|
216
242
|
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.');
|
package/src/errors.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { publicIdentifier, publicText } from './platform/core/src/services/public-error.js';
|
|
1
2
|
export class CliError extends Error {
|
|
2
3
|
constructor(code, message, details, exitCode = 1) {
|
|
3
4
|
super(message);
|
|
@@ -34,12 +35,7 @@ export async function localFile(action, context) {
|
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
export function safeMessage(message) {
|
|
37
|
-
return String(message)
|
|
38
|
-
.replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')
|
|
39
|
-
.replace(/\b(?:sk-|evup_)[a-zA-Z0-9_-]+/g, '[redacted]')
|
|
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]')
|
|
42
|
-
.slice(0, 2000);
|
|
38
|
+
return publicText(String(message));
|
|
43
39
|
}
|
|
44
40
|
|
|
45
41
|
export function errorView(error) {
|
|
@@ -50,11 +46,23 @@ export function errorView(error) {
|
|
|
50
46
|
return { code: error.code, message: safeMessage(error.message), ...(error.details ? { details: safeDetails(error.details) } : {}) };
|
|
51
47
|
}
|
|
52
48
|
|
|
53
|
-
function safeDetails(value) {
|
|
54
|
-
if (
|
|
55
|
-
if (
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
49
|
+
function safeDetails(value, depth = 0, seen = new WeakSet(), key = '') {
|
|
50
|
+
if (depth > 8) return '[truncated]';
|
|
51
|
+
if (typeof value === 'string') {
|
|
52
|
+
if (['client_request_id', 'task_id', 'quote_id', 'request_id'].includes(key)) return publicIdentifier(value);
|
|
53
|
+
// Preserve original media links in a failed task with partial results; they are delivery data.
|
|
54
|
+
if (['url', 'uri', 'image_url', 'video_url', 'audio_url'].includes(key)) {
|
|
55
|
+
try { const url = new URL(value); if (['https:', 'http:'].includes(url.protocol) && !url.username && !url.password) return value; } catch {}
|
|
56
|
+
}
|
|
57
|
+
return safeMessage(value);
|
|
58
|
+
}
|
|
59
|
+
if (value && typeof value === 'object') {
|
|
60
|
+
if (seen.has(value)) return '[truncated]';
|
|
61
|
+
seen.add(value);
|
|
62
|
+
if (Array.isArray(value)) return value.slice(0, 100).map(v => safeDetails(v, depth + 1, seen, key));
|
|
63
|
+
return Object.fromEntries(Object.entries(value).slice(0, 100)
|
|
64
|
+
.filter(([k]) => !k.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(k))
|
|
65
|
+
.map(([k, v]) => [safeMessage(k), safeDetails(v, depth + 1, seen, k)]));
|
|
66
|
+
}
|
|
67
|
+
return typeof value === 'number' && !Number.isFinite(value) ? undefined : value;
|
|
60
68
|
}
|
package/src/files.mjs
CHANGED
|
@@ -56,7 +56,7 @@ async function directUpload(file, size, mime, { client, state, server, upload_pa
|
|
|
56
56
|
await state.write('uploads', upload_id, journal);
|
|
57
57
|
const source = createReadStream(file);
|
|
58
58
|
try {
|
|
59
|
-
const result = await client.uploadFile(source, size, mime, path.basename(file), upload_path);
|
|
59
|
+
const result = await client.uploadFile(source, size, mime, path.basename(file), upload_path, upload_id);
|
|
60
60
|
const data = result?.data;
|
|
61
61
|
requireThat(result?.success === true && typeof data?.file_id === 'string' && typeof data?.file_url === 'string',
|
|
62
62
|
'upload_unknown', 'The file service returned no verified upload result.');
|
|
@@ -84,8 +84,20 @@ export async function getUpload(id, { client, state, server }) {
|
|
|
84
84
|
requireThat(journal.api_origin === client.apiUrl.origin && journal.binding === (await client.credentials.access()).binding,
|
|
85
85
|
'upload_session_changed', 'This receipt belongs to a different platform or login.');
|
|
86
86
|
if (journal.state === 'done') return journal.result;
|
|
87
|
+
let receipt;
|
|
88
|
+
try { receipt = await client.uploadReceipt?.(id); }
|
|
89
|
+
catch { throw new CliError('upload_unknown', 'The original upload receipt is unavailable. Keep this upload_id and retry this read later; no bytes were resent.',
|
|
90
|
+
{ upload_id: id, state: 'outcome_unknown', next_step: `evolink uploads get ${id}` }); }
|
|
91
|
+
if (receipt?.state === 'done' && receipt.result_verified === true) {
|
|
92
|
+
const data = receipt.file;
|
|
93
|
+
journal.state = 'done';
|
|
94
|
+
journal.result = { ok: true, upload_id: id, state: 'done', file_id: data.file_id, file_url: data.file_url,
|
|
95
|
+
file_name: data.original_name ?? data.file_name, size_bytes: data.file_size, mime_type: data.mime_type, expires_at: data.expires_at };
|
|
96
|
+
await state.write('uploads', id, journal);
|
|
97
|
+
return journal.result;
|
|
98
|
+
}
|
|
87
99
|
return { ok: true, upload_id: id, state: 'outcome_unknown', result_verified: false,
|
|
88
|
-
text: 'No completed receipt
|
|
100
|
+
text: 'No verified completed receipt is available. The upload may still have arrived. Check your files before starting another upload; this command only reads the original receipt and never resends bytes.' };
|
|
89
101
|
}
|
|
90
102
|
|
|
91
103
|
export async function download(taskId, output, { client, mcp = client, server, index = 1, signal, maxBytes = 1024 ** 3, fetchFn, task: suppliedTask, beforeCommit }) {
|
package/src/help.mjs
CHANGED
|
@@ -17,12 +17,18 @@ const COMMANDS = {
|
|
|
17
17
|
balance: ['', 'Read account balance and the shared CLI/MCP OAuth key limits. Free.', {}],
|
|
18
18
|
'models search': ['[options]', 'Search currently available models; search order is not a quality ranking.', { query: string('Search keywords'), type: allMedia, limit: integer(1, 50, 20), page: integer(1, 100000, 1) }],
|
|
19
19
|
'models show': ['MODEL', 'Read documented parameters, example input, reference fields and pricing. Free.', {}],
|
|
20
|
+
'models pricing': ['[options]', 'Read public default pricing rules without login. Decimal-string rates, minimums, tiers and expressions are configuration references, not account prices, quotes, bills or final spending caps. Coverage follows returned policies and legacy text adapters; empty results do not mean free.', {
|
|
21
|
+
model: string('Exact model ID; omit for the filtered list'), 'product-id': string('Product ID'), operation: string('Operation, e.g. text_generation'),
|
|
22
|
+
modality: choice(['text', 'image', 'video', 'audio']), lifecycle: choice(['active', 'preview', 'deprecated']), view: { ...choice(['summary', 'full']), default: 'full' },
|
|
23
|
+
}],
|
|
20
24
|
'models schema': ['MODEL', 'Read versioned input and generation-submission response schemas. The response schema may omit final task outputs; runtime constraints also apply.', {}],
|
|
21
25
|
'models recommend': ['--type TYPE [options]', 'Compare documented available alternatives with selection reasons. Unit rates are not total quotes.', { type: media, query: string('Search keywords; every term must match'), references: string('Comma-separated image,video,audio'), limit: integer(1, 10, 3) }],
|
|
22
26
|
'docs search': ['--query TEXT [options]', 'Search versioned official model reference excerpts, not the live full website.', { query: string('Required model reference keywords'), type: allMedia, limit: integer(1, 20, 5) }],
|
|
23
|
-
estimate: ['--model MODEL --input-file FILE [options]', 'Prepare
|
|
27
|
+
estimate: ['--model MODEL --input-file FILE [options] | --refresh-quote ID', 'Prepare an account estimate valid until the backend expiry, at most 15 minutes. Show the estimated cost and material uncertainty, then obtain user approval. No spending cap is created from the estimate.', {
|
|
24
28
|
model: string('Required model ID'), input: string('JSON object; mutually exclusive with input-file'), 'input-file': string('Local JSON file; mutually exclusive with input'), prompt: string('Optional prompt'),
|
|
25
|
-
'
|
|
29
|
+
'pricing-source': choice(['account', 'public_reference']), 'pricing-parameters': string('JSON object containing declared billing usage'),
|
|
30
|
+
'refresh-quote': string('Refresh an unsubmitted saved quote with its existing input and budget'),
|
|
31
|
+
'max-cost-usd': { type: 'number', exclusive_minimum: 0, maximum: 10000, description: 'Compatibility option for an explicit user budget: compare the estimate only; it does not cap the final charge' }, 'media-seconds': { type: 'number', exclusive_minimum: 0, maximum: 3600 },
|
|
26
32
|
}],
|
|
27
33
|
'tasks get': ['TASK_ID', 'Read one task. A failed task status is a successful query outcome. Free.', {}],
|
|
28
34
|
'tasks wait': ['TASK_ID [options]', 'Wait locally. Ctrl-C stops waiting; the submitted task continues. Free.', { timeout: integer(1, 86400, 1800) }],
|
package/src/media.mjs
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { hash } from './state.mjs';
|
|
3
3
|
import { CliError, requireThat, fileError } from './errors.mjs';
|
|
4
|
+
import { rulesBudgetExceeded } from './platform/core/src/services/pricing-rules-estimate.js';
|
|
5
|
+
import { compareDecimal } from './platform/core/src/services/pricing-quote-client.js';
|
|
4
6
|
|
|
5
7
|
function quoteError(error, cap) {
|
|
6
8
|
const cause = fileError(error);
|
|
7
|
-
|
|
9
|
+
const code = cause.details?.input_valid === false ? 'invalid_input'
|
|
10
|
+
: cap !== undefined && ['quote_usage_required', 'quote_parameter_required'].includes(cause.details?.error?.code) ? 'uncheckable_cap'
|
|
11
|
+
: cause instanceof CliError ? cause.code : 'estimate_unavailable';
|
|
12
|
+
return new CliError(code,
|
|
8
13
|
cause instanceof CliError ? cause.message : 'The quote could not be obtained. No generation was submitted.', {
|
|
9
14
|
...(cause instanceof CliError ? cause.details : {}), phase: 'estimate', submission_allowed: false,
|
|
10
15
|
...(cap !== undefined ? { max_cost_usd: cap } : {}),
|
|
@@ -14,7 +19,10 @@ function quoteError(error, cap) {
|
|
|
14
19
|
|
|
15
20
|
export function priceFingerprint(quote) {
|
|
16
21
|
return hash({ model: quote.model, type: quote.type, input_valid: quote.input_valid, estimate: quote.estimate,
|
|
17
|
-
warnings: quote.warnings, pricing_warning: quote.pricing_warning
|
|
22
|
+
warnings: quote.warnings, pricing_warning: quote.pricing_warning, pricing_scope: quote.pricing_scope,
|
|
23
|
+
rules: quote.pricing_quote && { fingerprint: quote.pricing_quote.fingerprint, request_hash: quote.pricing_quote.request_hash, total_uc: quote.pricing_quote.total_uc },
|
|
24
|
+
account: quote.account_quote && { request_hash: quote.account_quote.request_hash, parameters: quote.account_quote.parameters,
|
|
25
|
+
quote: Object.fromEntries(Object.entries(quote.account_quote.quote).filter(([key]) => !['estimate_id', 'expires_at', 'assumptions'].includes(key))) } });
|
|
18
26
|
}
|
|
19
27
|
|
|
20
28
|
export function checkEstimate(quote, cap) {
|
|
@@ -32,7 +40,10 @@ export function checkEstimate(quote, cap) {
|
|
|
32
40
|
requireThat(quote.input_valid === true, 'uncheckable_input', 'The service could not validate the model input. The CLI cannot submit this request with a spending cap.', { problems: quote.problems });
|
|
33
41
|
requireThat(quote.estimate?.status === 'estimated' && Number.isFinite(quote.estimate.max_usd),
|
|
34
42
|
'uncheckable_cap', 'This request has no complete cost estimate. The CLI cannot submit it with a spending cap.', { estimate: quote.estimate });
|
|
35
|
-
|
|
43
|
+
const withinBudget = quote.pricing_quote ? !rulesBudgetExceeded(quote.pricing_quote.total_uc, cap) : quote.account_quote
|
|
44
|
+
? compareDecimal(quote.account_quote.quote.amount, String(cap)) <= 0
|
|
45
|
+
: quote.estimate.max_usd <= cap;
|
|
46
|
+
requireThat(withinBudget, 'cost_exceeds_cap', 'The estimated cost exceeds max-cost-usd.', { estimate: quote.estimate, max_cost_usd: cap });
|
|
36
47
|
}
|
|
37
48
|
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 });
|
|
38
49
|
}
|
|
@@ -44,22 +55,33 @@ export class Media {
|
|
|
44
55
|
let quote;
|
|
45
56
|
try {
|
|
46
57
|
quote = await this.client.call('estimate_cost', input);
|
|
58
|
+
|
|
47
59
|
checkEstimate(quote, max_cost_usd);
|
|
48
60
|
requireThat(['image', 'video', 'audio'].includes(quote.type), 'unsupported_model', 'This model is not a media generation model.');
|
|
49
61
|
} catch (error) { throw quoteError(error, max_cost_usd); }
|
|
50
|
-
//
|
|
51
|
-
const quotedMax = quote.estimate.max_usd;
|
|
52
|
-
const effectiveCap = max_cost_usd ?? (quote.input_valid === true && quote.estimate.status === 'estimated' && Number.isFinite(quotedMax) && quotedMax > 0 && quotedMax <= 10_000 ? quotedMax : undefined);
|
|
62
|
+
// Keep an explicit user budget; an estimate does not create a spending cap.
|
|
53
63
|
const id = randomUUID();
|
|
54
|
-
const argsToSubmit = { ...input, model: quote.model, ...(
|
|
64
|
+
const argsToSubmit = { ...input, model: quote.model, ...(quote.pricing_quote ? { pricing_quote: quote.pricing_quote } : {}), ...(quote.account_quote ? { account_quote: quote.account_quote } : {}), ...(max_cost_usd !== undefined ? { max_cost_usd } : {}) };
|
|
65
|
+
const serverExpiry = quote.pricing_quote ? Date.parse(quote.pricing_quote.expires_at) : quote.account_quote ? Date.parse(quote.account_quote.quote.expires_at) : undefined;
|
|
66
|
+
requireThat(serverExpiry === undefined || Number.isFinite(serverExpiry) && serverExpiry > this.now(),
|
|
67
|
+
'quote_expired', 'The estimate expired before it could be saved. Request another estimate.');
|
|
68
|
+
const expires = Math.min(this.now() + 15 * 60_000, serverExpiry ?? Infinity);
|
|
55
69
|
const stored = { id, server: this.server, binding: quote._binding, args: argsToSubmit,
|
|
56
70
|
...(this.client.apiUrl ? { backend: 'platform', api_origin: this.client.apiUrl.origin } : {}),
|
|
57
71
|
type: quote.type, args_hash: hash(argsToSubmit), fingerprint: priceFingerprint(quote), estimate: quote.estimate,
|
|
58
|
-
created_at: this.now(), expires_at:
|
|
72
|
+
created_at: this.now(), expires_at: expires, ...(quote.account_quote ? { backend_estimate_id: quote.account_quote.quote.estimate_id,
|
|
73
|
+
server_expires_at: serverExpiry, account_quote: quote.account_quote } : {}), state: 'quoted', client_request_id: `cli-${randomUUID()}` };
|
|
59
74
|
await this.state.write('quotes', id, stored);
|
|
60
|
-
return { ...quote, quote_id: id, input: input.input || {}, max_cost_usd
|
|
75
|
+
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(),
|
|
61
76
|
requires_confirmation: true, next_step: `After the user approves, run evolink generate ${quote.type} --quote ${id} --confirm.` };
|
|
62
77
|
}
|
|
78
|
+
async refresh(id) {
|
|
79
|
+
const quote = await this.load(id);
|
|
80
|
+
requireThat(quote.state === 'quoted' && !quote.task_id, 'submission_already_started',
|
|
81
|
+
'This submission has started. Recover its original task instead of refreshing its quote.');
|
|
82
|
+
const { account_quote, pricing_quote, ...args } = quote.args;
|
|
83
|
+
return { ...await this.estimate(args), refreshed_from: id };
|
|
84
|
+
}
|
|
63
85
|
async load(id) {
|
|
64
86
|
const quote = await this.state.read('quotes', id);
|
|
65
87
|
requireThat(quote?.server === this.server, 'quote_not_found', 'This quote does not exist for the current server.');
|
|
@@ -85,24 +107,41 @@ export class Media {
|
|
|
85
107
|
requireThat(resume ? ['submitting', 'outcome_unknown'].includes(quote.state) : quote.state === 'quoted',
|
|
86
108
|
'submission_already_started', 'A submission already started. Use tasks resume with this quote; do not create a new request ID.', { quote_id: id, client_request_id: quote.client_request_id });
|
|
87
109
|
requireThat(this.now() <= quote.expires_at, 'quote_expired', 'The quote expired. Check recent tasks before preparing another submission.', { quote_id: id, client_request_id: quote.client_request_id });
|
|
88
|
-
const { max_cost_usd, ...checkArgs } = quote.args;
|
|
110
|
+
const { max_cost_usd, account_quote, pricing_quote, ...checkArgs } = quote.args;
|
|
89
111
|
let fresh;
|
|
90
112
|
try {
|
|
91
|
-
|
|
92
|
-
|
|
113
|
+
// Preserve the original approved request during uncertain submission recovery.
|
|
114
|
+
fresh = resume && (account_quote || pricing_quote) ? { model: quote.args.model, type: quote.type, input_valid: true, estimate: quote.estimate, account_quote, pricing_quote }
|
|
115
|
+
: await this.client.call('estimate_cost', checkArgs);
|
|
116
|
+
requireThat(resume && (account_quote || pricing_quote) || priceFingerprint(fresh) === quote.fingerprint, 'price_changed', 'The quote changed. Estimate again and obtain approval for the new quote.', { estimate: fresh.estimate });
|
|
93
117
|
checkEstimate(fresh, max_cost_usd);
|
|
94
118
|
} catch (error) { throw quoteError(error, max_cost_usd); }
|
|
119
|
+
if (!resume && fresh.pricing_quote) {
|
|
120
|
+
const expires = Date.parse(fresh.pricing_quote.expires_at);
|
|
121
|
+
requireThat(Number.isFinite(expires) && expires > this.now(), 'quote_expired', 'The refreshed estimate expired before submission.');
|
|
122
|
+
quote.args.pricing_quote = fresh.pricing_quote;
|
|
123
|
+
quote.server_expires_at = expires;
|
|
124
|
+
quote.args_hash = hash(quote.args);
|
|
125
|
+
}
|
|
126
|
+
if (!resume && fresh.account_quote) {
|
|
127
|
+
const expires = Date.parse(fresh.account_quote.quote.expires_at);
|
|
128
|
+
requireThat(Number.isFinite(expires) && expires > this.now(), 'quote_expired', 'The refreshed account quote expired before submission.');
|
|
129
|
+
quote.args.account_quote = fresh.account_quote; quote.account_quote = fresh.account_quote;
|
|
130
|
+
quote.backend_estimate_id = fresh.account_quote.quote.estimate_id; quote.server_expires_at = expires;
|
|
131
|
+
quote.args_hash = hash(quote.args);
|
|
132
|
+
}
|
|
95
133
|
quote.state = 'submitting';
|
|
96
134
|
quote.approved_at ??= this.now();
|
|
97
135
|
await this.state.write('quotes', id, quote);
|
|
98
136
|
let result;
|
|
99
137
|
try {
|
|
100
|
-
|
|
138
|
+
const { pricing_source, ...generationArgs } = quote.args;
|
|
139
|
+
result = await this.client.call(`generate_${kind}`, { ...generationArgs, client_request_id: quote.client_request_id });
|
|
101
140
|
requireThat(typeof result.task_id === 'string' && result.task_id.length > 0, 'outcome_unknown', 'The submission returned no task ID. Recover with the original quote.');
|
|
102
141
|
} catch (e) {
|
|
103
|
-
quote.state = e.details?.charged === 'no' ? 'refused' : 'outcome_unknown';
|
|
142
|
+
quote.state = !resume && e.details?.charged === 'no' && ['not_submitted', 'rejected'].includes(e.details?.submission_state) ? 'refused' : 'outcome_unknown';
|
|
104
143
|
await this.state.write('quotes', id, quote);
|
|
105
|
-
throw new CliError(e.code || 'outcome_unknown', e.message, { ...(e.details || {}), quote_id: id, client_request_id: quote.client_request_id,
|
|
144
|
+
throw new CliError(resume ? 'outcome_unknown' : e.code || 'outcome_unknown', resume ? 'The original submission remains unverified. The replay could not proceed; check recent tasks with the original request ID before preparing any new generation.' : e.message, { ...(e.details || {}), ...(quote.state === 'outcome_unknown' ? { charged: 'unknown', submission_state: 'outcome_unknown' } : {}), quote_id: id, client_request_id: quote.client_request_id,
|
|
106
145
|
recovery: `evolink tasks resume --quote ${id}` }, e.exitCode);
|
|
107
146
|
}
|
|
108
147
|
quote.state = 'submitted';
|
package/src/oauth.mjs
CHANGED
|
@@ -10,7 +10,7 @@ export async function metadata(server, fetchFn) {
|
|
|
10
10
|
const data = await response.json();
|
|
11
11
|
requireThat(data.issuer === issuer && data.code_challenge_methods_supported?.includes('S256'),
|
|
12
12
|
'invalid_auth_metadata', 'Passport did not provide the expected issuer and PKCE method.');
|
|
13
|
-
for (const key of ['authorization_endpoint', 'token_endpoint', '
|
|
13
|
+
for (const key of ['authorization_endpoint', 'token_endpoint', 'revocation_endpoint', ...(data.registration_endpoint ? ['registration_endpoint'] : [])]) {
|
|
14
14
|
let endpoint;
|
|
15
15
|
try { endpoint = new URL(data[key]); } catch { throw new CliError('invalid_auth_metadata', 'Passport did not provide valid login endpoints.'); }
|
|
16
16
|
requireThat(endpoint.origin === issuer && !endpoint.username && !endpoint.password && !endpoint.hash,
|
|
@@ -19,11 +19,19 @@ export async function metadata(server, fetchFn) {
|
|
|
19
19
|
return data;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
async function client(provider, data, fetchFn) {
|
|
22
|
+
async function client(provider, data, fetchFn, newLogin = false) {
|
|
23
23
|
let value = await provider.clientInformation();
|
|
24
24
|
if (value) requireThat(value.issuer === data.issuer && typeof value.client_id === 'string' && !value.client_secret,
|
|
25
25
|
'invalid_client', 'The saved public OAuth client belongs to a different service.');
|
|
26
|
+
// A rolled-back Passport may no longer support media grants for this public
|
|
27
|
+
// identity. Only a new login can change clients; an existing refresh cannot.
|
|
28
|
+
if (newLogin && value?.client_id === 'evolink-cli' && data.evolink_cli_mcp_supported !== true) value = undefined;
|
|
29
|
+
if ((!value || newLogin) && data.evolink_cli_mcp_supported === true) {
|
|
30
|
+
value = { client_id: 'evolink-cli', issuer: data.issuer, token_endpoint_auth_method: 'none' };
|
|
31
|
+
await provider.saveClientInformation(value);
|
|
32
|
+
}
|
|
26
33
|
if (!value) {
|
|
34
|
+
requireThat(data.registration_endpoint, 'registration_unavailable', 'Passport does not support CLI client registration. Update the login service or retry later.');
|
|
27
35
|
const response = await fetchFn(data.registration_endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
28
36
|
body: JSON.stringify(provider.clientMetadata) });
|
|
29
37
|
requireThat(response.ok, 'registration_failed', 'Passport could not register this CLI login.');
|
|
@@ -68,7 +76,7 @@ export async function refresh(provider, fetchFn) {
|
|
|
68
76
|
|
|
69
77
|
export async function authorize(provider, fetchFn, authorizationCode) {
|
|
70
78
|
const data = await metadata(provider.server, fetchFn);
|
|
71
|
-
const info = await client(provider, data, fetchFn);
|
|
79
|
+
const info = await client(provider, data, fetchFn, !authorizationCode);
|
|
72
80
|
if (authorizationCode) return token(provider, data, info, { grant_type: 'authorization_code', code: authorizationCode,
|
|
73
81
|
redirect_uri: String(provider.redirectUrl), code_verifier: await provider.codeVerifier() }, fetchFn);
|
|
74
82
|
const verifier = randomBytes(32).toString('base64url');
|