@evolinkai/cli 0.10.3 → 0.12.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 (30) hide show
  1. package/README.md +31 -4
  2. package/package.json +1 -1
  3. package/skills/evolink-cli/SKILL.md +14 -4
  4. package/skills/evolink-cli/references/usage-and-budget.md +19 -2
  5. package/src/api.mjs +8 -6
  6. package/src/auth.mjs +14 -3
  7. package/src/cli.mjs +23 -7
  8. package/src/help.mjs +1 -1
  9. package/src/media.mjs +161 -19
  10. package/src/platform/core/src/data/model-constraints.js +27 -0
  11. package/src/platform/core/src/data/model-params.js +8 -1
  12. package/src/platform/core/src/data/model-params.overrides.generated.js +4 -0
  13. package/src/platform/core/src/services/api-client.js +64 -28
  14. package/src/platform/core/src/services/http-policy.js +41 -12
  15. package/src/platform/core/src/services/pricing-quote-client.js +16 -2
  16. package/src/platform/core/src/services/pricing-rules-estimate.js +31 -2
  17. package/src/platform/core/src/services/public-error.js +1 -1
  18. package/src/platform/core/src/services/search-usage.js +22 -0
  19. package/src/platform/core/src/services/seedance-input.js +75 -0
  20. package/src/platform/core/src/services/task-response.js +176 -0
  21. package/src/platform/core/src/tool-guidance.js +3 -1
  22. package/src/platform/core/src/tools/estimate-cost.js +12 -2
  23. package/src/platform/core/src/tools/generate.js +33 -11
  24. package/src/platform/core/src/tools/get-model.js +8 -3
  25. package/src/platform/core/src/tools/get-task.js +40 -15
  26. package/src/platform/core/src/tools/list-tasks.js +108 -31
  27. package/src/platform/core/src/tools/shared.js +32 -2
  28. package/src/platform/core/src/tools/task-format.js +85 -18
  29. package/src/platform/core/src/version.js +1 -1
  30. package/src/platform/source.json +45 -37
@@ -1,6 +1,7 @@
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 { randomUUID } from 'node:crypto';
4
+ import { performance } from 'node:perf_hooks';
4
5
  import { currentRequestCredentials, currentClientName } from '../request-context.js';
5
6
  import { MCP_VERSION } from '../version.js';
6
7
  export const DEFAULT_READ_TIMEOUT_MS = 15_000;
@@ -10,6 +11,7 @@ export const DEFAULT_SUBMIT_TIMEOUT_MS = 30_000;
10
11
  export const MAX_RETRY_DELAY_MS = 30_000;
11
12
  /** Public site for console links in errors and results. */
12
13
  export const EVOLINK_SITE = 'https://evolink.ai';
14
+ export const DASHBOARD_URL = `${EVOLINK_SITE}/dashboard`;
13
15
  export const TOP_UP_URL = `${EVOLINK_SITE}/dashboard/credits`;
14
16
  export const API_KEYS_URL = `${EVOLINK_SITE}/dashboard/keys`;
