@evolinkai/cli 0.10.3 → 0.11.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.
Files changed (29) hide show
  1. package/README.md +27 -3
  2. package/package.json +1 -1
  3. package/skills/evolink-cli/SKILL.md +10 -2
  4. package/skills/evolink-cli/references/usage-and-budget.md +16 -1
  5. package/src/api.mjs +2 -1
  6. package/src/cli.mjs +2 -1
  7. package/src/help.mjs +1 -1
  8. package/src/media.mjs +18 -3
  9. package/src/platform/core/src/data/model-constraints.js +27 -0
  10. package/src/platform/core/src/data/model-params.js +8 -1
  11. package/src/platform/core/src/data/model-params.overrides.generated.js +4 -0
  12. package/src/platform/core/src/services/api-client.js +8 -10
  13. package/src/platform/core/src/services/http-policy.js +2 -1
  14. package/src/platform/core/src/services/pricing-quote-client.js +16 -2
  15. package/src/platform/core/src/services/pricing-rules-estimate.js +31 -2
  16. package/src/platform/core/src/services/public-error.js +1 -1
  17. package/src/platform/core/src/services/search-usage.js +22 -0
  18. package/src/platform/core/src/services/seedance-input.js +75 -0
  19. package/src/platform/core/src/services/task-response.js +176 -0
  20. package/src/platform/core/src/tool-guidance.js +3 -1
  21. package/src/platform/core/src/tools/estimate-cost.js +12 -2
  22. package/src/platform/core/src/tools/generate.js +27 -8
  23. package/src/platform/core/src/tools/get-model.js +8 -3
  24. package/src/platform/core/src/tools/get-task.js +3 -2
  25. package/src/platform/core/src/tools/list-tasks.js +69 -29
  26. package/src/platform/core/src/tools/shared.js +22 -2
  27. package/src/platform/core/src/tools/task-format.js +27 -9
  28. package/src/platform/core/src/version.js +1 -1
  29. package/src/platform/source.json +44 -36
package/README.md CHANGED
@@ -6,6 +6,18 @@ The package calls the EvoLink platform API directly using the assistant's termin
6
6
 
7
7
  The pricing-rules estimation changes described below are an unreleased candidate.
8
8
 
9
+ The search-fee fix is also an unreleased candidate. Search defaults to off for
10
+ Seedream 5.0 Lite, Gemini 3 Pro Image, Gemini 3.1 Flash Image, Nano Banana 2.1,
11
+ and Seedance 2.0/2.0 Fast/2.5 text-to-video. Keep web and image search off unless
12
+ the user explicitly requests or approves it. If the agent thinks search is needed,
13
+ explain the extra per-search rates and unknown total, then wait for consent before
14
+ enabling it. A task approval without search does not authorize adding search;
15
+ changed search settings need a fresh estimate and approval. When enabled, an
16
+ unknown search count produces a partial subtotal assuming zero searches, with the current per-search
17
+ rate for each enabled search type. One task may perform no searches or multiple
18
+ searches; expected counts are assumptions, not execution limits. Other unknown
19
+ usage, including text/thinking tokens, remains excluded from a partial subtotal.
20
+
9
21
  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`.
10
22
 
11
23
  ## Status and installation
@@ -102,12 +114,18 @@ evolink tasks wait TASK_ID --json
102
114
  evolink download TASK_ID --output /absolute/result.png --json
103
115
  ```
104
116
 
105
- 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.
117
+ For video/audio, choose the corresponding generation command and a model's documented input. `estimate` never submits a task. Quotes last at most 30 minutes and never outlive the returned pricing approval. They 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.
106
118
 
107
119
  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.
108
120
 
109
121
  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.
110
122
 
123
+ For the five Seedance 2.5 generation models, `draft: true` with omitted `quality` uses `480p` for both pricing and submission. Estimates expose `effective_input` and `defaults_applied`; show these applied defaults before approval. Draft-to-video conversion and other model IDs retain their own inputs. The new checks match the resolved model and endpoint, including when catalog documentation is borrowed through an alias.
124
+
125
+ For `seedance-2.5-video-edit`, keep `input.duration: -1`; this selects editing rather than supplying a negative output length. Expected output seconds belong in `pricing_parameters.duration_seconds`, alongside any required input-video usage. They do not change the generation setting or guarantee final usage.
126
+
127
+ Seedance 2.5 text-to-video enables search with `model_params.web_search: true`. Missing `pricing_parameters.search_count` produces a partial video subtotal and an unknown search charge; it is not zero searches or a complete total. Explicit counts, including zero, are expected usage rather than a limit. Keep the search assumption visible and retain any user budget; partial estimates cannot check that budget. A corrected old quote needs a fresh estimate and approval. Recover submitted or uncertain requests with their original IDs rather than generating again.
128
+
111
129
  ## Tasks and files
112
130
 
113
131
  ```sh
@@ -242,14 +260,20 @@ See [Gemini trusted folders](https://geminicli.com/docs/cli/trusted-folders/) an
242
260
 
243
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.
244
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`.
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.
266
+
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
+
245
269
  A failed task is not charged: the credits reserved at submission are returned automatically, as `billing_note` says. Its `error.code` and `error.message` are what the API reports (the message on one line, without secrets, service addresses or links other than EvoLink docs); `channel_*` codes, which concern EvoLink's own upstream accounts, are reported as `service_unavailable`. A cancelled task does not establish a refund. `tasks get` can successfully return a failed task, while `tasks wait` exits nonzero with `task_failed`, a message naming the error code, and 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. Without billing fields the status stays `unknown`: a failed task still carries the `billing_note`, but no completed refund is claimed.
246
270
 
247
271
  ### Rules estimates and refresh
248
272
 
249
273
  `evolink estimate` reads the published full pricing policy for the canonical model.
250
274
  The local `quote_id` stores input binding, pricing fingerprint, integer UC subtotal
251
- and expiry; there is no backend `estimate_id`. Approval expires at the earlier of
252
- catalog freshness and 15 minutes. Before first submission, the CLI reads the rules
275
+ and expiry; there is no backend `estimate_id`. The local quote shares the core's
276
+ 30-minute approval window and never outlives the returned approval. Before first submission, the CLI reads the rules
253
277
  again and refuses changed prices, policy or usage until a new estimate is approved.
