@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
package/src/media.mjs CHANGED
@@ -1,8 +1,44 @@
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';
7
+ import { dashboardCheck } from './platform/core/src/tools/shared.js';
8
+ import { NEXT_READ_MIN_MS, pollIntervalMs } from './platform/core/src/tools/task-format.js';
9
+
10
+ /** Longest single get_task round inside a local wait; each round shares the wait's one deadline. */
11
+ const WAIT_ROUND_SECONDS = 30;
12
+ const ROUND_PAUSE_MS = 500;
13
+ /** The first round starts with at least this much of the wait left; a later round needs the shared core's NEXT_READ_MIN_MS. */
14
+ const MIN_ROUND_MS = 300;
15
+ /** Drift ignored when the time left becomes whole seconds; the shared core still ends each round at the deadline. */
16
+ const ROUND_DRIFT_MS = 50;
17
+ const WAIT_STOPS_LOCAL = 'Stopping does not cancel the task.';
18
+
19
+ function interrupted(taskId) {
20
+ return new CliError('interrupted', 'Stopped waiting locally. The EvoLink task continues.', { task_id: taskId }, 130);
21
+ }
22
+
23
+ /** At the local limit, report what was last verified instead of claiming the task is still running. */
24
+ function waitTimeout(taskId, last) {
25
+ const verified = last?.status_check === 'verified' && last.status;
26
+ return new CliError('wait_timeout', verified
27
+ ? `Stopped waiting at the timeout. ${WAIT_STOPS_LOCAL} Last verified status: ${last.status}${last.read_at ? ` (read at ${last.read_at})` : ''}. Continue with evolink tasks wait ${taskId}.`
28
+ : `Stopped waiting at the timeout. ${WAIT_STOPS_LOCAL} Its latest status could not be verified${last?.status ? ` (last verified: ${last.status})` : ''}. Query it with evolink tasks get ${taskId}.`,
29
+ { task_id: taskId, status_check: verified ? 'verified' : 'unverified',
30
+ ...(last?.status ? { last_status: last.status } : {}), ...(last?.read_at ? { read_at: last.read_at } : {}),
31
+ ...(verified ? {} : dashboardCheck()), recovery: `evolink tasks wait ${taskId}` });
32
+ }
33
+
34
+ function pause(ms, signal) {
35
+ return new Promise(resolve => {
36
+ const timer = setTimeout(done, Math.max(0, ms));
37
+ function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); }
38
+ signal?.addEventListener('abort', done, { once: true });
39
+ if (signal?.aborted) done();
40
+ });
41
+ }
6
42
 