15
17
  /**
@@ -31,6 +33,26 @@ export class RequestTimeoutError extends Error {
31
33
  this.name = 'RequestTimeoutError';
32
34
  }
33
35
  }
36
+ /** Monotonic milliseconds for wait deadlines; unlike Date.now(), system clock changes do not move them. */
37
+ export function monotonicNow() {
38
+ return performance.now();
39
+ }
40
+ /** Milliseconds left before a monotonic deadline: 0 once it has passed, Infinity without one. */
41
+ export function remainingMs(deadline) {
42
+ return deadline === undefined ? Infinity : Math.max(0, deadline - monotonicNow());
43
+ }
44
+ /** A task read is not started with less than this left in its wait. */
45
+ export const MIN_READ_MS = 100;
46
+ /** The wait ran out before a task read could be verified. The task itself is not affected. */
47
+ export class TaskQueryTimeoutError extends Error {
48
+ cause;
49
+ code = 'task_query_timeout';
50
+ constructor(cause) {
51
+ super('The wait limit was reached before the latest task status could be verified. Stopping this wait does not cancel the task.');
52
+ this.cause = cause;
53
+ this.name = 'TaskQueryTimeoutError';
54
+ }
55
+ }
34
56
  export class SubmissionNotStartedError extends Error {
35
57
  cause;
36
58
  constructor(cause) {
@@ -72,7 +94,7 @@ export function siteUrl(pathOrUrl, fallback) {
72
94
  return fallback;
73
95
  const url = new URL(value, EVOLINK_SITE);
74
96
  if (url.origin !== EVOLINK_SITE || url.username || url.password || url.hash
75
- || !['/dashboard/credits', '/dashboard/keys', '/dashboard/mcp'].includes(url.pathname))
97
+ || !['/dashboard', '/dashboard/credits', '/dashboard/keys', '/dashboard/mcp'].includes(url.pathname))
76
98
  return fallback;
77
99
  // Only the documented console tab is accepted. Tracking is added locally.
78
100
  if ([...url.searchParams].some(([key, v]) => key !== 'tab' || v !== 'mcp'))
@@ -93,17 +115,21 @@ export function timeoutFromEnv(name, fallback) {
93
115
  }
94
116
  return parsed;
95
117
  }
96
- export function parseRetryAfter(value, nowMs = Date.now()) {
118
+ /** The pause the server asked for, uncapped: a task wait ends instead of retrying before it. */
119
+ export function requestedRetryAfterMs(value, nowMs = Date.now()) {
97
120
  if (!value)
98
121
  return undefined;
99
122
  const seconds = Number(value.trim());
100
- if (Number.isFinite(seconds) && seconds >= 0) {
101
- return Math.min(Math.ceil(seconds * 1000), MAX_RETRY_DELAY_MS);
102
- }
123
+ if (Number.isFinite(seconds) && seconds >= 0)
124
+ return Math.ceil(seconds * 1000);
103
125
  const dateMs = Date.parse(value);
104
126
  if (!Number.isFinite(dateMs))
105
127
  return undefined;
106
- return Math.min(Math.max(0, dateMs - nowMs), MAX_RETRY_DELAY_MS);
128
+ return Math.max(0, dateMs - nowMs);
129
+ }
130
+ export function parseRetryAfter(value, nowMs = Date.now()) {
131
+ const requested = requestedRetryAfterMs(value, nowMs);
132
+ return requested === undefined ? undefined : Math.min(requested, MAX_RETRY_DELAY_MS);
107
133
  }
108
134
  export function responseRequestId(headers) {
109
135
  return headers.get('x-request-id')?.trim()
@@ -142,8 +168,8 @@ export async function fetchWithTimeout(url, init, timeoutMs, fetchImpl) {
142
168
  }
143
169
  }
144
170
  /** Bound body consumption as well as response headers. Cancelling a reader also closes stalled streams. */
145
- export async function readJsonBody(response, timeoutMs = DEFAULT_READ_TIMEOUT_MS) {
146
- const signal = currentRequestCredentials()?.http?.signal;
171
+ export async function readJsonBody(response, timeoutMs = DEFAULT_READ_TIMEOUT_MS, operationSignal) {
172
+ const signals = [currentRequestCredentials()?.http?.signal, operationSignal].filter((signal) => !!signal);
147
173
  const reader = response.body?.getReader();
148
174
  let timer;
149
175
  let abort;
@@ -164,9 +190,11 @@ export async function readJsonBody(response, timeoutMs = DEFAULT_READ_TIMEOUT_MS
164
190
  const stop = (error) => { reject(error); void reader?.cancel().catch(() => undefined); };
165
191
  timer = setTimeout(() => stop(new RequestTimeoutError(timeoutMs)), timeoutMs);
166
192
  abort = () => stop(new Error('Request interrupted during response read'));
167
- signal?.addEventListener('abort', abort, { once: true });
168
- if (signal?.aborted)
169
- abort();
193
+ for (const signal of signals) {
194
+ signal.addEventListener('abort', abort, { once: true });
195
+ if (signal.aborted)
196
+ abort();
197
+ }
170
198
  })]);
171
199
  if (!body)
172
200
  return {};
@@ -180,7 +208,8 @@ export async function readJsonBody(response, timeoutMs = DEFAULT_READ_TIMEOUT_MS
180
208
  finally {
181
209
  clearTimeout(timer);
182
210
  if (abort)
183
- signal?.removeEventListener('abort', abort);
211
+ for (const signal of signals)
212
+ signal.removeEventListener('abort', abort);
184
213
  reader?.releaseLock();
185
214
  }
186
215
  }
@@ -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
+ }
@@ -0,0 +1,75 @@
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
+ const GENERATION_MODELS = new Set([
4
+ 'seedance-2.5-text-to-video',
5
+ 'seedance-2.5-image-to-video',
6
+ 'seedance-2.5-reference-to-video',
7
+ 'seedance-2.5-video-edit',
8
+ 'seedance-2.5-video-extend',
9
+ ]);
10
+ /** Match the resolved catalog identity, never a borrowed documentation alias. */
11
+ export function isSeedanceGeneration(entry) {
12
+ return entry.id !== undefined && GENERATION_MODELS.has(entry.id)
13
+ && entry.kind === 'video' && entry.spec?.path === '/v1/videos/generations';
14
+ }
15
+ export function isSeedanceSearch(entry) {
16
+ return isSeedanceGeneration(entry) && entry.id === 'seedance-2.5-text-to-video';
17
+ }
18
+ export function seedanceSearchEnabled(entry, input) {
19
+ const params = input.model_params;
20
+ return isSeedanceSearch(entry) && !!params && typeof params === 'object' && !Array.isArray(params)
21
+ && params.web_search === true;
22
+ }
23
+ /** Only reviewed gateway checks are blocking. Documentation-only differences warn. */
24
+ export function prepareSeedanceInput(entry, input) {
25
+ const applies = isSeedanceGeneration(entry);
26
+ const errors = [], warnings = [];
27
+ const defaults = [];
28
+ if (!applies)
29
+ return { applies, input, errors, warnings, defaults };
30
+ // Do not mutate the shared catalog spec, caller input, or nested references.
31
+ const effective = { ...input };
32
+ const params = input.model_params && typeof input.model_params === 'object' && !Array.isArray(input.model_params)
33
+ ? input.model_params : undefined;
34
+ if (input.web_search !== undefined)
35
+ errors.push({ param: 'web_search', problem: 'must be provided as model_params.web_search for this model.' });
36
+ if (params?.draft !== undefined)
37
+ errors.push({ param: 'model_params.draft', problem: 'must be provided as the top-level draft field.' });
38
+ if (params?.web_search !== undefined && typeof params.web_search !== 'boolean') {
39
+ errors.push({ param: 'model_params.web_search', problem: 'must be a boolean.' });
40
+ }
41
+ if (input.draft === true) {
42
+ if (input.quality === undefined) {
43
+ effective.quality = '480p';
44
+ defaults.push({ param: 'quality', value: '480p', reason: 'draft=true requires 480p' });
45
+ }
46
+ else if (input.quality !== '480p') {
47
+ errors.push({ param: 'quality', problem: 'must be 480p when draft is true; omit quality to use the 480p draft default.' });
48
+ }
49
+ }
50
+ if (typeof input.duration === 'number' && (input.duration === 0 || input.duration < -1)) {
51
+ errors.push({ param: 'duration', problem: 'must be an integer between 4 and 30 seconds, or -1 for automatic duration.' });
52
+ }
53
+ else if (entry.id !== 'seedance-2.5-video-edit' && typeof input.duration === 'number' && Number.isInteger(input.duration)
54
+ && input.duration !== -1 && (input.duration < 4 || input.duration > 30)) {
55
+ warnings.push({ param: 'duration', problem: 'is outside the documented 4–30 seconds or -1; acceptance by the service has not been verified.' });
56
+ }
57
+ if (seedanceSearchEnabled(entry, input) && input.content_filter === false) {
58
+ warnings.push({ param: 'content_filter', problem: 'false with model_params.web_search=true is documented as unsupported; service acceptance has not been verified.' });
59
+ }
60
+ return { applies, input: effective, errors, warnings, defaults };
61
+ }
62
+ /** A fresh object for the resolved model; never augment the shared docs index. */
63
+ export function seedanceInputRules(entry) {
64
+ if (!isSeedanceGeneration(entry))
65
+ return undefined;
66
+ return {
67
+ model: entry.id, endpoint: entry.spec.path,
68
+ conditional_defaults: [{ when: { draft: true }, parameter: 'quality', value: '480p' }],
69
+ blocking: ['draft=true requires quality=480p or omitted', 'duration=0 and duration<-1 are rejected',
70
+ 'draft must be top-level', 'model_params.web_search must be boolean when provided'],
71
+ warnings_only: ['Other unverified duration boundaries and search/content_filter combinations do not add blocking checks.'],
72
+ ...(entry.id === 'seedance-2.5-video-edit' ? { duration_usage: 'duration=-1 selects video editing; supply expected output seconds separately as pricing_parameters.duration_seconds, not as input.duration.' } : {}),
73
+ ...(isSeedanceSearch(entry) ? { search_usage: 'Search defaults to off. When model_params.web_search=true, missing search_count produces a partial subtotal assuming zero searches, with separate per-search rates. Expected counts are not execution limits; one task may search multiple times.' } : {}),
74
+ };
75
+ }
@@ -0,0 +1,176 @@
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
+ import { publicIdentifier, publicNumber, publicText } from './public-error.js';
4
+ import { publicTaskMessage } from './error-handler.js';
5
+ const STATUSES = new Set(['pending', 'processing', 'completed', 'failed', 'cancelled']);
6
+ const taskIdentifier = (value) => typeof value === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(value);
7
+ const record = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
8
+ /** A failed read is not a failed generation or evidence about its charge. */
9
+ export class TaskResponseError extends Error {
10
+ code;
11
+ taskId;
12
+ requestId;
13
+ rawStatus;
14
+ constructor(code, taskId, requestId, rawStatus) {
15
+ super(code === 'task_identity_mismatch' ? 'The response did not match the requested task.'
16
+ : code === 'task_status_unknown' ? 'The task status could not be verified.' : 'The task response could not be verified.');
17
+ this.code = code;
18
+ this.taskId = taskId;
19
+ this.requestId = requestId;
20
+ this.rawStatus = rawStatus;
21
+ this.name = 'TaskResponseError';
22
+ }
23
+ }
24
+ const outputSchema = {
25
+ voice: 'id', voice_id: 'id', persona_id: 'id', result_id: 'id', id: 'id', title: 'text', tags: 'text',
26
+ duration: 'number', seed: 'number', video_url: 'url', image_url: 'url', audio_url: 'url', stream_audio_url: 'url',
27
+ };
28
+ const schema = {
29
+ model: 'text', object: 'text', type: 'text', created: 'number', progress: 'number', duration: 'number', video_duration: 'number',
30
+ task_info: { can_cancel: 'boolean', estimated_time: 'number', video_duration: 'number' },
31
+ usage: { billing_rule: 'text', credits_reserved: 'number', credits_used: 'number',
32
+ cost: { credits: 'number', usd: 'number', cny: 'number' }, user_group: 'text' },
33
+ billing: { charge_status: ['unknown', 'reserved', 'charged', 'released'],
34
+ refund_status: ['unknown', 'not_required', 'pending', 'completed', 'failed'],
35
+ refund_scope: ['account_balance'], limit_restoration: ['unknown'], reserved_credits: 'number', charged_credits: 'number',
36
+ refunded_credits: 'number', refunded_at: 'text' },
37
+ error: { code: 'text', message: 'task_message', type: 'text', suggestion: 'text' }, request_id: 'id',
38
+ };
39
+ function url(value) {
40
+ if (typeof value !== 'string' || value.length > 16384)
41
+ return;
42
+ try {
43
+ const parsed = new URL(value);
44
+ if (['http:', 'https:'].includes(parsed.protocol) && !parsed.username && !parsed.password)
45
+ return value;
46
+ }
47
+ catch { /* Invalid optional URLs are omitted without fetching them. */ }
48
+ }
49
+ function normalize(value, rule, path, warnings) {
50
+ if (value === undefined)
51
+ return;
52
+ let result;
53
+ if (rule === 'text')
54
+ result = typeof value === 'string' ? publicText(value).slice(0, 2000) : undefined;
55
+ else if (rule === 'task_message')
56
+ result = publicTaskMessage(value);
57
+ else if (rule === 'id')
58
+ result = publicIdentifier(value);
59
+ else if (rule === 'number')
60
+ result = publicNumber(value);
61
+ else if (rule === 'boolean')
62
+ result = typeof value === 'boolean' ? value : undefined;
63
+ else if (rule === 'url')
64
+ result = url(value);
65
+ else if (Array.isArray(rule))
66
+ result = typeof value === 'string' && rule.includes(value) ? value : undefined;
67
+ else if (record(value)) {
68
+ const fields = {};
69
+ for (const [key, child] of Object.entries(rule)) {
70
+ const parsed = normalize(value[key], child, `${path}.${key}`, warnings);
71
+ if (parsed !== undefined)
72
+ fields[key] = parsed;
73
+ }
74
+ result = fields;
75
+ }
76
+ if (result === undefined)
77
+ warnings.add(path);
78
+ return result;
79
+ }
80
+ /** Project known public fields; model-specific omissions do not invalidate a task. */
81
+ export function parseTaskReceipt(value, requestId) {
82
+ if (!record(value) || !taskIdentifier(value.id))
83
+ throw new TaskResponseError('task_response_invalid', undefined, requestId);
84
+ const warnings = new Set();
85
+ const task = { id: value.id };
86
+ for (const [key, rule] of Object.entries(schema)) {
87
+ const parsed = normalize(value[key], rule, key, warnings);
88
+ if (parsed !== undefined)
89
+ task[key] = parsed;
90
+ }
91
+ if (typeof task.progress === 'number' && task.progress > 100) {
92
+ delete task.progress;
93
+ warnings.add('progress');
94
+ }
95
+ // Limit dates before consumers convert them to ISO strings.
96
+ if (typeof task.created === 'number' && task.created > 253402300799) {
97
+ delete task.created;
98
+ warnings.add('created');
99
+ }
100
+ if (typeof value.status === 'string' && STATUSES.has(value.status))
101
+ task.status = value.status;
102
+ else
103
+ warnings.add('status');
104
+ if (value.results !== undefined) {
105
+ if (Array.isArray(value.results)) {
106
+ task.results = value.results.slice(0, 100).flatMap((item, index) => {
107
+ const parsed = normalize(item, 'url', `results[${index}]`, warnings);
108
+ return typeof parsed === 'string' ? [parsed] : [];
109
+ });
110
+ if (value.results.length > 100)
111
+ warnings.add('results.truncated');
112
+ }
113
+ else
114
+ warnings.add('results');
115
+ }
116
+ if (value.result_data !== undefined) {
117
+ if (Array.isArray(value.result_data)) {
118
+ task.result_data = value.result_data.slice(0, 100).flatMap((item, index) => {
119
+ const parsed = normalize(item, outputSchema, `result_data[${index}]`, warnings);
120
+ return parsed === undefined ? [] : [parsed];
121
+ });
122
+ if (value.result_data.length > 100)
123
+ warnings.add('result_data.truncated');
124
+ }
125
+ else {
126
+ const parsed = normalize(value.result_data, outputSchema, 'result_data', warnings);
127
+ if (parsed !== undefined)
128
+ task.result_data = parsed;
129
+ }
130
+ }
131
+ if (requestId && publicIdentifier(requestId))
132
+ task.request_id = requestId;
133
+ if (warnings.size)
134
+ task.response_warnings = [...warnings].slice(0, 100);
135
+ return task;
136
+ }
137
+ export function parseTaskResponse(value, taskId, requestId) {
138
+ if (!record(value) || !taskIdentifier(value.id))
139
+ throw new TaskResponseError('task_response_invalid', taskId, requestId);
140
+ if (value.id !== taskId)
141
+ throw new TaskResponseError('task_identity_mismatch', taskId, requestId);
142
+ if (typeof value.status !== 'string' || !STATUSES.has(value.status)) {
143
+ const raw = typeof value.status === 'string' && /^[a-z_]{1,32}$/.test(value.status) ? value.status : undefined;
144
+ throw new TaskResponseError('task_status_unknown', taskId, requestId, raw);
145
+ }
146
+ return parseTaskReceipt(value, requestId);
147
+ }
148
+ export function parseBatchTasks(value, taskIds, requestId) {
149
+ if (!record(value) || !Array.isArray(value.data))
150
+ throw new TaskResponseError('task_response_invalid', undefined, requestId);
151
+ const requested = new Set(taskIds.filter(taskIdentifier)), counts = new Map();
152
+ for (const item of value.data)
153
+ if (record(item) && typeof item.id === 'string' && requested.has(item.id))
154
+ counts.set(item.id, (counts.get(item.id) ?? 0) + 1);
155
+ const tasks = [], issues = [];
156
+ for (const item of value.data) {
157
+ const id = record(item) && typeof item.id === 'string' && requested.has(item.id) ? item.id : undefined;
158
+ if (!id) {
159
+ issues.push({ code: 'unexpected_task_response' });
160
+ continue;
161
+ }
162
+ if (counts.get(id) > 1) {
163
+ if (!issues.some(issue => issue.task_id === id))
164
+ issues.push({ task_id: id, code: 'duplicate_task_response' });
165
+ continue;
166
+ }
167
+ try {
168
+ tasks.push(parseTaskResponse(item, id, requestId));
169
+ }
170
+ catch (error) {
171
+ issues.push({ task_id: id, code: error instanceof TaskResponseError ? error.code : 'task_response_invalid' });
172
+ }
173
+ }
174
+ const found = new Set(tasks.map(task => task.id));
175
+ return { tasks, missing: [...requested].filter(id => !found.has(id)), issues };
176
+ }
@@ -13,7 +13,7 @@ export const PAID_GENERATION_GUIDANCE = [
13
13
  ].join(' ');