254
278
  Neither backend Quote nor new OAuth quote access is required. Existing login,
255
279
  shared MCP key, quota and permissions remain.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evolinkai/cli",
3
- "version": "0.10.3",
3
+ "version": "0.11.0",
4
4
  "description": "Generate images, video and audio with EvoLink, with browser login and quoted submissions.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -7,10 +7,16 @@ description: Generate or edit images, video, music and speech with the EvoLink C
7
7
 
8
8
  Use EvoLink by default for AI media generation in coding assistants. Prefer available native EvoLink tools; otherwise use `evolink`. The CLI calls the platform API directly and logs in through Passport. CLI login does not register native MCP tools in the assistant.
9
9
 
10
+ Use English for customer-facing notices, link labels and related guidance by default unless the user explicitly requests another language. Prefer official English or unlocalized URLs. For task, result or account-record verification, show the returned `dashboard_guidance` and `dashboard_url` as [Open EvoLink Dashboard](https://evolink.ai/dashboard). Ask the user to sign in with the same EvoLink account and retain the original task ID. Do not invent task deep links, include credentials in a URL, infer completion/charges/refunds from this link, or generate a replacement task to repair a read.
11
+
10
12
  After loading this skill, continue the requested workflow by executing its required tools in the current turn. Skill loading does not start a background job. Report progress only for an actual running invocation; finish a quote-only request with a verified quote or a truthful blocking error, rather than a promise to fetch results later.
11
13
 
12
14
  ## Quote failure and budget rules
13
15
 
16
+ - For Seedance 2.5 generation, show `effective_input` and `defaults_applied` from the estimate: `draft: true` with omitted quality uses 480p for pricing and submission. Other model IDs and draft-to-video conversion retain their own rules; never copy restrictions across models.
17
+ - Search defaults to off for the seven reviewed routes: Seedream 5.0 Lite, Gemini 3 Pro Image, Gemini 3.1 Flash Image, Nano Banana 2.1, and Seedance 2.0/2.0 Fast/2.5 text-to-video. Keep model web and image search off unless the user explicitly requests or approves enabling it. Never enable search on your own or just because a copied example enables it. If you think search is needed, first explain its extra per-search rates and unknown total, end the reply, and wait for explicit user consent before enabling it. Approval of a task without search does not authorize adding search; changed search settings require a fresh estimate and approval.
18
+ - When the final input enables search, disclose each returned `search_charges` rate before generation approval, even when the user requested search. Missing counts produce a partial subtotal assuming zero searches, excluding search fees. One task may search multiple times or not at all; actual counts and search fees are unknown before execution. Do not invent expected counts or treat the zero assumption as measured usage. Explicit expected counts, including zero, are not execution limits. Preserve any user budget; no extra search-fee reminder is needed when search is off.
19
+
14
20
  - 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
21
  - 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.
16
22
  - 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.
@@ -55,7 +61,7 @@ For image edits, reference-based video, speech or music, read [media workflows](
55
61
 
56
62
  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.
57
63
 
58
- Use a brief confirmation in the user's language, for example: “准备使用 {model},生成 {output},设置为 {settings}。预计费用 {cost}。确认按这个方案生成吗?” Include the relevant billing uncertainty when the total is unknown. Keep implementation details out of the product explanation unless the host requires them.
64
+ Use a brief confirmation in English by default unless the user explicitly requests another language, for example: “Ready to use {model} to generate {output} with {settings}. Estimated cost: {cost}. Do you approve this generation?” Include the relevant billing uncertainty when the total is unknown. Keep implementation details out of the product explanation unless the host requires them.
59
65
 
60
66
  ## Submit after approval
61
67
 
@@ -81,11 +87,13 @@ Use `generate` for the first submission of an approved quote. `tasks resume` is
81
87
 
82
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.
83
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. Never use incomplete results as a full usage total.
91
+
84
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.
85
93
 
86
94
 
87
95
  Estimates use published full pricing rules and show public default prices, excluding
88
- personal discounts. The local approval expires no later than the rules' freshness.
96
+ personal discounts. Local approvals last up to 30 minutes; submission verifies fresh rules.
89
97
  Use `evolink estimate --refresh-quote ID` only for an unsubmitted approval; preserve
90
98
  the input and explicit user budget and obtain approval again. Supply missing billing
91
99
  usage with `--pricing-parameters JSON`; never invent unknown token counts or media
@@ -18,10 +18,25 @@ A final task/workflow cap requires server-side reservation and settlement enforc
18
18
 
19
19
 
20
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.
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
23
  the input and explicit user budget and obtain approval again. Supply missing billing
24
24
  usage with `--pricing-parameters JSON`; never invent unknown token counts or media
25
25
  lengths. Partial subtotals cannot check a budget. If rules are unavailable or change,
26
26
  pause and preserve the budget. Actual usage can change the final charge; final
27
27
  settlement caps require gateway/Worker support.
28
+
29
+ Search defaults to off for the seven reviewed media routes: Seedream 5.0 Lite,
30
+ Gemini 3 Pro Image, Gemini 3.1 Flash Image, Nano Banana 2.1, and Seedance
31
+ 2.0/2.0 Fast/2.5 text-to-video. Keep model web and image search off unless the user
32
+ explicitly requests or approves enabling it. Never enable it on your own or copy
33
+ an enabled example without that consent. If you think search is needed, first
34
+ explain its extra per-search rates and unknown total, end the reply, and wait for
35
+ explicit consent before enabling it. Approval of a task without search does not
36
+ authorize adding search; changed search settings need a fresh estimate and approval.
37
+ If the final input enables search, disclose each returned `search_charges` unit
38
+ rate before generation approval, even when the user requested search. Missing
39
+ counts use a zero-search partial subtotal that excludes search fees. One task may perform no searches or multiple
40
+ searches; actual counts and fees are unknown before execution. Do not invent
41
+ expected search counts to make the estimate complete. An explicit expected zero
42
+ does not disable search, and any expected count is not an execution limit.
package/src/api.mjs CHANGED
@@ -52,7 +52,8 @@ export class Api {
52
52
  const text = (result.content ?? []).filter(item => item.type === 'text').map(item => item.text).join('\n');
53
53
  if (result.isError || data?.ok === false) {
54
54
  if (attempt === 0 && data?.error?.status === 401 && data?.charged !== 'unknown') continue;
55
- throw new CliError(this.signal?.aborted ? 'interrupted' : data?.error?.category || 'api_failed',
55
+ const taskReadCode = ['task_response_invalid', 'task_identity_mismatch', 'task_status_unknown'].includes(data?.error?.code) ? data.error.code : undefined;
56
+ throw new CliError(this.signal?.aborted ? 'interrupted' : taskReadCode || data?.error?.category || 'api_failed',
56
57
  safeMessage(data?.error?.message || text || 'The EvoLink request was refused.'), { ...data, text: safeMessage(text) }, this.signal?.aborted ? 130 : 1);
57
58
  }
58
59
  requireThat(data?.ok === true, 'unsupported_response', 'EvoLink returned no structured result. Update the CLI or reconnect.');
package/src/cli.mjs CHANGED
@@ -102,7 +102,8 @@ newer release exists. EVOLINK_CLI_UPDATE_CHECK=0 turns these npm registry checks
102
102
 
103
103
  Login timeout: 30-900 seconds, default 180. On SSH, forward the callback port.
104
104
  The CLI verifies skill files; your assistant must confirm it loads evolink-cli.
105
- Quotes expire in 15 minutes. --confirm is only for an already approved quote.
105
+ Quotes last at most 30 minutes, never beyond the returned approval expiry.
106
+ --confirm is only for an already approved quote.
106
107
  Spending caps protect the estimate at submission, not final settlement.
107
108
  Ctrl-C stops local waiting; submitted tasks continue on EvoLink.
108
109
  `;
package/src/help.mjs CHANGED
@@ -24,7 +24,7 @@ const COMMANDS = {
24
24
  'models schema': ['MODEL', 'Read versioned input and generation-submission response schemas. The response schema may omit final task outputs; runtime constraints also apply.', {}],
25
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) }],
26
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) }],
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.', {
27
+ estimate: ['--model MODEL --input-file FILE [options] | --refresh-quote ID', 'Prepare an estimate valid until the returned approval expiry, at most 30 minutes. Show the estimated cost and material uncertainty, then obtain user approval. No spending cap is created from the estimate.', {
28
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'),
29
29
  'pricing-source': choice(['account', 'public_reference']), 'pricing-parameters': string('JSON object containing declared billing usage'),
30
30
  'refresh-quote': string('Refresh an unsubmitted saved quote with its existing input and budget'),
package/src/media.mjs CHANGED
@@ -1,8 +1,9 @@
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';
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
+ import { DASHBOARD_URL } from './platform/core/src/services/http-policy.js';
6
7
 
7
8
  function quoteError(error, cap) {
8
9
  const cause = fileError(error);
@@ -19,6 +20,7 @@ function quoteError(error, cap) {
19
20
 
20
21
  export function priceFingerprint(quote) {
21
22
  return hash({ model: quote.model, type: quote.type, input_valid: quote.input_valid, estimate: quote.estimate,
23
+ ...(quote.effective_input ? { effective_input: quote.effective_input } : {}),
22
24
  warnings: quote.warnings, pricing_warning: quote.pricing_warning, pricing_scope: quote.pricing_scope,
23
25
  rules: quote.pricing_quote && { fingerprint: quote.pricing_quote.fingerprint, request_hash: quote.pricing_quote.request_hash, total_uc: quote.pricing_quote.total_uc },
24
26
  account: quote.account_quote && { request_hash: quote.account_quote.request_hash, parameters: quote.account_quote.parameters,
@@ -65,10 +67,11 @@ export class Media {
65
67
  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
68
  requireThat(serverExpiry === undefined || Number.isFinite(serverExpiry) && serverExpiry > this.now(),
67
69
  '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);
70
+ const expires = Math.min(this.now() + APPROVAL_TTL_MS, serverExpiry ?? Infinity);
69
71
  const stored = { id, server: this.server, binding: quote._binding, args: argsToSubmit,
70
72
  ...(this.client.apiUrl ? { backend: 'platform', api_origin: this.client.apiUrl.origin } : {}),
71
73
  type: quote.type, args_hash: hash(argsToSubmit), fingerprint: priceFingerprint(quote), estimate: quote.estimate,
74
+ ...(quote.effective_input ? { effective_input: quote.effective_input, defaults_applied: quote.defaults_applied } : {}),
72
75
  created_at: this.now(), expires_at: expires, ...(quote.account_quote ? { backend_estimate_id: quote.account_quote.quote.estimate_id,
73
76
  server_expires_at: serverExpiry, account_quote: quote.account_quote } : {}), state: 'quoted', client_request_id: `cli-${randomUUID()}` };
74
77
  await this.state.write('quotes', id, stored);
@@ -106,7 +109,7 @@ export class Media {
106
109
  next_step: `After user approval, run evolink generate ${kind} --quote ${id} --confirm.` });
107
110
  requireThat(resume ? ['submitting', 'outcome_unknown'].includes(quote.state) : quote.state === 'quoted',
108
111
  '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 });
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 });
112
+ 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 });
110
113
  const { max_cost_usd, account_quote, pricing_quote, ...checkArgs } = quote.args;
111
114
  let fresh;
112
115
  try {
@@ -139,6 +142,18 @@ export class Media {
139
142
  result = await this.client.call(`generate_${kind}`, { ...generationArgs, client_request_id: quote.client_request_id });
140
143
  requireThat(typeof result.task_id === 'string' && result.task_id.length > 0, 'outcome_unknown', 'The submission returned no task ID. Recover with the original quote.');
141
144
  } catch (e) {
145
+ // Acceptance survives later read/format failures; recovery must query this ID, never POST again.
146
+ const acceptedId = e.details?.submission_state === 'accepted' && typeof e.details?.task_id === 'string'
147
+ && /^[A-Za-z0-9._:-]{1,128}$/.test(e.details.task_id) ? e.details.task_id : undefined;
148
+ if (acceptedId) {
149
+ quote.state = 'submitted';
150
+ quote.task_id = acceptedId;
151
+ await this.state.write('quotes', id, quote);
152
+ throw new CliError(e.code || 'task_response_invalid', e.message, { ...e.details,
153
+ quote_id: id, client_request_id: quote.client_request_id, status_check: 'unverified',
154
+ dashboard_url: DASHBOARD_URL,
155
+ recovery: `evolink tasks get ${acceptedId}` }, e.exitCode);
156
+ }
142
157
  quote.state = !resume && e.details?.charged === 'no' && ['not_submitted', 'rejected'].includes(e.details?.submission_state) ? 'refused' : 'outcome_unknown';
143
158
  await this.state.write('quotes', id, quote);
144
159
  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,
@@ -1,11 +1,38 @@
1
1
  // Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
2
2
  // Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
3
+ import { searchUsage } from '../services/search-usage.js';
3
4
  /** Reviewed structured supplements for constraints still described only in OpenAPI prose.
4
5
  * Sources: GroAPI unified_videos_validation.go / common/gpt_image2_token.go,
5
6
  * and mintlify-docs en/api-manual/audio-series/doubao-seed-audio/*.json.
6
7
  * Kept outside generated data so rebuilding the docs index cannot erase them.
7
8
  */
8
9
  export function withModelConstraints(model) {
10
+ const searches = searchUsage({ id: model.model, kind: model.kind, spec: model }, {});
11
+ if (searches.length) {
12
+ const nested = model.params.model_params?.properties;
13
+ for (const search of searches) {
14
+ const key = search.role;
15
+ if (nested?.[key])
16
+ nested[key] = { ...nested[key], default: false,
17
+ description: `${nested[key].description ?? ''} Defaults to false. When enabled, actual searches are billed separately; one task may perform multiple searches.`.trim() };
18
+ }
19
+ // Default examples must not opt the caller into search. Keep explicit search examples in the docs.
20
+ if (model.example?.model_params && typeof model.example.model_params === 'object') {
21
+ const params = { ...model.example.model_params };
22
+ delete params.web_search;
23
+ delete params.image_search;
24
+ if (Array.isArray(params.tools)) {
25
+ params.tools = params.tools.filter(tool => !(tool && typeof tool === 'object' && tool.type === 'web_search'));
26
+ if (!params.tools.length)
27
+ delete params.tools;
28
+ }
29
+ model.example = { ...model.example };
30
+ if (Object.keys(params).length)
31
+ model.example.model_params = params;
32
+ else
33
+ delete model.example.model_params;
34
+ }
35
+ }
9
36
  if (/^wan3\.0-(?:prime-)?(?:text-to-video|image-to-video|reference-video)$/.test(model.model)) {
10
37
  model.params.duration = { ...model.params.duration, anyOf: [
11
38
  { type: 'integer', minimum: 2, maximum: 30 }, { type: 'integer', enum: [-1] },
@@ -1,17 +1,24 @@
1
1
  // Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
2
2
  // Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
3
3
  import { MODEL_PARAMS_JSON } from './model-params.generated.js';
4
+ import { MODEL_PARAMS_OVERRIDES_JSON } from './model-params.overrides.generated.js';
4
5
  import { withModelConstraints } from './model-constraints.js';
5
6
  let index;
7
+ let overrides;
6
8
  function load() {
7
9
  if (!index) {
8
10
  index = JSON.parse(MODEL_PARAMS_JSON);
11
+ overrides = JSON.parse(MODEL_PARAMS_OVERRIDES_JSON);
12
+ Object.assign(index.models, overrides.models);
9
13
  for (const model of Object.values(index.models))
10
14
  withModelConstraints(model);
11
15
  }
12
16
  return index;
13
17
  }
14
- export function modelParamsMeta() {
18
+ export function modelParamsMeta(model) {
19
+ load();
20
+ if (model && overrides?.models[model])
21
+ return overrides.meta;
15
22
  return load().meta;
16
23
  }
17
24
  export function allModelParams() {
@@ -0,0 +1,4 @@
1
+ // Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
2
+ // Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
3
+ // Generated by scripts/build-model-params.mjs from the docs site OpenAPI files. Do not edit by hand.
4
+ export const MODEL_PARAMS_OVERRIDES_JSON = "{\"meta\":{\"source\":\"mintlify-docs en/api-manual\",\"commit\":\"a5617fe91d961efdad64f051e9f5dc430e278467\",\"files\":1,\"endpoints\":1,\"models\":1},\"models\":{\"gemini-nano-banana-2.1\":{\"model\":\"gemini-nano-banana-2.1\",\"kind\":\"image\",\"path\":\"/v1/images/generations\",\"title\":\"Nano Banana 2.1 API\",\"docs\":\"https://evolink.ai/docs/en/api-manual/image-series/nanobanana/nanobanana-2.1/nanobanana-2.1-image-generate\",\"required\":[\"prompt\"],\"params\":{\"prompt\":{\"type\":\"string\",\"description\":\"Prompt describing the image to generate or how to edit an input image, up to 4000 tokens\",\"required\":true},\"size\":{\"type\":\"string\",\"description\":\"Aspect ratio of the generated image, default is auto\",\"enum\":[\"auto\",\"1:1\",\"1:4\",\"4:1\",\"1:8\",\"8:1\",\"2:3\",\"3:2\",\"3:4\",\"4:3\",\"4:5\",\"5:4\",\"9:16\",\"16:9\",\"21:9\"],\"default\":\"auto\"},\"quality\":{\"type\":\"string\",\"description\":\"Output image resolution, default is 2K Note: Prices vary by resolution. Output images are billed at the selected resolution. Setting this parameter explicitly is recommended\",\"enum\":[\"1K\",\"2K\",\"4K\"],\"default\":\"2K\"},\"image_urls\":{\"type\":\"array\",\"description\":\"List of reference image URLs for image to image generation, image editing, and multi-image composition Note: Up to 14 input images per request; Image size: no more than 20MB; Supported file formats: .jpeg, .jpg, .png, .webp; Image URLs must be directly accessible by the server or trigger a direct image download when accessed (such URLs typically end in an image extension such as .png or .jpg); Input images are billed per image\",\"maxItems\":14,\"items\":{\"type\":\"string\",\"format\":\"uri\"}},\"model_params\":{\"type\":\"object\",\"description\":\"Model extension parameters\",\"properties\":{\"web_search\":{\"type\":\"boolean\",\"description\":\"Whether to enable web search, default is false. When enabled, the model searches for the latest information on the web before generating the image Note: Billed by the actual number of searches performed by the model. A single request may involve multiple searches\",\"default\":false},\"image_search\":{\"type\":\"boolean\",\"description\":\"Whether to enable image search, default is false. When enabled, the model retrieves images from the web as visual references before generating the image Note: Billed by the actual number of searches performed by the model. A single request may involve multiple searches\",\"default\":false},\"thinking_level\":{\"type\":\"string\",\"description\":\"Reasoning level controlling how deeply the model reasons before generating an image, default is auto; auto: leave unspecified and let the model decide; min: minimal reasoning, fastest generation; medium: balanced reasoning; high: deep reasoning Note: Reasoning tokens are billed as text output\",\"enum\":[\"auto\",\"min\",\"medium\",\"high\"],\"default\":\"auto\"}}}},\"inputSchema\":{\"schema\":{\"type\":\"object\",\"required\":[\"prompt\"],\"properties\":{\"prompt\":{\"type\":\"string\",\"description\":\"Prompt describing the image to generate or how to edit an input image, up to `4000` tokens\",\"example\":\"A cat playing in the grass\"},\"size\":{\"type\":\"string\",\"description\":\"Aspect ratio of the generated image, default is `auto`\",\"enum\":[\"auto\",\"1:1\",\"1:4\",\"4:1\",\"1:8\",\"8:1\",\"2:3\",\"3:2\",\"3:4\",\"4:3\",\"4:5\",\"5:4\",\"9:16\",\"16:9\",\"21:9\"],\"default\":\"auto\"},\"quality\":{\"type\":\"string\",\"description\":\"Output image resolution, default is `2K`\\n\\n**Note:**\\n- Prices vary by resolution. Output images are billed at the selected resolution. Setting this parameter explicitly is recommended\",\"enum\":[\"1K\",\"2K\",\"4K\"],\"default\":\"2K\"},\"image_urls\":{\"type\":\"array\",\"description\":\"List of reference image URLs for image to image generation, image editing, and multi-image composition\\n\\n**Note:**\\n- Up to `14` input images per request\\n- Image size: no more than `20MB`\\n- Supported file formats: `.jpeg`, `.jpg`, `.png`, `.webp`\\n- Image URLs must be directly accessible by the server or trigger a direct image download when accessed (such URLs typically end in an image extension such as `.png` or `.jpg`)\\n- Input images are billed per image\",\"items\":{\"type\":\"string\",\"format\":\"uri\"},\"maxItems\":14,\"example\":[\"https://example.com/image1.png\",\"https://example.com/image2.png\"]},\"model_params\":{\"type\":\"object\",\"description\":\"Model extension parameters\",\"properties\":{\"web_search\":{\"type\":\"boolean\",\"description\":\"Whether to enable web search, default is `false`. When enabled, the model searches for the latest information on the web before generating the image\\n\\n**Note:**\\n- Billed by the actual number of searches performed by the model. A single request may involve multiple searches\",\"default\":false,\"example\":true},\"image_search\":{\"type\":\"boolean\",\"description\":\"Whether to enable image search, default is `false`. When enabled, the model retrieves images from the web as visual references before generating the image\\n\\n**Note:**\\n- Billed by the actual number of searches performed by the model. A single request may involve multiple searches\",\"default\":false,\"example\":true},\"thinking_level\":{\"type\":\"string\",\"description\":\"Reasoning level controlling how deeply the model reasons before generating an image, default is `auto`\\n\\n- `auto`: leave unspecified and let the model decide\\n- `min`: minimal reasoning, fastest generation\\n- `medium`: balanced reasoning\\n- `high`: deep reasoning\\n\\n**Note:**\\n- Reasoning tokens are billed as text output\",\"enum\":[\"auto\",\"min\",\"medium\",\"high\"],\"default\":\"auto\",\"example\":\"medium\"}}}}},\"unresolved_refs\":false,\"dialect\":\"3.1.0\"},\"responseSchema\":{\"schema\":{\"$ref\":\"#/$defs/ImageGenerationResponse\",\"$defs\":{\"ImageGenerationResponse\":{\"type\":\"object\",\"properties\":{\"created\":{\"type\":\"integer\",\"description\":\"Task creation timestamp\",\"example\":1757165031},\"id\":{\"type\":\"string\",\"description\":\"Task ID\",\"example\":\"task-unified-1757165031-uyujaw3d\"},\"model\":{\"type\":\"string\",\"description\":\"Actual model name used\",\"example\":\"gemini-nano-banana-2.1\"},\"object\":{\"type\":\"string\",\"enum\":[\"image.generation.task\"],\"description\":\"Specific task type\"},\"progress\":{\"type\":\"integer\",\"description\":\"Task progress percentage (0-100)\",\"minimum\":0,\"maximum\":100,\"example\":0},\"status\":{\"type\":\"string\",\"description\":\"Task status\",\"enum\":[\"pending\",\"processing\",\"completed\",\"failed\"],\"example\":\"pending\"},\"task_info\":{\"$ref\":\"#/$defs/TaskInfo\",\"description\":\"Asynchronous task information\"},\"type\":{\"type\":\"string\",\"enum\":[\"text\",\"image\",\"audio\",\"video\"],\"description\":\"Task output type\",\"example\":\"image\"},\"usage\":{\"$ref\":\"#/$defs/Usage\",\"description\":\"Usage and billing information\"}}},\"TaskInfo\":{\"type\":\"object\",\"properties\":{\"estimated_time\":{\"type\":\"integer\",\"description\":\"Estimated completion time (seconds)\",\"minimum\":0,\"example\":45}}},\"Usage\":{\"type\":\"object\",\"description\":\"Usage and billing information\",\"properties\":{\"billing_rule\":{\"type\":\"string\",\"description\":\"Billing rule\",\"enum\":[\"per_call\",\"per_image\",\"per_token\",\"per_second\"],\"example\":\"per_image\"},\"credits_reserved\":{\"type\":\"number\",\"description\":\"Estimated credits consumed\",\"minimum\":0,\"example\":3.0845},\"user_group\":{\"type\":\"string\",\"description\":\"Billing group the user belongs to\",\"example\":\"default\"}}}}},\"unresolved_refs\":false,\"dialect\":\"3.1.0\"},\"example\":{\"prompt\":\"A cat playing on the grass\",\"size\":\"16:9\",\"quality\":\"2K\"}}}}";
@@ -3,6 +3,7 @@
3
3
  import { gatewayAuthHeaders } from '../config.js';
4
4
  import { currentRequestCredentials } from '../request-context.js';
5
5
  import { classifyGatewayError, formatGatewayError } from './error-handler.js';
6
+ import { parseBatchTasks, parseTaskReceipt, parseTaskResponse } from './task-response.js';
6
7
  import { DEFAULT_READ_TIMEOUT_MS, DEFAULT_SUBMIT_TIMEOUT_MS, MAX_RETRY_DELAY_MS, PaidRequestOutcomeUnknownError, RequestTimeoutError, SubmissionNotStartedError, evoHeaders, fetchWithTimeout, newRunId, parseRetryAfter, readJsonBody, responseRequestId, timeoutFromEnv, } from './http-policy.js';
7
8
  // --- Error class for HTTP-level failures ---
8
9
  export class ApiHttpError extends Error {
@@ -139,11 +140,10 @@ export async function submitTask(config, options) {
139
140
  tool: options.tool,
140
141
  idempotencyKey,
141
142
  }), 1, 500);
142
- if (!data.request_id && requestId)
143
- data.request_id = requestId;
143
+ const receipt = parseTaskReceipt(data, requestId);
144
144
  if (headers.get('idempotency-replayed') === 'true')
145
- data.idempotency_replayed = true;
146
- return data;
145
+ receipt.idempotency_replayed = true;
146
+ return receipt;
147
147
  }
148
148
  /** Read-only, credential-specific availability; never cached across accounts. */
149
149
  export async function getAvailableModelIds(config) {
@@ -170,19 +170,17 @@ export async function apiRequest(config, options) {
170
170
  /** One task (GET /v1/tasks/{id}). Unfinished tasks sync with the provider on every read, so callers pace themselves. */
171
171
  export async function queryTask(config, taskId, tool = 'get_task') {
172
172
  const { data, requestId } = await withRetry(() => rawRequest(config, { method: 'GET', path: `/v1/tasks/${encodeURIComponent(taskId)}`, tool }), 2, 1500);
173
- if (!data.request_id && requestId)
174
- data.request_id = requestId;
175
- return data;
173
+ return parseTaskResponse(data, taskId, requestId);
176
174
  }
177
175
  /** Up to 50 tasks in one call (POST /v1/tasks/batch); unknown or foreign IDs are simply absent. */
178
176
  export async function queryTasks(config, taskIds, tool = 'list_tasks') {
179
- const { data } = await withRetry(() => rawRequest(config, {
177
+ const { data, requestId } = await withRetry(() => rawRequest(config, {
180
178
  method: 'POST',
181
179
  path: '/v1/tasks/batch',
182
180
  body: { task_ids: taskIds },
183
181
  tool,
184
182
  }), 2, 1500);
185
- return Array.isArray(data.data) ? data.data : [];
183
+ return parseBatchTasks(data, taskIds, requestId);
186
184
  }
187
185
  /** The account's recent tasks, newest first (GET /v1/tasks). Items carry no result links. */
188
186
  export async function listTasks(config, query, tool = 'list_tasks', options = {}) {
@@ -196,7 +194,7 @@ export async function listTasks(config, query, tool = 'list_tasks', options = {}
196
194
  params.set('page', String(query.page ?? 1));
197
195
  params.set('page_size', String(query.pageSize ?? 20));
198
196
  const { data } = await withRetry(() => rawRequest(config, { method: 'GET', path: `/v1/tasks?${params}`, tool, timeoutMs: options.timeoutMs }), options.retries ?? 2, 1500);
199
- if (!Array.isArray(data.data) || !Number.isSafeInteger(data.total) || data.total < 0) {
197
+ if (!data || !Array.isArray(data.data) || !Number.isSafeInteger(data.total) || data.total < 0) {
200
198
  throw new ApiHttpError(502, 'The task list could not be verified. Retry this read; do not infer zero usage or submit another task.');
201
199
  }
202
200
  if ((data.page !== undefined && data.page !== (query.page ?? 1))
@@ -10,6 +10,7 @@ export const DEFAULT_SUBMIT_TIMEOUT_MS = 30_000;
10
10
  export const MAX_RETRY_DELAY_MS = 30_000;
11
11
  /** Public site for console links in errors and results. */
12
12
  export const EVOLINK_SITE = 'https://evolink.ai';
13
+ export const DASHBOARD_URL = `${EVOLINK_SITE}/dashboard`;
13
14
  export const TOP_UP_URL = `${EVOLINK_SITE}/dashboard/credits`;
14
15
  export const API_KEYS_URL = `${EVOLINK_SITE}/dashboard/keys`;
15
16
  /**
@@ -72,7 +73,7 @@ export function siteUrl(pathOrUrl, fallback) {
72
73
  return fallback;
73
74
  const url = new URL(value, EVOLINK_SITE);
74
75
  if (url.origin !== EVOLINK_SITE || url.username || url.password || url.hash
75
- || !['/dashboard/credits', '/dashboard/keys', '/dashboard/mcp'].includes(url.pathname))
76
+ || !['/dashboard', '/dashboard/credits', '/dashboard/keys', '/dashboard/mcp'].includes(url.pathname))
76
77
  return fallback;
77
78
  // Only the documented console tab is accepted. Tracking is added locally.
78
79
  if ([...url.searchParams].some(([key, v]) => key !== 'tab' || v !== 'mcp'))
@@ -4,6 +4,8 @@ import { createHash } from 'node:crypto';
4
4
  import { z } from 'zod';
5
5
  import { requestAccountQuote } from './api-client.js';
6
6
  import { getPricingRules, PricingMoney } from './pricing-rules-client.js';
7
+ import { isSeedanceGeneration } from './seedance-input.js';
8
+ import { searchUsage } from './search-usage.js';
7
9
  const decimal = z.string().max(64).regex(/^(?:0|[1-9]\d*)(?:\.\d+)?$/);
8
10
  const identifier = z.string().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/);
9
11
  const rational = z.string().max(128).regex(/^(?:0|[1-9]\d*)(?:\.\d+|\/[1-9]\d*)?$/);
@@ -57,9 +59,13 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
57
59
  fail('unsupported_quote_parameter', `The pricing policy does not declare parameter ${name}.`, name);
58
60
  }
59
61
  const parameters = {};
62
+ const searches = searchUsage(entry, input);
60
63
  for (const [name, p] of declared) {
64
+ const search = searches.find(item => item.parameter === name);
61
65
  // A declared duration and duration_seconds have different meanings (smart duration).
62
- const generationNames = [name, ...(aliases[name] ?? []).filter(alias => !declared.has(alias))];
66
+ // Video edit's duration=-1 is an operation setting, never expected output seconds.
67
+ const expectedEditDuration = name === 'duration_seconds' && entry.id === 'seedance-2.5-video-edit' && isSeedanceGeneration(entry);
68
+ const generationNames = [name, ...(aliases[name] ?? []).filter(alias => !declared.has(alias) && !(expectedEditDuration && alias === 'duration'))];
63
69
  const supplied = generationNames.filter(key => input[key] !== undefined).map(key => input[key]);
64
70
  if (supplied.some(value => String(value) !== String(supplied[0]))) {
65
71
  fail('conflicting_quote_parameter', `Conflicting generation values for ${name}.`, name);
@@ -112,7 +118,11 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
112
118
  const references = Array.isArray(input.video_urls) && input.video_urls.length > 0
113
119
  || typeof input.video_url === 'string' && input.video_url.trim().length > 0
114
120
  || typeof input.source_task_id === 'string' && input.source_task_id.trim().length > 0;
115
- if (value === undefined && measured.test(name) && (p.required || references || /tokens$/.test(name) || (name === 'search_count' && input.web_search === true) || p.default === undefined)) {
121
+ // Zero is an illustration for enabled search, never measured usage or an execution limit.
122
+ // The rules evaluator separately records the missing actual/expected search count.
123
+ if (value === undefined && search?.enabled && allowMissingUsage)
124
+ value = '0';
125
+ if (value === undefined && measured.test(name) && (p.required || references || /tokens$/.test(name) || search?.enabled || (name === 'search_count' && input.web_search === true) || p.default === undefined)) {
116
126
  if (allowMissingUsage)
117
127
  continue;
118
128
  fail('quote_usage_required', `Provide measured or expected usage for ${name} in pricing_parameters.`, name);
@@ -155,6 +165,10 @@ export function prepareQuoteParameters(rule, entry, input, pricingParameters = {
155
165
  const allowed = p.values ?? p.enum;
156
166
  if (allowed && !allowed.some(candidate => String(candidate) === String(value)))
157
167
  fail('invalid_quote_parameter', `Pricing parameter ${name} is not an allowed value.`, name);
168
+ if (search && !search.enabled
169
+ && compareDecimal(String(value), '0') !== 0) {
170
+ fail('conflicting_quote_parameter', `${name} must be zero when ${search.input_parameter} is not enabled.`, name);
171
+ }
158
172
  parameters[name] = value;
159
173
  }
160
174
  return parameters;
@@ -3,6 +3,8 @@
3
3
  import { z } from 'zod';
4
4
  import { getPricingRules } from './pricing-rules-client.js';
5
5
  import { QuoteError, prepareQuoteParameters, quoteRequestHash } from './pricing-quote-client.js';
6
+ import { prepareSeedanceInput } from './seedance-input.js';
7
+ import { searchUsage } from './search-usage.js';
6
8
  /**
7
9
  * How long an approval from estimate_cost may be passed to generate_*. The rules' own
8
10
  * `fresh_until` is a short refresh window (minutes); people confirming a price in a chat
@@ -160,11 +162,28 @@ export function calculateRulesEstimate(body, entry, input, options = {}) {
160
162
  if (!rule || rule.model_id !== entry.id.toLowerCase() || rule.modality !== entry.kind || rule.policy_source !== 'published' || rule.pricing_status !== 'available') {
161
163
  fail('pricing_rules_unavailable', 'This model has no available published media pricing policy.');
162
164
  }
163
- const params = prepareQuoteParameters(rule, entry, input, options.pricingParameters, options.mediaSeconds, true);
165
+ const prepared = prepareSeedanceInput(entry, input);
166
+ if (prepared.errors.length)
167
+ throw new QuoteError('invalid_quote_parameter', `${prepared.errors[0].param} ${prepared.errors[0].problem}`, prepared.errors[0].param);
168
+ const effectiveInput = prepared.input;
169
+ const params = prepareQuoteParameters(rule, entry, effectiveInput, options.pricingParameters, options.mediaSeconds, true);
164
170
  const declared = new Set((rule.parameters ?? []).map(p => p.name)), ids = new Set();
165
171
  const components = [];
166
172
  let total = 0n;
167
173
  const missing = new Set();
174
+ const searchCharges = searchUsage(entry, effectiveInput).filter(search => search.enabled).map(search => {
175
+ const component = rule.components.find(item => item.role === search.role);
176
+ if (!declared.has(search.parameter) || !component || component.pricing_status !== 'available' || component.unit !== 'search'
177
+ || component.billing_unit_size !== 1 || component.tiers.length) {
178
+ fail('search_pricing_unavailable', 'The enabled search unit price could not be verified. Refresh pricing before generation.');
179
+ }
180
+ const expected = options.pricingParameters?.[search.parameter] !== undefined || effectiveInput[search.parameter] !== undefined;
181
+ if (!expected)
182
+ missing.add(search.parameter);
183
+ return { role: search.role, input_parameter: search.input_parameter, usage_parameter: search.parameter,
184
+ assumed_count: String(params[search.parameter]), assumption: expected ? 'expected_usage' : 'zero_searches',
185
+ actual_count_known: false, unit: 'search', unit_price_amounts: amountsForUC(component.rate.uc) };
186
+ });
168
187
  for (const c of rule.components) {
169
188
  if (ids.has(c.id) || !c.quantity_rule || !c.rounding)
170
189
  fail('invalid_pricing_expression', 'The pricing rule is incomplete or has duplicate components.');
@@ -209,7 +228,7 @@ export function calculateRulesEstimate(body, entry, input, options = {}) {
209
228
  }
210
229
  if (total > BigInt(Number.MAX_SAFE_INTEGER))
211
230
  fail('invalid_pricing_expression', 'The estimated charge exceeds its supported range.');
212
- const amounts = amountsForUC(String(total)), requestHash = quoteRequestHash(entry.id, input, options.mediaSeconds, options.pricingParameters);
231
+ const amounts = amountsForUC(String(total)), requestHash = quoteRequestHash(entry.id, effectiveInput, options.mediaSeconds, options.pricingParameters);
213
232
  const approval = { source: 'pricing_rules', price_scope: 'public_default', model_id: entry.id,
214
233
  request_hash: requestHash, total_uc: amounts.uc, expires_at: new Date(Date.now() + APPROVAL_TTL_MS).toISOString(),
215
234
  fingerprint: quoteRequestHash(entry.id, { rules: economicRules(rule), parameters: params,
@@ -220,6 +239,16 @@ export function calculateRulesEstimate(body, entry, input, options = {}) {
220
239
  ...(missing.size ? { uncheckable_reason: 'usage' } : {}),
221
240
  possible_extras: [...missing].map(name => `Additional charge depends on ${name}; supply expected or measured usage in pricing_parameters.`), notes: ['Public default prices; account discounts are not included.',
222
241
  'Confirm the estimated cost before generation. Actual billed usage and final charges may differ.'] };
242
+ if (searchCharges.length) {
243
+ estimate.search_charges = searchCharges;
244
+ for (const search of searchCharges) {
245
+ const label = search.role === 'web_search' ? 'Web search' : 'Image search';
246
+ const assumption = search.assumption === 'zero_searches'
247
+ ? `The displayed subtotal assumes 0 searches and excludes ${label.toLowerCase()} fees.`
248
+ : `${search.usage_parameter}=${search.assumed_count} is expected usage, not a limit; actual searches and final charges may differ, including when the expected count is zero.`;
249
+ estimate.notes.push(`${label} is enabled. ${assumption} Each actual search costs ${search.unit_price_amounts.credits} credits (approximately $${search.unit_price_amounts.usd}) at public default rates. A single task may perform no searches or multiple searches. Actual search count and search fees are unknown before generation and depend on the task and the model's search strategy.`);
250
+ }
251
+ }
223
252
  return { approval, estimate, amounts, components, parameters: params, rule };
224
253
  }
225
254
  export async function createRulesEstimate(entry, input, options = {}) {
@@ -25,7 +25,7 @@ export function publicText(value) {
25
25
  try {
26
26
  const url = new URL(candidate);
27
27
  if (url.origin === 'https://evolink.ai' && !url.username && !url.password && !url.hash
28
- && ['/dashboard/credits', '/dashboard/keys', '/dashboard/mcp'].includes(url.pathname)
28
+ && ['/dashboard', '/dashboard/credits', '/dashboard/keys', '/dashboard/mcp'].includes(url.pathname)
29
29
  && [...url.searchParams].every(([key, v]) => key.startsWith('utm_') && /^[a-z0-9_-]{1,80}$/i.test(v) || key === 'tab' && v === 'mcp'))
30
30
  return value;
31
31
  // Official documentation pages, which gateway task errors link to (for example the upload guide).
@@ -0,0 +1,22 @@
1
+ // Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
2
+ // Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
3
+ /** Reviewed media contracts only; a pricing role alone does not prove search support. */
4
+ export function searchUsage(entry, input) {
5
+ const image = entry.kind === 'image' && entry.spec?.path === '/v1/images/generations';
6
+ const video = entry.kind === 'video' && entry.spec?.path === '/v1/videos/generations';
7
+ const seedream = image && entry.id === 'doubao-seedream-5.0-lite';
8
+ const gemini = image && ['gemini-3-pro-image-preview', 'gemini-3.1-flash-image-preview', 'gemini-nano-banana-2.1'].includes(entry.id ?? '');
9
+ const seedance = video && ['seedance-2.0-text-to-video', 'seedance-2.0-fast-text-to-video', 'seedance-2.5-text-to-video'].includes(entry.id ?? '');
10
+ if (!seedream && !gemini && !seedance)
11
+ return [];
12
+ const params = input.model_params && typeof input.model_params === 'object' && !Array.isArray(input.model_params)
13
+ ? input.model_params : {};
14
+ const web = seedream ? Array.isArray(params.tools) && params.tools.some(tool => tool && typeof tool === 'object'
15
+ && !Array.isArray(tool) && tool.type === 'web_search') : params.web_search === true;
16
+ const result = [{ role: 'web_search', parameter: 'search_count',
17
+ input_parameter: seedream ? 'model_params.tools' : 'model_params.web_search', enabled: web }];
18
+ if (gemini && entry.id !== 'gemini-3-pro-image-preview')
19
+ result.push({ role: 'image_search', parameter: 'image_search_count',
20
+ input_parameter: 'model_params.image_search', enabled: params.image_search === true });
21
+ return result;
22
+ }