7
43
  function quoteError(error, cap) {
8
44
  const cause = fileError(error);
@@ -19,6 +55,7 @@ function quoteError(error, cap) {
19
55
 
20
56
  export function priceFingerprint(quote) {
21
57
  return hash({ model: quote.model, type: quote.type, input_valid: quote.input_valid, estimate: quote.estimate,
58
+ ...(quote.effective_input ? { effective_input: quote.effective_input } : {}),
22
59
  warnings: quote.warnings, pricing_warning: quote.pricing_warning, pricing_scope: quote.pricing_scope,
23
60
  rules: quote.pricing_quote && { fingerprint: quote.pricing_quote.fingerprint, request_hash: quote.pricing_quote.request_hash, total_uc: quote.pricing_quote.total_uc },
24
61
  account: quote.account_quote && { request_hash: quote.account_quote.request_hash, parameters: quote.account_quote.parameters,
@@ -51,6 +88,12 @@ export function checkEstimate(quote, cap) {
51
88
  export class Media {
52
89
  constructor({ client, mcp = client, state, server, now = Date.now }) { this.client = mcp; this.state = state; this.server = server.href; this.now = now; }
53
90
  async estimate(args) {
91
+ const { stored, view } = await this.prepareQuote(args);
92
+ await this.state.write('quotes', stored.id, stored);
93
+ return view;
94
+ }
95
+ /** Obtains and checks an estimate and builds its quote record; nothing is saved. */
96
+ async prepareQuote(args) {
54
97
  const { max_cost_usd, ...input } = args;
55
98
  let quote;
56
99
  try {
@@ -65,22 +108,76 @@ export class Media {
65
108
  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
109
  requireThat(serverExpiry === undefined || Number.isFinite(serverExpiry) && serverExpiry > this.now(),
67
110
  '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);
111
+ const expires = Math.min(this.now() + APPROVAL_TTL_MS, serverExpiry ?? Infinity);
69
112
  const stored = { id, server: this.server, binding: quote._binding, args: argsToSubmit,
70
113
  ...(this.client.apiUrl ? { backend: 'platform', api_origin: this.client.apiUrl.origin } : {}),
71
114
  type: quote.type, args_hash: hash(argsToSubmit), fingerprint: priceFingerprint(quote), estimate: quote.estimate,
115
+ ...(quote.effective_input ? { effective_input: quote.effective_input, defaults_applied: quote.defaults_applied } : {}),
72
116
  created_at: this.now(), expires_at: expires, ...(quote.account_quote ? { backend_estimate_id: quote.account_quote.quote.estimate_id,
73
117
  server_expires_at: serverExpiry, account_quote: quote.account_quote } : {}), state: 'quoted', client_request_id: `cli-${randomUUID()}` };
74
- await this.state.write('quotes', id, stored);
75
- return { ...quote, quote_id: id, input: input.input || {}, ...(max_cost_usd !== undefined ? { max_cost_usd, cap_source: 'user' } : {}), expires_at: new Date(stored.expires_at).toISOString(),
118
+ const view = { ...quote, quote_id: id, input: input.input || {}, ...(max_cost_usd !== undefined ? { max_cost_usd, cap_source: 'user' } : {}), expires_at: new Date(stored.expires_at).toISOString(),
76
119
  requires_confirmation: true, next_step: `After the user approves, run evolink generate ${quote.type} --quote ${id} --confirm.` };
120
+ return { stored, view };
77
121
  }
122
+ /**
123
+ * One generation per estimate. A refresh gives it a new quote but keeps its request ID, and moves a single pointer
124
+ * (intents/<first quote ID>) to the new quote, which is saved first; only the quote that pointer names can be submitted.
125
+ * A quote never refreshed is its own generation and has no pointer, as in earlier releases.
126
+ */
127
+ intentOf(quote) { return quote.intent_id ?? quote.id; }
78
128
  async refresh(id) {
79
- const quote = await this.load(id);
80
- requireThat(quote.state === 'quoted' && !quote.task_id, 'submission_already_started',
81
- 'This submission has started. Recover its original task instead of refreshing its quote.');
82
- const { account_quote, pricing_quote, ...args } = quote.args;
83
- return { ...await this.estimate(args), refreshed_from: id };
129
+ const intentId = this.intentOf(await this.load(id));
130
+ const lock = `quote-${intentId}`;
131
+ // Checked before and again after the estimate, under the lock that submission and recovery share: a submission
132
+ // or another refresh while the estimate ran means no new submittable quote is saved.
133
+ const before = await this.state.lock(lock, () => this.refreshable(intentId));
134
+ const { account_quote, pricing_quote, ...args } = before.args;
135
+ const { stored, view } = await this.prepareQuote(args);
136
+ return this.state.lock(lock, async () => {
137
+ const current = await this.refreshable(intentId);
138
+ requireThat(current.id === before.id, 'quote_refresh_conflict',
139
+ `Another refresh already replaced this quote with quote ${current.id}. Show the user that quote and obtain approval for it.`,
140
+ { quote_id: id, active_quote_id: current.id, client_request_id: current.client_request_id, submission_allowed: false });
141
+ // Nothing was ever submitted with this request ID, so the refreshed quote keeps it.
142
+ const next = { ...stored, intent_id: intentId, client_request_id: current.client_request_id, refreshed_from: current.id };
143
+ await this.state.write('quotes', next.id, next);
144
+ const intent = await this.state.read('intents', intentId);
145
+ await this.state.write('intents', intentId, { id: intentId, client_request_id: next.client_request_id, active_quote_id: next.id,
146
+ quotes: [...(intent?.quotes ?? [intentId]), next.id], updated_at: this.now() });
147
+ // The pointer above decides; marking the replaced quote only explains it.
148
+ await this.state.write('quotes', current.id, { ...current, state: 'superseded', superseded_by: next.id });
149
+ return { ...view, refreshed_from: id, superseded_quote_id: current.id, client_request_id: next.client_request_id };
150
+ });
151
+ }
152
+ /** The generation's current quote, which must not have started a submission. */
153
+ async refreshable(intentId) {
154
+ const intent = await this.state.read('intents', intentId);
155
+ const active = await this.load(intent?.active_quote_id ?? intentId);
156
+ requireThat(active.state === 'quoted' && !active.task_id, 'submission_already_started',
157
+ 'This submission has started. Recover its original task instead of refreshing its quote.', {
158
+ quote_id: active.id, client_request_id: active.client_request_id, submission_allowed: false,
159
+ ...(active.task_id ? { task_id: active.task_id, recovery: `evolink tasks get ${active.task_id}` }
160
+ : ['submitting', 'outcome_unknown'].includes(active.state) ? { recovery: `evolink tasks resume --quote ${active.id}` } : {}) });
161
+ return active;
162
+ }
163
+ /** Only the generation's current quote may be submitted or recovered; any other names the current one or its task. */
164
+ async requireActive(quote, kind) {
165
+ const intentId = this.intentOf(quote);
166
+ const intent = await this.state.read('intents', intentId);
167
+ const activeId = intent?.active_quote_id ?? intentId;
168
+ if (activeId === quote.id) return;
169
+ const details = { quote_id: quote.id, active_quote_id: activeId, client_request_id: quote.client_request_id, submission_allowed: false };
170
+ if (!intent) throw new CliError('quote_refresh_incomplete',
171
+ `This refreshed quote was not saved completely and cannot be submitted. Use quote ${activeId} or refresh it again.`, details);
172
+ const active = await this.state.read('quotes', activeId);
173
+ if (active?.task_id) throw new CliError('quote_superseded',
174
+ `This quote was replaced by quote ${activeId}, which was already submitted as task ${active.task_id}. Do not generate again.`,
175
+ { ...details, task_id: active.task_id, recovery: `evolink tasks get ${active.task_id}` });
176
+ if (['submitting', 'outcome_unknown'].includes(active?.state)) throw new CliError('quote_superseded',
177
+ `This quote was replaced by quote ${activeId}, whose submission is unverified. Recover that quote; do not create a new request.`,
178
+ { ...details, recovery: `evolink tasks resume --quote ${activeId}` });
179
+ throw new CliError('quote_superseded', `This quote was replaced by quote ${activeId}. Show the user that quote and obtain approval for it.`,
180
+ { ...details, next_step: `After the user approves, run evolink generate ${kind} --quote ${activeId} --confirm.` });
84
181
  }
85
182
  async load(id) {
86
183
  const quote = await this.state.read('quotes', id);
@@ -93,10 +190,13 @@ export class Media {
93
190
  async generate(kind, id, { confirmed = false, resume = false } = {}) {
94
191
  requireThat(['image', 'video', 'audio'].includes(kind), 'invalid_type', 'Choose image, video or audio.');
95
192
  requireThat(confirmed || resume, 'confirmation_required', 'Show the quote to the user and obtain approval before adding --confirm.');
96
- return this.state.lock(`quote-${id}`, async () => {
193
+ // Submission, recovery and refresh of one generation share its lock; the quote is validated inside it.
194
+ const intentId = this.intentOf((await this.state.read('quotes', id)) ?? { id });
195
+ return this.state.lock(`quote-${intentId}`, async () => {
97
196
  const quote = await this.load(id);
98
197
  requireThat(quote.type === kind, 'quote_type_mismatch', 'Use the media type shown in the saved quote.');
99
198
  if (quote.task_id) return { ...await this.client.call('get_task', { task_id: quote.task_id, wait_seconds: 0 }), quote_id: id, recovered: true };
199
+ await this.requireActive(quote, kind);
100
200
  requireThat(quote.state !== 'refused', 'submission_refused',
101
201
  'EvoLink refused this submission and reported no charge. Resolve the original error, estimate again with the same budget, and obtain approval for the new quote.',
102
202
  { quote_id: id, client_request_id: quote.client_request_id, charged: 'no', submission_allowed: false });
@@ -106,7 +206,7 @@ export class Media {
106
206
  next_step: `After user approval, run evolink generate ${kind} --quote ${id} --confirm.` });
107
207
  requireThat(resume ? ['submitting', 'outcome_unknown'].includes(quote.state) : quote.state === 'quoted',
108
208
  '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 });
209
+ 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
210
  const { max_cost_usd, account_quote, pricing_quote, ...checkArgs } = quote.args;
111
211
  let fresh;
112
212
  try {
@@ -139,6 +239,18 @@ export class Media {
139
239
  result = await this.client.call(`generate_${kind}`, { ...generationArgs, client_request_id: quote.client_request_id });
140
240
  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
241
  } catch (e) {
242
+ // Acceptance survives later read/format failures; recovery must query this ID, never POST again.
243
+ const acceptedId = e.details?.submission_state === 'accepted' && typeof e.details?.task_id === 'string'
244
+ && /^[A-Za-z0-9._:-]{1,128}$/.test(e.details.task_id) ? e.details.task_id : undefined;
245
+ if (acceptedId) {
246
+ quote.state = 'submitted';
247
+ quote.task_id = acceptedId;
248
+ await this.state.write('quotes', id, quote);
249
+ throw new CliError(e.code || 'task_response_invalid', e.message, { ...e.details,
250
+ quote_id: id, client_request_id: quote.client_request_id, status_check: 'unverified',
251
+ dashboard_url: DASHBOARD_URL,
252
+ recovery: `evolink tasks get ${acceptedId}` }, e.exitCode);
253
+ }
142
254
  quote.state = !resume && e.details?.charged === 'no' && ['not_submitted', 'rejected'].includes(e.details?.submission_state) ? 'refused' : 'outcome_unknown';
143
255
  await this.state.write('quotes', id, quote);
144
256
  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,
@@ -154,21 +266,51 @@ export class Media {
154
266
  const quote = await this.load(id);
155
267
  return this.generate(quote.type, id, { resume: true });
156
268
  }
157
- async wait(taskId, { timeout = 1800, signal, progress = () => {} } = {}) {
158
- const deadline = Date.now() + timeout * 1000;
269
+ /**
270
+ * Waits locally for one task. A single monotonic deadline bounds every round, read, retry and pause; a round asks
271
+ * only for the whole seconds left. budget.deadline lets the command keep optional work (the update notice) inside it.
272
+ */
273
+ async wait(taskId, { timeout = 1800, signal, progress = () => {}, budget } = {}) {
274
+ const deadline = performance.now() + timeout * 1000;
275
+ if (budget) budget.deadline = deadline;
276
+ let last, rounds = 0;
159
277
  for (;;) {
160
- if (signal?.aborted) throw new CliError('interrupted', 'Stopped waiting locally. The EvoLink task continues.', { task_id: taskId }, 130);
161
- const remaining = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
162
- const task = await this.client.call('get_task', { task_id: taskId, wait_seconds: Math.min(30, remaining) });
278
+ if (signal?.aborted) throw interrupted(taskId);
279
+ const left = deadline - performance.now();
280
+ // Too little time for another round: report the last verified state as it is. Like a later read in the shared
281
+ // core, a later round needs time to finish; started with less, it would only turn a verified status unverified.
282
+ if (left < (rounds === 0 ? MIN_ROUND_MS : NEXT_READ_MIN_MS)) throw waitTimeout(taskId, last);
283
+ rounds += 1;
284
+ let task;
285
+ try {
286
+ task = await this.client.call('get_task', { task_id: taskId, wait_seconds: Math.min(WAIT_ROUND_SECONDS, Math.floor((left + ROUND_DRIFT_MS) / 1000)) }, { deadline });
287
+ } catch (error) {
288
+ if (signal?.aborted) throw interrupted(taskId);
289
+ // A round that ran out of time is not a task outcome; continue while the wait itself has time left.
290
+ if (!['task_query_timeout', 'wait_deadline_reached'].includes(error.code)) throw error;
291
+ last = { ...last, status_check: 'unverified' };
292
+ const rest = deadline - performance.now();
293
+ if (rest < NEXT_READ_MIN_MS) throw waitTimeout(taskId, last);
294
+ progress(`${taskId}: latest status unverified${last.status ? ` (last verified: ${last.status})` : ''}`);
295
+ await pause(Math.min(ROUND_PAUSE_MS, rest), signal);
296
+ continue;
297
+ }
163
298
  if (task.status === 'completed') return task;
164
299
  // task.error.code is the shared core's user-facing code, the one the API reports.
165
300
  if (['failed', 'cancelled'].includes(task.status)) {
166
301
  throw new CliError('task_failed', `The generation task ${task.status === 'failed' ? 'failed' : 'was cancelled'}${
167
302
  task.error?.code ? ` with error code ${task.error.code}` : ''}.`, { task });
168
303
  }
169
- progress(`${task.task_id}: ${task.status}${task.progress !== undefined ? ` (${task.progress}%)` : ''}`);
170
- if (Date.now() >= deadline) throw new CliError('wait_timeout', 'The task is still running. Continue with tasks wait.', { task_id: taskId });
171
- await new Promise(resolve => { const timer = setTimeout(done, 500); function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); } signal?.addEventListener('abort', done, { once: true }); });
304
+ last = task.status ? { status: task.status, read_at: task.read_at, status_check: 'verified' }
305
+ : { status: task.last_known_status ?? last?.status, read_at: task.read_at ?? last?.read_at, status_check: 'unverified' };
306
+ progress(task.status ? `${task.task_id}: ${task.status}${task.progress !== undefined ? ` (${task.progress}%)` : ''}`
307
+ : `${taskId}: latest status unverified${last.status ? ` (last verified: ${last.status})` : ''}`);
308
+ const rest = deadline - performance.now();
309
+ if (rest <= 0) throw waitTimeout(taskId, last);
310
+ // Rounds keep the shared polling rhythm for the task type: a short round does not mean reading more often.
311
+ const readMs = Date.parse(task.read_at);
312
+ const sinceRead = Number.isFinite(readMs) ? Math.max(0, Date.now() - readMs) : 0;
313
+ await pause(Math.min(Math.max(ROUND_PAUSE_MS, pollIntervalMs(task.type) - sinceRead), rest), signal);
172
314
  }
173
315
  }
174
316
  }
@@ -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,7 +3,8 @@
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 { 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';
6
+ import { parseBatchTasks, parseTaskReceipt, parseTaskResponse } from './task-response.js';
7
+ import { DEFAULT_READ_TIMEOUT_MS, DEFAULT_SUBMIT_TIMEOUT_MS, MAX_RETRY_DELAY_MS, MIN_READ_MS, PaidRequestOutcomeUnknownError, RequestTimeoutError, SubmissionNotStartedError, TaskQueryTimeoutError, evoHeaders, fetchWithTimeout, monotonicNow, newRunId, parseRetryAfter, readJsonBody, remainingMs, requestedRetryAfterMs, responseRequestId, timeoutFromEnv, } from './http-policy.js';
7
8
  // --- Error class for HTTP-level failures ---
8
9
  export class ApiHttpError extends Error {
9
10
  status;
@@ -11,6 +12,8 @@ export class ApiHttpError extends Error {
11
12
  requestId;
12
13
  info;
13
14
  submissionState;
15
+ /** Retry-After as the server sent it, without the general 30 s cap. */
16
+ requestedRetryAfterMs;
14
17
  constructor(status, message, retryAfterMs, requestId, info, submissionState) {
15
18
  super(message);
16
19
  this.status = status;
@@ -23,16 +26,21 @@ export class ApiHttpError extends Error {
23
26
  }
24
27
  // --- Retry logic ---
25
28
  const RETRYABLE_STATUS_CODES = new Set([429, 502, 503]);
26
- function sleep(ms) {
27
- const signal = currentRequestCredentials()?.http?.signal;
29
+ function sleep(ms, extra) {
30
+ const signals = [currentRequestCredentials()?.http?.signal, extra].filter((signal) => !!signal);
28
31
  return new Promise(resolve => {
29
32
  const timer = setTimeout(done, ms);
30
- function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); }
31
- signal?.addEventListener('abort', done, { once: true });
32
- if (signal?.aborted)
33
+ function done() { clearTimeout(timer); for (const signal of signals)
34
+ signal.removeEventListener('abort', done); resolve(); }
35
+ for (const signal of signals)
36
+ signal.addEventListener('abort', done, { once: true });
37
+ if (signals.some(signal => signal.aborted))
33
38
  done();
34
39
  });
35
40
  }
41
+ function stopped(signal) {
42
+ return !!signal?.aborted || !!currentRequestCredentials()?.http?.signal?.aborted;
43
+ }
36
44
  function isRetryable(error) {
37
45
  // Key and balance rejections are always HTTP 402, so they are never retried here.
38
46
  if (error instanceof ApiHttpError)
@@ -45,7 +53,11 @@ function isRetryable(error) {
45
53
  return true; // network errors (DNS, reset, …)
46
54
  return false;
47
55
  }
48
- export async function withRetry(fn, retries, baseDelayMs) {
56
+ /** A gateway answer (rate limit, overload) says more than "ran out of time"; network and timeout failures do not. */
57
+ function budgetError(error) {
58
+ return error instanceof ApiHttpError || !isRetryable(error) ? error : new TaskQueryTimeoutError(error);
59
+ }
60
+ export async function withRetry(fn, retries, baseDelayMs, budget = {}) {
49
61
  let lastError;
50
62
  for (let attempt = 0; attempt <= retries; attempt++) {
51
63
  try {
@@ -53,11 +65,25 @@ export async function withRetry(fn, retries, baseDelayMs) {
53
65
  }
54
66
  catch (error) {
55
67
  lastError = error;
56
- if (attempt < retries && isRetryable(error) && !currentRequestCredentials()?.http?.signal?.aborted) {
57
- const retryAfterMs = error instanceof ApiHttpError ? error.retryAfterMs : undefined;
58
- await sleep(Math.min(retryAfterMs ?? baseDelayMs * (attempt + 1), MAX_RETRY_DELAY_MS));
68
+ if (attempt < retries && isRetryable(error) && !stopped(budget.signal)) {
69
+ if (budget.deadline === undefined) {
70
+ const retryAfterMs = error instanceof ApiHttpError ? error.retryAfterMs : undefined;
71
+ await sleep(Math.min(retryAfterMs ?? baseDelayMs * (attempt + 1), MAX_RETRY_DELAY_MS), budget.signal);
72
+ continue;
73
+ }
74
+ // A task wait never retries before the server's requested pause, and ends instead of running past its window.
75
+ const requested = error instanceof ApiHttpError ? error.requestedRetryAfterMs ?? error.retryAfterMs : undefined;
76
+ const delay = requested ?? baseDelayMs * (attempt + 1);
77
+ // Twice the read minimum leaves room for timer lateness before the retry's own check.
78
+ if (delay > MAX_RETRY_DELAY_MS || remainingMs(budget.deadline) < delay + 2 * MIN_READ_MS)
79
+ throw budgetError(error);
80
+ await sleep(delay, budget.signal);
81
+ if (stopped(budget.signal))
82
+ throw error;
59
83
  continue;
60
84
  }
85
+ if (budget.deadline !== undefined && remainingMs(budget.deadline) < MIN_READ_MS)
86
+ throw budgetError(error);
61
87
  throw error;
62
88
  }
63
89
  }
@@ -79,6 +105,13 @@ async function rawRequest(config, options) {
79
105
  }
80
106
  body = options.body ? JSON.stringify(options.body) : undefined;
81
107
  timeout = options.timeoutMs ?? timeoutFromEnv(isPaid ? 'EVOLINK_MCP_WRITE_TIMEOUT_MS' : 'EVOLINK_MCP_READ_TIMEOUT_MS', isPaid ? DEFAULT_SUBMIT_TIMEOUT_MS : DEFAULT_READ_TIMEOUT_MS);
108
+ if (!isPaid && options.deadline !== undefined) {
109
+ // A task read shares its wait's remaining time instead of getting a fresh full timeout.
110
+ const left = remainingMs(options.deadline);
111
+ if (left < MIN_READ_MS)
112
+ throw new TaskQueryTimeoutError();
113
+ timeout = Math.min(timeout, Math.floor(left));
114
+ }
82
115
  }
83
116
  catch (error) {
84
117
  if (isPaid)
@@ -87,16 +120,18 @@ async function rawRequest(config, options) {
87
120
  }
88
121
  // Reading and verifying the body belong to the submission boundary too.
89
122
  try {
90
- const started = Date.now();
123
+ const started = monotonicNow();
91
124
  const response = await fetchWithTimeout(`${config.baseUrl}${options.path}`, {
92
- method: options.method, headers, body,
125
+ method: options.method, headers, body, ...(options.signal ? { signal: options.signal } : {}),
93
126
  }, timeout);
94
- const data = await readJsonBody(response, Math.max(1, timeout - (Date.now() - started)));
127
+ const data = await readJsonBody(response, Math.max(1, timeout - (monotonicNow() - started)), options.signal);
95
128
  const requestId = responseRequestId(response.headers);
96
129
  if (!response.ok) {
97
130
  const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'));
98
131
  const info = classifyGatewayError(response.status, data, retryAfterMs, requestId);
99
- throw new ApiHttpError(response.status, formatGatewayError(info), retryAfterMs, info.request_id, info, isPaid ? (verifiedPrechargeRejection(response.status, info.code) ? 'rejected' : 'outcome_unknown') : undefined);
132
+ const error = new ApiHttpError(response.status, formatGatewayError(info), retryAfterMs, info.request_id, info, isPaid ? (verifiedPrechargeRejection(response.status, info.code) ? 'rejected' : 'outcome_unknown') : undefined);
133
+ error.requestedRetryAfterMs = requestedRetryAfterMs(response.headers.get('retry-after'));
134
+ throw error;
100
135
  }
101
136
  if (isPaid && (!data || typeof data !== 'object' || Array.isArray(data)
102
137
  || typeof data.id !== 'string'
@@ -139,11 +174,10 @@ export async function submitTask(config, options) {
139
174
  tool: options.tool,
140
175
  idempotencyKey,
141
176
  }), 1, 500);
142
- if (!data.request_id && requestId)
143
- data.request_id = requestId;
177
+ const receipt = parseTaskReceipt(data, requestId);
144
178
  if (headers.get('idempotency-replayed') === 'true')
145
- data.idempotency_replayed = true;
146
- return data;
179
+ receipt.idempotency_replayed = true;
180
+ return receipt;
147
181
  }
148
182
  /** Read-only, credential-specific availability; never cached across accounts. */
149
183
  export async function getAvailableModelIds(config) {
@@ -168,21 +202,23 @@ export async function apiRequest(config, options) {
168
202
  return submitTask(config, { path: options.path, body: options.body, tool: options.tool ?? 'unknown' });
169
203
  }
170
204
  /** One task (GET /v1/tasks/{id}). Unfinished tasks sync with the provider on every read, so callers pace themselves. */
171
- export async function queryTask(config, taskId, tool = 'get_task') {
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;
205
+ export async function queryTask(config, taskId, tool = 'get_task', budget = {}) {
206
+ const { data, requestId } = await withRetry(() => rawRequest(config, { method: 'GET', path: `/v1/tasks/${encodeURIComponent(taskId)}`, tool,
207
+ deadline: budget.deadline, signal: budget.signal }), budget.retries ?? 2, 1500, budget);
208
+ return parseTaskResponse(data, taskId, requestId);
176
209
  }
177
210
  /** Up to 50 tasks in one call (POST /v1/tasks/batch); unknown or foreign IDs are simply absent. */
178
- export async function queryTasks(config, taskIds, tool = 'list_tasks') {
179
- const { data } = await withRetry(() => rawRequest(config, {
211
+ /** Several tasks in one free read (POST /v1/tasks/batch). A budget bounds it, its retries and pauses like a task wait. */
212
+ export async function queryTasks(config, taskIds, tool = 'list_tasks', budget = {}) {
213
+ const { data, requestId } = await withRetry(() => rawRequest(config, {
180
214
  method: 'POST',
181
215
  path: '/v1/tasks/batch',
182
216
  body: { task_ids: taskIds },
183
217
  tool,
184
- }), 2, 1500);
185
- return Array.isArray(data.data) ? data.data : [];
218
+ deadline: budget.deadline,
219
+ signal: budget.signal,
220
+ }), 2, 1500, budget);
221
+ return parseBatchTasks(data, taskIds, requestId);
186
222
  }
187
223
  /** The account's recent tasks, newest first (GET /v1/tasks). Items carry no result links. */
188
224
  export async function listTasks(config, query, tool = 'list_tasks', options = {}) {
@@ -196,7 +232,7 @@ export async function listTasks(config, query, tool = 'list_tasks', options = {}
196
232
  params.set('page', String(query.page ?? 1));
197
233
  params.set('page_size', String(query.pageSize ?? 20));
198
234
  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) {
235
+ if (!data || !Array.isArray(data.data) || !Number.isSafeInteger(data.total) || data.total < 0) {
200
236
  throw new ApiHttpError(502, 'The task list could not be verified. Retry this read; do not infer zero usage or submit another task.');
201
237
  }
202
238
  if ((data.page !== undefined && data.page !== (query.page ?? 1))