14
14
  /** Shared confirmation wording; approval and spending rules above still apply. */
15
15
  export const GENERATION_CONFIRMATION_GUIDANCE = [
16
- 'When spending approval is needed, use the following layout in the user\'s language. Fill it from the exact model and input checked by `estimate_cost`; summarize the content in one sentence. Render normal text and bullets; the code blocks below only illustrate the layout.',
16
+ 'When spending approval is needed, use the following layout in English by default unless the user explicitly requests another language. Fill it from the exact model and input checked by `estimate_cost`; summarize the content in one sentence. Render normal text and bullets; the code blocks below only illustrate the layout.',
17
17
  '',
18
18
  'Chinese:',
19
19
  '',
@@ -43,6 +43,8 @@ export const GENERATION_CONFIRMATION_GUIDANCE = [
43
43
  '- For a complete estimate, show the returned amount or range in credits and approximate USD. Label it as an estimate, not a guaranteed final charge.',
44
44
  '- Do not add a separate estimated cap or max_cost_usd to the default confirmation. If the user specified a budget, state whether the estimate fits it; pause if it exceeds the budget. A budget comparison does not limit the final settlement.',
45
45
  '- For a partial estimate, label it "部分估价" / "Partial estimate", state what is excluded, and say it is neither the total nor an upper bound.',
46
+ '- 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.',
47
+ '- When search_charges is returned, disclose each enabled search type and its per-search rate before generation approval, even when the user requested search. A zero-search subtotal excludes unknown search fees; one task may search multiple times or not at all. Expected counts are assumptions, not execution limits. Actual counts depend on the task and model strategy. Do not add a search-fee warning when search is off.',
46
48
  '- For token billing, say "按实际 token 用量计费,生成前无法确定总价" / "Billed by actual token usage; the total is unknown before generation." Include the applicable published unit rates when returned. If no price is available, say so rather than assuming token billing.',
47
49
  '- If the user set a fixed cap that cannot be checked, explain that gap and replace the usual closing with an explicit question about proceeding without that cap. Do not treat a generic "Confirm generation" as consent to remove or raise a cap.',
48
50
  '- The suggested confirmation phrase is not a required command; any clear approval of the quoted task is valid. Existing task or batch approval still follows the spending approval rules; do not ask again when it already covers this request.',
@@ -8,6 +8,7 @@ import { formatEstimateRange } from '../services/pricing-client.js';
8
8
  import { PricingRulesError } from '../services/pricing-rules-client.js';
9
9
  import { QuoteError, QuoteParameters } from '../services/pricing-quote-client.js';
10
10
  import { createRulesEstimate } from '../services/pricing-rules-estimate.js';
11
+ import { prepareSeedanceInput } from '../services/seedance-input.js';
11
12
  import { API_KEYS_URL, MCP_CONSOLE_URL, MCP_KEY_NAME, TOP_UP_URL } from '../services/http-policy.js';
12
13
  import { trackedLink } from '../services/utm.js';
13
14
  import { currentCredentialMode } from '../request-context.js';
@@ -25,7 +26,7 @@ export function registerEstimateCost(server, config) {
25
26
  input: z.record(z.unknown()).optional()
26
27
  .describe('The input you plan to pass to the generate tool, e.g. {"prompt":"…","duration":5,"quality":"1080p"}.'),
27
28
  pricing_source: z.enum(['pricing_rules', 'account', 'public_reference']).default('pricing_rules').describe('Use published full pricing rules for public default estimates. The old account/public_reference values are compatibility aliases; neither requests a backend account quote.'),
28
- pricing_parameters: QuoteParameters.optional().describe('Measured or expected billing usage declared by the pricing policy, such as input_seconds. Do not include user_group, prices or generation prompts.'),
29
+ pricing_parameters: QuoteParameters.optional().describe('Measured or explicitly expected usage declared by the pricing policy, such as input_seconds or search_count. Missing enabled-search counts produce a zero-search partial subtotal and per-search rates. Do not invent counts, include user_group/prices/prompts, or treat expected counts as execution limits.'),
29
30
  media_seconds: z.number().positive().max(MEDIA_SECONDS_MAX).optional().describe(MEDIA_SECONDS_DESCRIPTION),
30
31
  },
31
32
  annotations: { title: 'Estimate cost', ...READ_ONLY },
@@ -36,8 +37,11 @@ export function registerEstimateCost(server, config) {
36
37
  const suggestions = suggestModels(catalog, model);
37
38
  return failure(`Unknown model "${model}".${suggestions.length ? ` Did you mean: ${suggestions.join(', ')}?` : ''} Use search_models to find model IDs.`, { error: { category: 'not_found', param: 'model' }, suggestions });
38
39
  }
39
- const values = input ?? {};
40
+ const prepared = prepareSeedanceInput(entry, input ?? {});
41
+ const values = prepared.input;
40
42
  const validation = entry.spec ? validateInput(entry.spec, values) : undefined;
43
+ validation?.errors.push(...prepared.errors);
44
+ validation?.warnings.push(...prepared.warnings);
41
45
  if (validation?.errors.length)
42
46
  return failure('The generation input is invalid; no estimate was created.', { input_valid: false, problems: validation.errors, error: { category: 'invalid_request' }, charged: 'no' });
43
47
  const rulesEstimate = await createRulesEstimate(entry, values, { mediaSeconds, pricingParameters });
@@ -54,6 +58,8 @@ export function registerEstimateCost(server, config) {
54
58
  }
55
59
  if (validation?.warnings.length)
56
60
  lines.push('Warnings:', ...formatIssues(validation.warnings));
61
+ for (const applied of prepared.defaults)
62
+ lines.push(`Applied default: ${applied.param}=${applied.value} (${applied.reason}); this effective value is used for pricing and submission.`);
57
63
  const range = formatEstimateRange(estimate);
58
64
  if (estimate.status === 'estimated' && range)
59
65
  lines.push(`Estimated cost: ${range}`);
@@ -91,6 +97,10 @@ export function registerEstimateCost(server, config) {
91
97
  problems: validation?.errors ?? [],
92
98
  warnings: validation?.warnings ?? [],
93
99
  estimate,
100
+ ...(estimate.search_charges?.length ? { search_charges: estimate.search_charges,
101
+ amount_scope: estimate.status === 'partial' ? 'known_components_subtotal' : estimate.status === 'estimated' ? 'expected_usage_estimate' : 'not_established' } : {}),
102
+ ...(prepared.applies ? { effective_input: values, defaults_applied: prepared.defaults,
103
+ amount_scope: estimate.status === 'partial' ? 'known_components_subtotal' : estimate.status === 'estimated' ? 'expected_usage_estimate' : 'not_established' } : {}),
94
104
  };
95
105
  try {
96
106
  const credits = await getCredits(config, 'estimate_cost');