@evolinkai/cli 0.11.0 → 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.
package/README.md CHANGED
@@ -260,9 +260,9 @@ See [Gemini trusted folders](https://geminicli.com/docs/cli/trusted-folders/) an
260
260
 
261
261
  Generation errors preserve the saved quote and request ID when acceptance or charging is uncertain. `charged: no` alone does not authorize a new request: `submission_state` must also establish `not_submitted` or `rejected`. Recover uncertain submissions with the original quote, and query a known task. A new generation needs a fresh estimate and user approval.
262
262
 
263
- Task queries verify the requested ID and the public states `pending`, `processing`, `completed`, `failed`, `cancelled`. Invalid bodies, mismatched IDs and unknown states return `task_response_invalid`, `task_identity_mismatch` or `task_status_unknown`, with the original task ID and `status_check: unverified`. Retry the free query; this does not establish task failure, a zero charge or a refund. Accepted submissions retain their ID even if a follow-up query fails; resume queries that ID without creating another task. Optional fields vary by model: missing progress or costs are not zero, and completed voice/persona tasks may return reusable identifiers without download links. Invalid optional fields are omitted with `response_warnings`.
263
+ Task queries verify the requested ID and the public states `pending`, `processing`, `completed`, `failed`, `cancelled`. Invalid bodies, mismatched IDs and unknown states return `task_response_invalid`, `task_identity_mismatch` or `task_status_unknown`, with the original task ID and `status_check: unverified`. Retry the free query; this does not establish task failure, a zero charge or a refund. `tasks wait --timeout` is one limit for every read, retry and pause: at the limit it exits with `wait_timeout`, the task ID, the last verified status and its `read_at` (or `status_check: unverified` when the latest status could not be read), and the task keeps running. `tasks get` reads once without waiting; that read can still take up to 15 s. Accepted submissions retain their ID even if a follow-up query fails; resume queries that ID without creating another task. Optional fields vary by model: missing progress or costs are not zero, and completed voice/persona tasks may return reusable identifiers without download links. Invalid optional fields are omitted with `response_warnings`.
264
264
 
265
- `tasks batch` retains independently verified tasks and marks `partial`, `missing` and `issues` when other rows are absent, invalid or duplicated. `tasks list` keeps the verified base page if detail enrichment fails, marking `details_missing` and affected rows with `details_available: false`. An unavailable detail is not proof that the task never existed. Follow `next_page` and query the original missing IDs; do not interpret partial results as a complete usage total or regenerate to repair a read.
265
+ `tasks batch` retains independently verified tasks and marks `partial`, `missing` and `issues` when other rows are absent, invalid or duplicated. `tasks list` keeps the verified base page if detail enrichment fails, marking `details_missing` and affected rows with `details_available: false` and a `details_reason` (`read_failed`, `invalid` or `not_returned`); `details_status` summarizes the read. Retry `details_retry_task_ids` with `tasks batch --ids` (free) and check `not_returned` rows with `tasks get`. `last_page` names the last page; an empty page past it is not an empty account. An unavailable detail is not proof that the task never existed. Follow `next_page` and query the original missing IDs; do not interpret partial results as a complete usage total or regenerate to repair a read.
266
266
 
267
267
  Customer-facing notices, link labels and related guidance default to English unless the user explicitly requests another language. For uncertain task status, missing results, execution failure or incomplete lists, use the returned `dashboard_url` and English `dashboard_guidance`: [Open EvoLink Dashboard](https://evolink.ai/dashboard). Sign in with the same EvoLink account and keep the original task ID; this link does not establish task completion, charges or refunds.
268
268
 
@@ -280,7 +280,10 @@ shared MCP key, quota and permissions remain.
280
280
 
281
281
  Use `evolink estimate --refresh-quote ID` for an unsubmitted approval. It preserves
282
282
  input and an explicit user budget, creates a new local approval and requires user
283
- confirmation again. Unknown recovery keeps the original input and request ID;
283
+ confirmation again. The new quote replaces the old one, which can no longer be
284
+ submitted (`quote_superseded` names the current quote), and keeps its request ID;
285
+ if a submission or another refresh finishes first, no new quote is saved.
286
+ Unknown recovery keeps the original input and request ID;
284
287
  a failed replay cannot prove the first submission was free. Known tasks remain
285
288
  readable after expiry; check the original task before preparing another request.
286
289
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evolinkai/cli",
3
- "version": "0.11.0",
3
+ "version": "0.12.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",
@@ -76,7 +76,7 @@ The saved model and input are the submitted model and input. A changed or expire
76
76
  - Preserve `quote_id`, `client_request_id` and `task_id`. If submission outcome is unknown, use `tasks resume --quote QUOTE_ID` or `tasks list --since 30m --json`. Do not create a new quote/request ID to retry an uncertain submission. A known refused request can be corrected and quoted again.
77
77
  - `tasks list --status` accepts only the case-sensitive filters `processing`, `completed`, `failed`, `cancelled`. `processing` includes queued tasks. Do not use `pending`, `queued`, `canceled` or `all` as filter values. A task response may report `pending`; do not copy that response value into `--status`. Omit `--status` to read recent tasks across states, especially when recovering an uncertain submission that may already have completed or failed.
78
78
  - For active tasks, use `evolink tasks list --status processing --json`. To find recent completed videos, use `evolink tasks list --status completed --type video --limit 50 --json`. Task-list `--type` accepts only `image`, `video`, `audio`; omit it for all types. `--limit` is 1–50 (default 20); `--since` accepts ISO 8601, Unix seconds or a relative time such as `30m`, `2h`, `1d`. It filters the selected page, not the entire history. Use `--page` and follow `next_page`; `--model` and `--until` narrow results. `total` is before time filtering. An empty list does not prove no task was submitted; retain the original IDs and use recovery. `cancelled` is a read filter, not a CLI cancellation feature.
79
- - Poll with `tasks get TASK_ID --json` or `tasks wait TASK_ID --json`. Never poll with `generate`. Ctrl-C stops local waiting; it does not cancel the paid task.
79
+ - Poll with `tasks get TASK_ID --json` or `tasks wait TASK_ID --json`. Never poll with `generate`. Ctrl-C and the `tasks wait --timeout` limit stop only local waiting; they do not cancel the paid task. A `wait_timeout` error reports `status_check`: `verified` gives the last read `last_status` and its `read_at`, not a live status; `unverified` means the latest status could not be read. Continue with the returned `recovery` command, never with a new generation.
80
80
  - Deliver original result links immediately and the reported final charge. Links expire after 24 hours. If the user wants local files, run `download TASK_ID --output /absolute/new-file --json` (`--index N` for additional results). Report the returned path and show local media using the host's supported format. Do not claim a download or preview succeeded without evidence.
81
81
  - For several original results, read [Discovery and delivery extensions](references/capabilities.md), then use `download TASK_ID --all --output-dir DIR --json`. Partial delivery is a command error even though generation completed. Resume only downloads with the same task/directory/template and `--resume`; verify saved files and never generate again to repair delivery.
82
82
  - When the user asks for spending or usage, read [Usage and budget boundaries](references/usage-and-budget.md). Task summaries are not invoices or refund ledgers; missing costs and incomplete coverage must remain visible. An estimate guard is not a final settlement cap.
@@ -87,7 +87,7 @@ Use `generate` for the first submission of an approved quote. `tasks resume` is
87
87
 
88
88
  Use `--json` for commands consumed by the assistant. Progress is on stderr; stdout is one JSON envelope with `schema_version: 1`. `ok: false` and a nonzero exit code indicate a command error; a successful task query reporting `status: failed` is a task outcome, not a failed CLI invocation. Tell the user its `error.code` and `error.message` (EvoLink's explanation). A failed task is not charged; the credits reserved at submission are returned automatically (`billing_note`). Read the error's recovery details before retrying. For `invalid_status`, use `error.details.allowed_values` and correct only the free query; local status validation occurs before a platform request. Never guess an enum, interpret an empty list as a service failure, or resubmit a paid task to fix a query error. Run `evolink --help` for the maintained command reference and `evolink tasks list --help` for task filters.
89
89
 
90
- For `task_response_invalid`, `task_identity_mismatch`, `task_status_unknown` or `status_check: unverified`, keep the original task and request IDs. Tell the user the latest state could not be verified; retry only the free query. This is not evidence of failed generation, no charge or a completed refund. `submission_state: accepted` proves a task was accepted even when status is unavailable; use `tasks get` or the saved quote's `tasks resume`, never a new generation. Missing optional progress or costs are not zero; inspect `response_warnings`. Completed resource tasks may return reusable voice/persona IDs instead of result links. For `partial: true`, retain verified tasks and the base page, disclose missing coverage, and query `missing` or `details_missing` original IDs. Never use incomplete results as a full usage total.
90
+ For `task_response_invalid`, `task_identity_mismatch`, `task_status_unknown`, `task_query_timeout` or `status_check: unverified`, keep the original task and request IDs. Tell the user the latest state could not be verified; retry only the free query. This is not evidence of failed generation, no charge or a completed refund. `submission_state: accepted` proves a task was accepted even when status is unavailable; use `tasks get` or the saved quote's `tasks resume`, never a new generation. Missing optional progress or costs are not zero; inspect `response_warnings`. Completed resource tasks may return reusable voice/persona IDs instead of result links. For `partial: true`, retain verified tasks and the base page, disclose missing coverage, and query `missing` or `details_missing` original IDs: retry `details_retry_task_ids` with `tasks batch --ids`, and check rows whose `details_reason` is `not_returned` with `tasks get`. Never use incomplete results as a full usage total.
91
91
 
92
92
  For setup problems, run `evolink doctor --agent NAME --json` if the installed version supports the agent option; otherwise use `doctor --json`. Read every failed or skipped check and every `guidance` entry; without `--agent`, outdated or modified skill copies appear in `guidance` and `skills` without failing the check. On Linux, login and later commands need the same unlocked Secret Service/D-Bus session. On SSH hosts, opening the link on another computer requires forwarding the loopback callback port; `--no-browser` does not solve callback routing. Report connection, model discovery and assistant skill discovery separately.
93
93
 
@@ -95,7 +95,9 @@ For setup problems, run `evolink doctor --agent NAME --json` if the installed ve
95
95
  Estimates use published full pricing rules and show public default prices, excluding
96
96
  personal discounts. Local approvals last up to 30 minutes; submission verifies fresh rules.
97
97
  Use `evolink estimate --refresh-quote ID` only for an unsubmitted approval; preserve
98
- the input and explicit user budget and obtain approval again. Supply missing billing
98
+ the input and explicit user budget and obtain approval again. The refreshed quote
99
+ replaces the old one and keeps its request ID: submit only the newest quote, which
100
+ `quote_superseded` names. Supply missing billing
99
101
  usage with `--pricing-parameters JSON`; never invent unknown token counts or media
100
102
  lengths. Partial subtotals cannot check a budget. If rules are unavailable or change,
101
103
  pause and preserve the budget. Actual usage can change the final charge; final
@@ -20,7 +20,9 @@ A final task/workflow cap requires server-side reservation and settlement enforc
20
20
  Estimates use published full pricing rules and show public default prices, excluding
21
21
  personal discounts. Local approvals last up to 30 minutes; submission verifies fresh rules.
22
22
  Use `evolink estimate --refresh-quote ID` only for an unsubmitted approval; preserve
23
- the input and explicit user budget and obtain approval again. Supply missing billing
23
+ the input and explicit user budget and obtain approval again. The refreshed quote
24
+ replaces the old one and keeps its request ID: submit only the newest quote, which
25
+ `quote_superseded` names. Supply missing billing
24
26
  usage with `--pricing-parameters JSON`; never invent unknown token counts or media
25
27
  lengths. Partial subtotals cannot check a budget. If rules are unavailable or change,
26
28
  pause and preserve the budget. Actual usage can change the final charge; final
package/src/api.mjs CHANGED
@@ -22,13 +22,14 @@ export class Api {
22
22
  return fetchFn(input, { ...options, redirect: 'error', credentials: 'omit' });
23
23
  };
24
24
  }
25
- context(access, name) {
25
+ context(access, name, deadline) {
26
26
  // linkCampaign: site links the CLI shows are tagged utm_campaign=cli, not as the local MCP package.
27
+ // deadline (performance.now() ms): the local wait's own limit, which shared task reads never run past.
27
28
  return { serviceChannel: { accessToken: access.access_token }, clientName: 'EvoLink CLI', linkCampaign: 'cli',
28
29
  http: { fetch: this.fetchFn, signal: this.signal, userAgent: USER_AGENT, client: 'cli', version: CLI_VERSION,
29
- controlBaseUrl: this.apiUrl.origin, filesBaseUrl: this.filesUrl.origin } };
30
+ controlBaseUrl: this.apiUrl.origin, filesBaseUrl: this.filesUrl.origin, ...(deadline !== undefined ? { deadline } : {}) } };
30
31
  }
31
- async call(name, args = {}, { requireCapability = false, requiredInputs = [] } = {}) {
32
+ async call(name, args = {}, { requireCapability = false, requiredInputs = [], deadline } = {}) {
32
33
  if (requireCapability) requireThat(this.platform.supports(name, requiredInputs),
33
34
  'capability_unavailable', 'This CLI does not contain the requested platform capability. Update the CLI; no request was sent.',
34
35
  { tool: name, required_inputs: requiredInputs, request_sent: false });
@@ -46,13 +47,13 @@ export class Api {
46
47
  return { ...data, text };
47
48
  }
48
49
  for (let attempt = 0; attempt < 2; attempt++) {
49
- const access = await this.credentials.access(attempt > 0);
50
- const result = await this.platform.call(name, args, this.context(access, name));
50
+ const access = await this.credentials.access(attempt > 0, { deadline });
51
+ const result = await this.platform.call(name, args, this.context(access, name, deadline));
51
52
  const data = result.structuredContent;
52
53
  const text = (result.content ?? []).filter(item => item.type === 'text').map(item => item.text).join('\n');
53
54
  if (result.isError || data?.ok === false) {
54
55
  if (attempt === 0 && data?.error?.status === 401 && data?.charged !== 'unknown') continue;
55
- const taskReadCode = ['task_response_invalid', 'task_identity_mismatch', 'task_status_unknown'].includes(data?.error?.code) ? data.error.code : undefined;
56
+ const taskReadCode = ['task_response_invalid', 'task_identity_mismatch', 'task_status_unknown', 'task_query_timeout'].includes(data?.error?.code) ? data.error.code : undefined;
56
57
  throw new CliError(this.signal?.aborted ? 'interrupted' : taskReadCode || data?.error?.category || 'api_failed',
57
58
  safeMessage(data?.error?.message || text || 'The EvoLink request was refused.'), { ...data, text: safeMessage(text) }, this.signal?.aborted ? 130 : 1);
58
59
  }
package/src/auth.mjs CHANGED
@@ -7,6 +7,9 @@ import { hash } from './state.mjs';
7
7
  import { authFetch, ISSUER, SERVER, SITE } from './network.mjs';
8
8
  import { CliError, requireThat } from './errors.mjs';
9
9
 
10
+ /** A local wait with less time left than this does not start a token renewal. */
11
+ export const REFRESH_MIN_MS = 3_000;
12
+
10
13
  export class Vault {
11
14
  constructor(server, state) { this.account = hash({ server: server.href, home: state.home }); }
12
15
  async entry() {
@@ -143,7 +146,7 @@ export class Credentials {
143
146
  }
144
147
  lock(fn) { return this.state.lock(`auth-${hash(this.server.href)}`, fn); }
145
148
  provider() { return new OAuthProvider({ server: this.server, state: this.state, vault: this.vault, redirectUrl: 'http://127.0.0.1:1/oauth/callback' }); }
146
- async access(force = false) {
149
+ async access(force = false, { deadline } = {}) {
147
150
  if (this.token) {
148
151
  // The hash binds quotes to this temporary credential without writing it to disk.
149
152
  return { access_token: this.token, binding: hash(this.token) };
@@ -152,8 +155,16 @@ export class Credentials {
152
155
  let saved = await this.vault.read();
153
156
  requireThat(saved?.tokens, 'login_required', 'Run evolink auth login.');
154
157
  if (force || saved.expires_at <= Date.now() + 60_000) {
155
- await refresh(this.provider(), this.fetchFn);
156
- saved = await this.vault.read();
158
+ // Near a wait's deadline, a token still valid past it is used as is, and a renewal that could not
159
+ // finish in time is not started. A renewal that has started is never cut short: its new token must be saved.
160
+ const left = deadline === undefined ? Infinity : Math.max(0, deadline - performance.now());
161
+ const coversWait = !force && Number.isFinite(left) && saved.expires_at > Date.now() + left + 1_000;
162
+ if (!coversWait) {
163
+ if (left < REFRESH_MIN_MS) throw new CliError('wait_deadline_reached',
164
+ 'The wait limit was reached before the login could be renewed. Stopping this wait does not cancel the task.');
165
+ await refresh(this.provider(), this.fetchFn);
166
+ saved = await this.vault.read();
167
+ }
157
168
  }
158
169
  const issuer = this.server.href === SERVER ? ISSUER : this.server.origin;
159
170
  requireThat(saved?.tokens?.issuer === issuer && saved.tokens.access_token, 'login_required', 'This login belongs to a different service. Run auth login.');
package/src/cli.mjs CHANGED
@@ -204,7 +204,7 @@ async function estimateArgs(options) {
204
204
  return { model: options.model, input, ...(pricingParameters !== undefined ? { pricing_parameters: pricingParameters } : {}), ...(options['pricing-source'] ? { pricing_source: options['pricing-source'] } : {}), ...(media !== undefined ? { media_seconds: media } : {}), ...(cap !== undefined ? { max_cost_usd: cap } : {}) };
205
205
  }
206
206
 
207
- export async function dispatch(positionals, options, { state, server, credentials, client, mcp = client, signal, progress, skillHome, updates }) {
207
+ export async function dispatch(positionals, options, { state, server, credentials, client, mcp = client, signal, progress, skillHome, updates, budget }) {
208
208
  // login, setup and doctor always ask the registry and report the outcome, including a disabled check;
209
209
  // loopback test resources never contact it.
210
210
  const update = () => checkForUpdate({ state, server, force: true, signal, ...updates });
@@ -254,14 +254,14 @@ export async function dispatch(positionals, options, { state, server, credential
254
254
  requireThat(!['model', 'input', 'input-file', 'prompt', 'max-cost-usd', 'media-seconds'].some(k => options[k] !== undefined), 'quote_changed', 'Generation uses the saved quote. Change inputs by preparing a new estimate.');
255
255
  const result = await media.generate(action, options.quote, { confirmed: options.confirm });
256
256
  if (options.wait && result.task_id && result.status !== 'completed') {
257
- const task = await media.wait(result.task_id, { timeout: number(options.timeout, 'timeout', 1, 86400, true) || 1800, signal, progress });
257
+ const task = await media.wait(result.task_id, { timeout: number(options.timeout, 'timeout', 1, 86400, true) || 1800, signal, progress, budget });
258
258
  return { ...task, quote_id: options.quote, client_request_id: result.client_request_id };
259
259
  }
260
260
  return result;
261
261
  }
262
262
  if (command === 'tasks') {
263
263
  if (action === 'get' && id) return client.call('get_task', { task_id: id, wait_seconds: 0 });
264
- if (action === 'wait' && id) return media.wait(id, { timeout: number(options.timeout, 'timeout', 1, 86400, true) || 1800, signal, progress });
264
+ if (action === 'wait' && id) return media.wait(id, { timeout: number(options.timeout, 'timeout', 1, 86400, true) || 1800, signal, progress, budget });
265
265
  if (action === 'resume' && options.quote) return media.resume(options.quote);
266
266
  if (action === 'batch') return client.call('list_tasks', { task_ids: taskIds(options.ids) });
267
267
  if (action === 'list') {
@@ -306,6 +306,15 @@ async function stdinToken(stream) {
306
306
  return token;
307
307
  }
308
308
 
309
+ /** Resolves with the promise's value, or undefined once the deadline (performance.now() ms) passes. */
310
+ export async function beforeDeadline(promise, deadline) {
311
+ const left = deadline - performance.now();
312
+ if (left <= 0) return undefined;
313
+ let timer;
314
+ try { return await Promise.race([promise, new Promise(resolve => { timer = setTimeout(resolve, left); })]); }
315
+ finally { clearTimeout(timer); }
316
+ }
317
+
309
318
  export async function main(argv = process.argv.slice(2), io = { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin },
310
319
  { env = process.env, fetchFn, now, timeout, updateState } = {}) {
311
320
  let options = { json: argv.includes('--json') };
@@ -315,10 +324,14 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
315
324
  process.once('SIGTERM', interrupt);
316
325
  // The update notice follows the command's own output on stderr; stdout stays one envelope.
317
326
  let update;
327
+ const budget = {};
328
+ // Ctrl-C stops the update check; so does a local wait that reached its limit, so the process can exit at once.
329
+ const updateCheck = new AbortController();
330
+ controller.signal.addEventListener('abort', () => updateCheck.abort(), { once: true });
318
331
  const updates = { env, fetchFn, now, timeout };
319
332
  const checkUpdate = server => {
320
333
  // Building the state path can throw (for example without a home directory); that never fails the command.
321
- update = Promise.resolve().then(() => updateNotice({ state: updateState || new State(), server, signal: controller.signal, ...updates }))
334
+ update = Promise.resolve().then(() => updateNotice({ state: updateState || new State(), server, signal: updateCheck.signal, ...updates }))
322
335
  .catch(() => undefined);
323
336
  };
324
337
  try {
@@ -342,7 +355,7 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
342
355
  const client = new Api(credentials, { signal: controller.signal, apiUrl: options['api-url'], filesUrl: options['files-url'] });
343
356
  // Only a fully validated command checks: invalid tokens and service URLs fail without contacting npm.
344
357
  if (!NO_UPDATE_NOTICE.has(positionals[0]) && !NO_UPDATE_NOTICE.has(positionals.slice(0, 2).join(' '))) checkUpdate(server);
345
- const result = publicView(await dispatch(positionals, options, { state, server, credentials, client, signal: controller.signal, progress: message => io.stderr.write(message + '\n'), updates }));
358
+ const result = publicView(await dispatch(positionals, options, { state, server, credentials, client, signal: controller.signal, progress: message => io.stderr.write(message + '\n'), updates, budget }));
346
359
  const view = { schema_version: 1, ...result, ok: result.ok !== false };
347
360
  io.stdout.write(options.json ? JSON.stringify(view) + '\n' : `${result.text || JSON.stringify(view, null, 2)}\n${result.quote_id ? `Quote: ${result.quote_id}\n` : ''}`);
348
361
  if (!view.ok) process.exitCode = view.error?.code === 'interrupted' ? 130 : 1;
@@ -352,7 +365,9 @@ export async function main(argv = process.argv.slice(2), io = { stdout: process.
352
365
  process.exitCode = error.exitCode || (controller.signal.aborted ? 130 : 1);
353
366
  } finally {
354
367
  // Ctrl-C while the check finishes stops the check, not the completed command.
355
- const notice = await update;
368
+ // A local wait that reached its limit does not wait longer for the optional update notice.
369
+ const notice = budget.deadline === undefined ? await update : await beforeDeadline(update, budget.deadline);
370
+ if (budget.deadline !== undefined && notice === undefined) updateCheck.abort();
356
371
  process.removeListener('SIGINT', interrupt); process.removeListener('SIGTERM', interrupt);
357
372
  if (notice && !controller.signal.aborted) io.stderr.write(notice + '\n');
358
373
  }
package/src/media.mjs CHANGED
@@ -4,6 +4,41 @@ import { CliError, requireThat, fileError } from './errors.mjs';
4
4
  import { APPROVAL_TTL_MS, rulesBudgetExceeded } from './platform/core/src/services/pricing-rules-estimate.js';
5
5
  import { compareDecimal } from './platform/core/src/services/pricing-quote-client.js';
6
6
  import { DASHBOARD_URL } from './platform/core/src/services/http-policy.js';
7
+ import { dashboardCheck } from './platform/core/src/tools/shared.js';
8
+ import { NEXT_READ_MIN_MS, pollIntervalMs } from './platform/core/src/tools/task-format.js';
9
+
10
+ /** Longest single get_task round inside a local wait; each round shares the wait's one deadline. */
11
+ const WAIT_ROUND_SECONDS = 30;
12
+ const ROUND_PAUSE_MS = 500;
13
+ /** The first round starts with at least this much of the wait left; a later round needs the shared core's NEXT_READ_MIN_MS. */
14
+ const MIN_ROUND_MS = 300;
15
+ /** Drift ignored when the time left becomes whole seconds; the shared core still ends each round at the deadline. */
16
+ const ROUND_DRIFT_MS = 50;
17
+ const WAIT_STOPS_LOCAL = 'Stopping does not cancel the task.';
18
+
19
+ function interrupted(taskId) {
20
+ return new CliError('interrupted', 'Stopped waiting locally. The EvoLink task continues.', { task_id: taskId }, 130);
21
+ }
22
+
23
+ /** At the local limit, report what was last verified instead of claiming the task is still running. */
24
+ function waitTimeout(taskId, last) {
25
+ const verified = last?.status_check === 'verified' && last.status;
26
+ return new CliError('wait_timeout', verified
27
+ ? `Stopped waiting at the timeout. ${WAIT_STOPS_LOCAL} Last verified status: ${last.status}${last.read_at ? ` (read at ${last.read_at})` : ''}. Continue with evolink tasks wait ${taskId}.`
28
+ : `Stopped waiting at the timeout. ${WAIT_STOPS_LOCAL} Its latest status could not be verified${last?.status ? ` (last verified: ${last.status})` : ''}. Query it with evolink tasks get ${taskId}.`,
29
+ { task_id: taskId, status_check: verified ? 'verified' : 'unverified',
30
+ ...(last?.status ? { last_status: last.status } : {}), ...(last?.read_at ? { read_at: last.read_at } : {}),
31
+ ...(verified ? {} : dashboardCheck()), recovery: `evolink tasks wait ${taskId}` });
32
+ }
33
+
34
+ function pause(ms, signal) {
35
+ return new Promise(resolve => {
36
+ const timer = setTimeout(done, Math.max(0, ms));
37
+ function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); }
38
+ signal?.addEventListener('abort', done, { once: true });
39
+ if (signal?.aborted) done();
40
+ });
41
+ }
7
42
 
8
43
  function quoteError(error, cap) {
9
44
  const cause = fileError(error);
@@ -53,6 +88,12 @@ export function checkEstimate(quote, cap) {
53
88
  export class Media {
54
89
  constructor({ client, mcp = client, state, server, now = Date.now }) { this.client = mcp; this.state = state; this.server = server.href; this.now = now; }
55
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) {
56
97
  const { max_cost_usd, ...input } = args;
57
98
  let quote;
58
99
  try {
@@ -74,16 +115,69 @@ export class Media {
74
115
  ...(quote.effective_input ? { effective_input: quote.effective_input, defaults_applied: quote.defaults_applied } : {}),
75
116
  created_at: this.now(), expires_at: expires, ...(quote.account_quote ? { backend_estimate_id: quote.account_quote.quote.estimate_id,
76
117
  server_expires_at: serverExpiry, account_quote: quote.account_quote } : {}), state: 'quoted', client_request_id: `cli-${randomUUID()}` };
77
- await this.state.write('quotes', id, stored);
78
- return { ...quote, quote_id: id, input: input.input || {}, ...(max_cost_usd !== undefined ? { max_cost_usd, cap_source: 'user' } : {}), expires_at: new Date(stored.expires_at).toISOString(),
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(),
79
119
  requires_confirmation: true, next_step: `After the user approves, run evolink generate ${quote.type} --quote ${id} --confirm.` };
120
+ return { stored, view };
80
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; }
81
128
  async refresh(id) {
82
- const quote = await this.load(id);
83
- requireThat(quote.state === 'quoted' && !quote.task_id, 'submission_already_started',
84
- 'This submission has started. Recover its original task instead of refreshing its quote.');
85
- const { account_quote, pricing_quote, ...args } = quote.args;
86
- 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.` });
87
181
  }
88
182
  async load(id) {
89
183
  const quote = await this.state.read('quotes', id);
@@ -96,10 +190,13 @@ export class Media {
96
190
  async generate(kind, id, { confirmed = false, resume = false } = {}) {
97
191
  requireThat(['image', 'video', 'audio'].includes(kind), 'invalid_type', 'Choose image, video or audio.');
98
192
  requireThat(confirmed || resume, 'confirmation_required', 'Show the quote to the user and obtain approval before adding --confirm.');
99
- 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 () => {
100
196
  const quote = await this.load(id);
101
197
  requireThat(quote.type === kind, 'quote_type_mismatch', 'Use the media type shown in the saved quote.');
102
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);
103
200
  requireThat(quote.state !== 'refused', 'submission_refused',
104
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.',
105
202
  { quote_id: id, client_request_id: quote.client_request_id, charged: 'no', submission_allowed: false });
@@ -169,21 +266,51 @@ export class Media {
169
266
  const quote = await this.load(id);
170
267
  return this.generate(quote.type, id, { resume: true });
171
268
  }
172
- async wait(taskId, { timeout = 1800, signal, progress = () => {} } = {}) {
173
- 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;
174
277
  for (;;) {
175
- if (signal?.aborted) throw new CliError('interrupted', 'Stopped waiting locally. The EvoLink task continues.', { task_id: taskId }, 130);
176
- const remaining = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
177
- 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
+ }
178
298
  if (task.status === 'completed') return task;
179
299
  // task.error.code is the shared core's user-facing code, the one the API reports.
180
300
  if (['failed', 'cancelled'].includes(task.status)) {
181
301
  throw new CliError('task_failed', `The generation task ${task.status === 'failed' ? 'failed' : 'was cancelled'}${
182
302
  task.error?.code ? ` with error code ${task.error.code}` : ''}.`, { task });
183
303
  }
184
- progress(`${task.task_id}: ${task.status}${task.progress !== undefined ? ` (${task.progress}%)` : ''}`);
185
- if (Date.now() >= deadline) throw new CliError('wait_timeout', 'The task is still running. Continue with tasks wait.', { task_id: taskId });
186
- 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);
187
314
  }
188
315
  }
189
316
  }
@@ -4,7 +4,7 @@ import { gatewayAuthHeaders } from '../config.js';
4
4
  import { currentRequestCredentials } from '../request-context.js';
5
5
  import { classifyGatewayError, formatGatewayError } from './error-handler.js';
6
6
  import { parseBatchTasks, parseTaskReceipt, parseTaskResponse } from './task-response.js';
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
+ 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';
8
8
  // --- Error class for HTTP-level failures ---
9
9
  export class ApiHttpError extends Error {
10
10
  status;
@@ -12,6 +12,8 @@ export class ApiHttpError extends Error {
12
12
  requestId;
13
13
  info;
14
14
  submissionState;
15
+ /** Retry-After as the server sent it, without the general 30 s cap. */
16
+ requestedRetryAfterMs;
15
17
  constructor(status, message, retryAfterMs, requestId, info, submissionState) {
16
18
  super(message);
17
19
  this.status = status;
@@ -24,16 +26,21 @@ export class ApiHttpError extends Error {
24
26
  }
25
27
  // --- Retry logic ---
26
28
  const RETRYABLE_STATUS_CODES = new Set([429, 502, 503]);
27
- function sleep(ms) {
28
- const signal = currentRequestCredentials()?.http?.signal;
29
+ function sleep(ms, extra) {
30
+ const signals = [currentRequestCredentials()?.http?.signal, extra].filter((signal) => !!signal);
29
31
  return new Promise(resolve => {
30
32
  const timer = setTimeout(done, ms);
31
- function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); }
32
- signal?.addEventListener('abort', done, { once: true });
33
- 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))
34
38
  done();
35
39
  });
36
40
  }
41
+ function stopped(signal) {
42
+ return !!signal?.aborted || !!currentRequestCredentials()?.http?.signal?.aborted;
43
+ }
37
44
  function isRetryable(error) {
38
45
  // Key and balance rejections are always HTTP 402, so they are never retried here.
39
46
  if (error instanceof ApiHttpError)
@@ -46,7 +53,11 @@ function isRetryable(error) {
46
53
  return true; // network errors (DNS, reset, …)
47
54
  return false;
48
55
  }
49
- 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 = {}) {
50
61
  let lastError;
51
62
  for (let attempt = 0; attempt <= retries; attempt++) {
52
63
  try {
@@ -54,11 +65,25 @@ export async function withRetry(fn, retries, baseDelayMs) {
54
65
  }
55
66
  catch (error) {
56
67
  lastError = error;
57
- if (attempt < retries && isRetryable(error) && !currentRequestCredentials()?.http?.signal?.aborted) {
58
- const retryAfterMs = error instanceof ApiHttpError ? error.retryAfterMs : undefined;
59
- 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;
60
83
  continue;
61
84
  }
85
+ if (budget.deadline !== undefined && remainingMs(budget.deadline) < MIN_READ_MS)
86
+ throw budgetError(error);
62
87
  throw error;
63
88
  }
64
89
  }
@@ -80,6 +105,13 @@ async function rawRequest(config, options) {
80
105
  }
81
106
  body = options.body ? JSON.stringify(options.body) : undefined;
82
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
+ }
83
115
  }
84
116
  catch (error) {
85
117
  if (isPaid)
@@ -88,16 +120,18 @@ async function rawRequest(config, options) {
88
120
  }
89
121
  // Reading and verifying the body belong to the submission boundary too.
90
122
  try {
91
- const started = Date.now();
123
+ const started = monotonicNow();
92
124
  const response = await fetchWithTimeout(`${config.baseUrl}${options.path}`, {
93
- method: options.method, headers, body,
125
+ method: options.method, headers, body, ...(options.signal ? { signal: options.signal } : {}),
94
126
  }, timeout);
95
- 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);
96
128
  const requestId = responseRequestId(response.headers);
97
129
  if (!response.ok) {
98
130
  const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'));
99
131
  const info = classifyGatewayError(response.status, data, retryAfterMs, requestId);
100
- 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;
101
135
  }
102
136
  if (isPaid && (!data || typeof data !== 'object' || Array.isArray(data)
103
137
  || typeof data.id !== 'string'
@@ -168,18 +202,22 @@ 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);
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);
173
208
  return parseTaskResponse(data, taskId, requestId);
174
209
  }
175
210
  /** Up to 50 tasks in one call (POST /v1/tasks/batch); unknown or foreign IDs are simply absent. */
176
- export async function queryTasks(config, taskIds, tool = 'list_tasks') {
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 = {}) {
177
213
  const { data, requestId } = await withRetry(() => rawRequest(config, {
178
214
  method: 'POST',
179
215
  path: '/v1/tasks/batch',
180
216
  body: { task_ids: taskIds },
181
217
  tool,
182
- }), 2, 1500);
218
+ deadline: budget.deadline,
219
+ signal: budget.signal,
220
+ }), 2, 1500, budget);
183
221
  return parseBatchTasks(data, taskIds, requestId);
184
222
  }
185
223
  /** The account's recent tasks, newest first (GET /v1/tasks). Items carry no result links. */
@@ -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;
@@ -32,6 +33,26 @@ export class RequestTimeoutError extends Error {
32
33
  this.name = 'RequestTimeoutError';
33
34
  }
34
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
+ }
35
56
  export class SubmissionNotStartedError extends Error {
36
57
  cause;
37
58
  constructor(cause) {
@@ -94,17 +115,21 @@ export function timeoutFromEnv(name, fallback) {
94
115
  }
95
116
  return parsed;
96
117
  }
97
- 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()) {
98
120
  if (!value)
99
121
  return undefined;
100
122
  const seconds = Number(value.trim());
101
- if (Number.isFinite(seconds) && seconds >= 0) {
102
- return Math.min(Math.ceil(seconds * 1000), MAX_RETRY_DELAY_MS);
103
- }
123
+ if (Number.isFinite(seconds) && seconds >= 0)
124
+ return Math.ceil(seconds * 1000);
104
125
  const dateMs = Date.parse(value);
105
126
  if (!Number.isFinite(dateMs))
106
127
  return undefined;
107
- 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);
108
133
  }
109
134
  export function responseRequestId(headers) {
110
135
  return headers.get('x-request-id')?.trim()
@@ -143,8 +168,8 @@ export async function fetchWithTimeout(url, init, timeoutMs, fetchImpl) {
143
168
  }
144
169
  }
145
170
  /** Bound body consumption as well as response headers. Cancelling a reader also closes stalled streams. */
146
- export async function readJsonBody(response, timeoutMs = DEFAULT_READ_TIMEOUT_MS) {
147
- 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);
148
173
  const reader = response.body?.getReader();
149
174
  let timer;
150
175
  let abort;
@@ -165,9 +190,11 @@ export async function readJsonBody(response, timeoutMs = DEFAULT_READ_TIMEOUT_MS
165
190
  const stop = (error) => { reject(error); void reader?.cancel().catch(() => undefined); };
166
191
  timer = setTimeout(() => stop(new RequestTimeoutError(timeoutMs)), timeoutMs);
167
192
  abort = () => stop(new Error('Request interrupted during response read'));
168
- signal?.addEventListener('abort', abort, { once: true });
169
- if (signal?.aborted)
170
- abort();
193
+ for (const signal of signals) {
194
+ signal.addEventListener('abort', abort, { once: true });
195
+ if (signal.aborted)
196
+ abort();
197
+ }
171
198
  })]);
172
199
  if (!body)
173
200
  return {};
@@ -181,7 +208,8 @@ export async function readJsonBody(response, timeoutMs = DEFAULT_READ_TIMEOUT_MS
181
208
  finally {
182
209
  clearTimeout(timer);
183
210
  if (abort)
184
- signal?.removeEventListener('abort', abort);
211
+ for (const signal of signals)
212
+ signal.removeEventListener('abort', abort);
185
213
  reader?.releaseLock();
186
214
  }
187
215
  }
@@ -8,7 +8,7 @@ import { formatEstimateRange } from '../services/pricing-client.js';
8
8
  import { ApprovedAccountQuote, QuoteParameters, QuoteError } from '../services/pricing-quote-client.js';
9
9
  import { ApprovedRulesEstimate, createRulesEstimate, checkRulesApproval, rulesBudgetExceeded } from '../services/pricing-rules-estimate.js';
10
10
  import { PricingRulesError } from '../services/pricing-rules-client.js';
11
- import { CLIENT_REQUEST_ID_PATTERN, newRunId } from '../services/http-policy.js';
11
+ import { CLIENT_REQUEST_ID_PATTERN, monotonicNow, newRunId, remainingMs } from '../services/http-policy.js';
12
12
  import { formatUsd } from '../services/error-handler.js';
13
13
  import { MEDIA_SECONDS_DESCRIPTION, MEDIA_SECONDS_MAX, PAID, errorResult, failure, money, ok, progressReporter, usdOf } from './shared.js';
14
14
  import { RESULT_DELIVERY_GUIDANCE, TERMINAL_STATUSES, describeTask, waitForTask } from './task-format.js';
@@ -105,6 +105,7 @@ function registerGenerate(server, config, kind) {
105
105
  annotations: { title, ...PAID },
106
106
  }, async (args, extra) => {
107
107
  const started = Date.now();
108
+ const startedMono = monotonicNow();
108
109
  const credentials = currentRequestCredentials();
109
110
  const unavailable = !credentials?.serviceChannel && !credentials?.apiKey ? credentials?.unavailableReason : undefined;
110
111
  if (unavailable)
@@ -198,17 +199,19 @@ function registerGenerate(server, config, kind) {
198
199
  acceptedTaskId = submitted.id;
199
200
  let task = submitted;
200
201
  let statusCheck = 'not_requested';
201
- const waitUntil = started + WAIT_MS[kind];
202
- if ((!task.status || !TERMINAL_STATUSES.has(task.status)) && WAIT_MS[kind] > 0 && Date.now() + 3_000 < waitUntil) {
202
+ // The post-submit wait has its own deadline; it never bounds or interrupts the paid submission above.
203
+ const waitUntil = startedMono + WAIT_MS[kind];
204
+ if ((!task.status || !TERMINAL_STATUSES.has(task.status)) && WAIT_MS[kind] > 0 && remainingMs(waitUntil) > 3_000) {
203
205
  const report = progressReporter(extra, WAIT_MS[kind] / 1000);
204
206
  try {
205
- task = await waitForTask(config, submitted.id, {
207
+ const waited = await waitForTask(config, submitted.id, {
206
208
  deadline: waitUntil,
207
209
  tool: name,
208
210
  signal: extra.signal,
209
211
  onPoll: current => report((Date.now() - started) / 1000, `${current.status}${current.progress !== undefined ? `, ${current.progress}%` : ''}`),
210
212
  });
211
- statusCheck = 'verified';
213
+ task = waited.task;
214
+ statusCheck = waited.statusCheck;
212
215
  }
213
216
  catch {
214
217
  // The task exists; a failed status read must not turn a successful submit into an error.
@@ -1,20 +1,33 @@
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 { z } from 'zod';
4
- import { READ_ONLY, errorResult, ok, progressReporter } from './shared.js';
5
- import { RESULT_DELIVERY_GUIDANCE, TERMINAL_STATUSES, describeTask, waitForTask } from './task-format.js';
4
+ import { currentRequestCredentials } from '../request-context.js';
5
+ import { DEFAULT_READ_TIMEOUT_MS, monotonicNow, timeoutFromEnv } from '../services/http-policy.js';
6
+ import { READ_ONLY, errorResult, errorSummary, ok, progressReporter } from './shared.js';
7
+ import { RESULT_DELIVERY_GUIDANCE, TERMINAL_STATUSES, describeTask, setCallDeadline, waitForTask } from './task-format.js';
6
8
  export const TASK_ID = /^[A-Za-z0-9._:-]{4,128}$/;
7
9
  /** Codex and Cursor drop a tool call after about 60 s; the reply also needs time to travel. */
8
10
  export const MAX_WAIT_SECONDS = 45;
9
11
  const REPLY_MARGIN_MS = 2_000;
10
12
  const PROGRESS_EVERY_SECONDS = 10;
13
+ /**
14
+ * The monotonic deadline of one get_task call. A positive wait covers its reads, retries, pauses and polls,
15
+ * keeping a reply margin that shrinks with short windows (a 1 s wait keeps 100 ms, not 2 s). wait_seconds 0
16
+ * reads once within the read timeout. An embedding host's own deadline (the CLI's tasks wait) is never exceeded.
17
+ */
18
+ export function getTaskDeadline(startedMs, waitSeconds, outerDeadline) {
19
+ const singleRead = waitSeconds <= 0;
20
+ const windowMs = singleRead ? timeoutFromEnv('EVOLINK_MCP_READ_TIMEOUT_MS', DEFAULT_READ_TIMEOUT_MS) : waitSeconds * 1000;
21
+ const own = startedMs + windowMs - (singleRead ? 0 : Math.min(REPLY_MARGIN_MS, Math.round(windowMs / 10)));
22
+ return { deadline: outerDeadline === undefined ? own : Math.min(own, outerDeadline), singleRead };
23
+ }
11
24
  export function registerGetTask(server, config) {
12
25
  server.registerTool('get_task', {
13
26
  title: 'Get task status and results',
14
27
  description: [
15
28
  'Check one generation task and, while it is still running, wait up to wait_seconds (max 45) for it to finish. Free.',
16
29
  'Returns the status, progress, result links (they expire after 24 hours, so give them to the user right away), the final charge, or the error with a next step.',
17
- 'If the task is still running when this returns, call get_task again.',
30
+ 'If the task is still running when this returns, call get_task again. wait_seconds bounds the whole call, including retries; stopping a wait never cancels the task.',
18
31
  'Invalid bodies, mismatched IDs and unknown states return a query error with the original task ID and status_check unverified. Retry the free query; do not infer generation failure, zero charge or a refund. Missing optional fields are not zero. Completed resource tasks may return voice/persona IDs without links.',
19
32
  'Never call generate_image, generate_video or generate_audio again to check progress: that creates and charges a new task.',
20
33
  RESULT_DELIVERY_GUIDANCE,
@@ -22,32 +35,43 @@ export function registerGetTask(server, config) {
22
35
  inputSchema: {
23
36
  task_id: z.string().regex(TASK_ID).describe('task_id returned by generate_image, generate_video or generate_audio'),
24
37
  wait_seconds: z.number().int().min(0).max(MAX_WAIT_SECONDS).default(30)
25
- .describe('How long this call may wait for the task to finish (0–45 s, default 30). Use 0 for a quick check.'),
38
+ .describe('How long this call may wait for the task to finish (0–45 s, default 30), including reads and retries. Use 0 for one read without waiting for the task; that read can still take up to the read timeout (15 s by default).'),
26
39
  },
27
40
  annotations: { title: 'Get task status and results', ...READ_ONLY },
28
41
  }, async ({ task_id, wait_seconds }, extra) => {
29
- const started = Date.now();
42
+ const started = monotonicNow();
30
43
  const waitSeconds = Math.min(wait_seconds ?? 30, MAX_WAIT_SECONDS);
31
44
  const report = progressReporter(extra, waitSeconds);
32
45
  let lastReport = -PROGRESS_EVERY_SECONDS;
33
46
  try {
34
- const task = await waitForTask(config, task_id, {
35
- deadline: started + waitSeconds * 1000 - REPLY_MARGIN_MS,
47
+ const { deadline, singleRead } = getTaskDeadline(started, waitSeconds, currentRequestCredentials()?.http?.deadline);
48
+ setCallDeadline(extra, deadline);
49
+ const waited = await waitForTask(config, task_id, {
50
+ deadline,
51
+ singleRead,
36
52
  tool: 'get_task',
37
53
  signal: extra.signal,
38
54
  onPoll: async (current) => {
39
- const elapsed = (Date.now() - started) / 1000;
55
+ const elapsed = (monotonicNow() - started) / 1000;
40
56
  if (elapsed - lastReport < PROGRESS_EVERY_SECONDS)
41
57
  return;
42
58
  lastReport = elapsed;
43
59
  await report(elapsed, `${current.status}${current.progress !== undefined ? `, ${current.progress}%` : ''}`);
44
60
  },
45
61
  });
46
- const view = describeTask(task);
47
- if (!TERMINAL_STATUSES.has(task.status) && waitSeconds > 0) {
48
- const waited = Math.round((Date.now() - started) / 1000);
49
- view.lines.splice(1, 0, `Still running after waiting ${waited} s.`);
50
- view.structured.waited_seconds = waited;
62
+ const { task } = waited;
63
+ const view = describeTask(task, waited.statusCheck);
64
+ const waitedSeconds = Math.round((monotonicNow() - started) / 1000);
65
+ if (waited.statusCheck === 'unverified') {
66
+ view.lines.splice(1, 0, `Waited ${waitedSeconds} s. The last verified status was ${task.status} (read at ${waited.readAt}); a later read ${waited.ended === 'deadline' ? 'did not finish within the wait limit' : 'failed'}, so the latest status is unverified. Stopping this wait does not cancel the task.`);
67
+ Object.assign(view.structured, { read_at: waited.readAt, wait_ended: waited.ended, waited_seconds: waitedSeconds,
68
+ last_read_error: errorSummary(waited.readError) });
69
+ }
70
+ else if (!TERMINAL_STATUSES.has(task.status)) {
71
+ if (waitSeconds > 0)
72
+ view.lines.splice(1, 0, `Still running after waiting ${waitedSeconds} s (status read at ${waited.readAt}).`);
73
+ Object.assign(view.structured, { read_at: waited.readAt,
74
+ ...(waitSeconds > 0 ? { waited_seconds: waitedSeconds, wait_ended: waited.ended } : {}) });
51
75
  }
52
76
  return ok(view.lines.join('\n'), view.structured, view.resources);
53
77
  }
@@ -4,10 +4,17 @@ import { z } from 'zod';
4
4
  import { listTasks, queryTasks } from '../services/api-client.js';
5
5
  import { publicTaskErrorCode } from '../services/error-handler.js';
6
6
  import { parseBatchTasks } from '../services/task-response.js';
7
- import { DASHBOARD_CHECK_GUIDANCE, READ_ONLY, dashboardCheck, errorResult, failure, money, ok, usdOf } from './shared.js';
7
+ import { monotonicNow } from '../services/http-policy.js';
8
+ import { DASHBOARD_CHECK_GUIDANCE, READ_ONLY, dashboardCheck, errorResult, errorSummary, failure, money, ok, usdOf } from './shared.js';
8
9
  import { TASK_ID } from './get-task.js';
9
10
  import { RESULT_DELIVERY_GUIDANCE, RESULT_DELIVERY_INSTRUCTIONS, RESULT_LINK_HOURS, resultDeliveryMarkdown, resultLinks, resultResources, taskOutputs } from './task-format.js';
10
11
  const MAX_IDS = 50;
12
+ /** The verified base page answers a list; the optional detail read (result links, error codes) gets at most this long. */
13
+ const DETAILS_BUDGET_MS = 15_000;
14
+ let detailsBudgetMs = DETAILS_BUDGET_MS;
15
+ export function setDetailsBudgetForTests(ms) {
16
+ detailsBudgetMs = ms ?? DETAILS_BUDGET_MS;
17
+ }
11
18
  /** ISO 8601, unix seconds, or relative such as 30m, 2h, 1d. */
12
19
  export function parseSince(value, now = Date.now()) {
13
20
  const trimmed = value.trim();
@@ -72,6 +79,7 @@ export function registerListTasks(server, config) {
72
79
  'Use it to recover tasks after a lost connection or a timed-out submit before submitting anything again.',
73
80
  'Recent tasks cover the whole EvoLink account, newest first.',
74
81
  'partial means some rows or details could not be verified. Retain verified tasks and the base page, disclose incomplete coverage and query the original missing or details_missing IDs. Missing costs are not zero; do not regenerate to repair a read.',
82
+ 'details_status says whether result links and error codes were read for finished rows: retry details_retry_task_ids with task_ids (free); check rows whose details_reason is not_returned with get_task.',
75
83
  RESULT_DELIVERY_GUIDANCE,
76
84
  ].join(' '),
77
85
  inputSchema: {
@@ -90,7 +98,7 @@ export function registerListTasks(server, config) {
90
98
  .describe('Without task_ids: how many recent tasks to return (1–50, default 20).'),
91
99
  },
92
100
  annotations: { title: 'List generation tasks', ...READ_ONLY },
93
- }, async ({ task_ids, status, type, model, page: pageNumber, since, until, limit }) => {
101
+ }, async ({ task_ids, status, type, model, page: pageNumber, since, until, limit }, extra) => {
94
102
  try {
95
103
  if (task_ids && [status, type, model, pageNumber, since, until].some(value => value !== undefined)) {
96
104
  return failure('Choose task_ids or list filters, not both.', { error: { category: 'invalid_request' } });
@@ -148,24 +156,35 @@ export function registerListTasks(server, config) {
148
156
  return (sinceMs === undefined || item.created * 1000 >= sinceMs) && (untilMs === undefined || item.created * 1000 <= untilMs);
149
157
  });
150
158
  }
151
- // The list endpoint omits result links and error codes; read those tasks in one batch to include them.
159
+ // The list endpoint omits result links and error codes; read those tasks in one batch to include them. That read is
160
+ // optional: it has a short budget, and when it fails the verified base page stays, with the reason for each missing detail.
152
161
  const finished = items.filter(item => item.status === 'completed' && page.data.some(raw => raw?.id === item.id && raw.has_results === true) || item.status === 'failed')
153
162
  .map(item => item.id).slice(0, MAX_IDS);
154
163
  const details = new Map();
155
- let detailsMissing = [];
164
+ const reasons = new Map();
165
+ let detailsError;
156
166
  if (finished.length > 0) {
157
167
  try {
158
- const batch = await queryTasks(config, finished);
168
+ const batch = await queryTasks(config, finished, 'list_tasks', { deadline: monotonicNow() + detailsBudgetMs, signal: extra?.signal });
159
169
  for (const task of batch.tasks)
160
170
  details.set(task.id, task);
161
- detailsMissing = batch.missing;
162
171
  issues.push(...batch.issues);
172
+ const invalid = new Set(batch.issues.flatMap(issue => issue.task_id ? [issue.task_id] : []));
173
+ for (const id of batch.missing)
174
+ reasons.set(id, invalid.has(id) ? 'invalid' : 'not_returned');
163
175
  }
164
- catch {
165
- detailsMissing = finished;
176
+ catch (error) {
166
177
  issues.push({ code: 'task_details_unavailable' });
178
+ detailsError = errorSummary(error);
179
+ for (const id of finished)
180
+ reasons.set(id, 'read_failed');
167
181
  }
168
182
  }
183
+ const detailsMissing = [...reasons.keys()];
184
+ const detailsStatus = finished.length === 0 ? 'not_needed' : detailsError ? 'unavailable' : detailsMissing.length ? 'partial' : 'complete';
185
+ // A failed or invalid read may succeed when retried (free); a task the read did not return is checked on its own.
186
+ const detailsRetry = detailsMissing.filter(id => reasons.get(id) !== 'not_returned');
187
+ const notReturned = detailsMissing.filter(id => reasons.get(id) === 'not_returned');
169
188
  const rows = items.map(item => {
170
189
  const detailed = details.get(item.id);
171
190
  if (detailed)
@@ -173,8 +192,11 @@ export function registerListTasks(server, config) {
173
192
  const row = rowFromTask(item);
174
193
  // Compact pages do not establish a detailed execution error code.
175
194
  delete row.error_code;
176
- if (detailsMissing.includes(item.id))
195
+ const reason = reasons.get(item.id);
196
+ if (reason) {
177
197
  row.details_available = false;
198
+ row.details_reason = reason;
199
+ }
178
200
  return row;
179
201
  });
180
202
  const filters = [status && `status ${status}`, type && `type ${type}`, model && `model ${model}`, since && `since ${since}`, until && `until ${until}`].filter(Boolean).join(', ');
@@ -182,20 +204,35 @@ export function registerListTasks(server, config) {
182
204
  lines.push(...(rows.length > 0 ? rows.map(rowLine) : ['(none)']));
183
205
  if (issues.length || detailsMissing.length)
184
206
  lines.push(`Partial response: verified base rows were retained; some rows or details could not be verified. Missing details: ${detailsMissing.join(', ') || 'none'}. Query the original IDs again; do not infer zero usage or generate again.`);
207
+ if (detailsMissing.length) {
208
+ lines.push(`Details (result links, error codes, charges) were read for ${details.size} of ${finished.length} finished task${finished.length === 1 ? '' : 's'}.`);
209
+ if (detailsError)
210
+ lines.push(`The detail read failed (${[detailsError.code ?? detailsError.category, detailsError.status && `HTTP ${detailsError.status}`].filter(Boolean).join(', ')}).`);
211
+ if (detailsRetry.length)
212
+ lines.push(`Retrying is free: call list_tasks with task_ids ${JSON.stringify(detailsRetry)}.`);
213
+ if (notReturned.length)
214
+ lines.push(`Not returned by the detail read: ${notReturned.join(', ')}. Check each with get_task; this does not prove a task was never submitted.`);
215
+ }
185
216
  if (rows.some(row => row.response_warnings))
186
217
  lines.push('Some optional fields were omitted; missing values do not mean zero. See response_warnings.');
187
218
  const websiteCheck = issues.length > 0 || detailsMissing.length > 0 || rows.some(row => row.response_warnings || ['failed', 'cancelled'].includes(row.status));
188
219
  if (websiteCheck)
189
220
  lines.push(DASHBOARD_CHECK_GUIDANCE);
190
221
  const nextPage = page.page * page.page_size < page.total ? page.page + 1 : null;
222
+ const lastPage = Math.max(1, Math.ceil(page.total / page.page_size));
223
+ // An empty page past the end is not an empty account.
224
+ if (rows.length === 0 && page.page > lastPage)
225
+ lines.push(`Page ${page.page} is past the last page (${lastPage}) of ${page.total} tasks; use pages 1–${lastPage}.`);
191
226
  lines.push(`Page ${page.page}; ${page.total} tasks before page-local time filtering.${nextPage ? ` Continue with page ${nextPage}.` : ''}`);
192
227
  if (rows.some(row => row.results))
193
228
  lines.push(`Result links expire after ${RESULT_LINK_HOURS} hours.`);
194
229
  if (rows.some(row => row.results))
195
230
  lines.push(`Next step: ${RESULT_DELIVERY_INSTRUCTIONS}`);
196
231
  return ok(lines.join('\n'), { tasks: rows, total: page.total, page: page.page, page_size: page.page_size,
197
- next_page: nextPage, time_filter_scope: 'selected_page', total_scope: 'server_filters_before_time_filter',
232
+ next_page: nextPage, last_page: lastPage, time_filter_scope: 'selected_page', total_scope: 'server_filters_before_time_filter',
198
233
  partial: issues.length > 0 || detailsMissing.length > 0, issues, details_missing: detailsMissing,
234
+ details_status: detailsStatus, details_coverage: { needed: finished.length, returned: details.size },
235
+ ...(detailsRetry.length ? { details_retry_task_ids: detailsRetry } : {}), ...(detailsError ? { details_error: detailsError } : {}),
199
236
  ...(websiteCheck ? dashboardCheck() : {}),
200
237
  }, rows.flatMap(row => resultResources(row.task_id, row.results ?? [])));
201
238
  }
@@ -5,7 +5,7 @@ import { publicIdentifier, publicErrorDetails, publicText } from '../services/pu
5
5
  import { processCredentialsAllowed } from '../request-context.js';
6
6
  import { ApiHttpError } from '../services/api-client.js';
7
7
  import { CREDITS_PER_USD, formatCredits, formatUsd } from '../services/error-handler.js';
8
- import { API_KEYS_URL, DASHBOARD_URL, PaidRequestOutcomeUnknownError, RequestTimeoutError, SubmissionNotStartedError } from '../services/http-policy.js';
8
+ import { API_KEYS_URL, DASHBOARD_URL, PaidRequestOutcomeUnknownError, RequestTimeoutError, SubmissionNotStartedError, TaskQueryTimeoutError } from '../services/http-policy.js';
9
9
  import { trackedLink } from '../services/utm.js';
10
10
  import { TaskResponseError } from '../services/task-response.js';
11
11
  /** Free lookups: clients can run them without asking. */
@@ -71,6 +71,11 @@ function infoFor(error) {
71
71
  retryable: true,
72
72
  };
73
73
  }
74
+ if (error instanceof TaskQueryTimeoutError)
75
+ return {
76
+ status: 0, category: 'server_error', code: error.code, message: error.message,
77
+ next_step: 'Query the original task again later. Its status, charge and refund are unverified; do not generate again.', retryable: true,
78
+ };
74
79
  if (error instanceof RequestTimeoutError || error instanceof TypeError) {
75
80
  return { status: 0, category: 'server_error', message: 'EvoLink did not respond in time.', next_step: 'Retry in a minute.', retryable: true };
76
81
  }
@@ -92,6 +97,11 @@ function infoFor(error) {
92
97
  retryable: false,
93
98
  };
94
99
  }
100
+ /** Category, code and HTTP status of an error, without its message: enough to say why a later read failed. */
101
+ export function errorSummary(error) {
102
+ const info = infoFor(error);
103
+ return { category: info.category, ...(info.code ? { code: info.code } : {}), ...(info.status ? { status: info.status } : {}) };
104
+ }
95
105
  /** Converts a thrown error into a tool error with a category and a concrete next step. */
96
106
  export function errorResult(error, context = {}) {
97
107
  const info = infoFor(error);
@@ -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 { queryTask } from '../services/api-client.js';
4
+ import { MIN_READ_MS, TaskQueryTimeoutError, remainingMs } from '../services/http-policy.js';
4
5
  import { publicIdentifier } from '../services/public-error.js';
5
6
  import { publicTaskError } from '../services/error-handler.js';
6
7
  import { taskBilling } from './task-billing.js';
@@ -273,18 +274,66 @@ export function pollIntervalMs(type) {
273
274
  return 6_000;
274
275
  return 3_000;
275
276
  }
276
- /** Reads a task until it finishes or the deadline passes, pacing reads by task type. */
277
+ /** A progress notification may not hold the wait; it continues on its own if slow. */
278
+ const PROGRESS_SEND_LIMIT_MS = 1_000;
279
+ const callDeadlines = new WeakMap();
280
+ /** Records the wait deadline of one tool call, so optional work after it (previews) stays inside the call's window. */
281
+ export function setCallDeadline(extra, deadline) {
282
+ if (extra && typeof extra === 'object')
283
+ callDeadlines.set(extra, deadline);
284
+ }
285
+ export function callDeadline(extra) {
286
+ return extra && typeof extra === 'object' ? callDeadlines.get(extra) : undefined;
287
+ }
288
+ /** A late timer still leaves a planned read twice the hard minimum, so the read's own check never sees a shorter window. */
289
+ const READ_START_MS = 2 * MIN_READ_MS;
290
+ /**
291
+ * A later read is planned only when at least this much of the wait is left after its pause. A read of an unfinished
292
+ * task syncs with the provider and can take a second or more; started with less time, it would likely be cut at the
293
+ * deadline and only turn the verified snapshot into an unverified one. The first read of a wait is not limited by it.
294
+ */
295
+ export const NEXT_READ_MIN_MS = 2_000;
296
+ async function boundedPoll(pending, limitMs) {
297
+ if (!pending)
298
+ return;
299
+ let timer;
300
+ await Promise.race([pending.catch(() => undefined),
301
+ new Promise(resolve => { timer = setTimeout(resolve, Math.max(0, Math.min(PROGRESS_SEND_LIMIT_MS, limitMs))); })]);
302
+ clearTimeout(timer);
303
+ }
304
+ /**
305
+ * Reads a task until it finishes or its wait ends, pacing reads by task type.
306
+ * One deadline covers every read, retry, pause and poll: nothing starts that cannot finish before it, and a later read
307
+ * needs NEXT_READ_MIN_MS. The first read's failure is thrown; a later failure returns the last valid snapshot as unverified.
308
+ */
277
309
  export async function waitForTask(config, taskId, options) {
278
- let task = options.initial ?? await queryTask(config, taskId, options.tool);
279
- while (!TERMINAL_STATUSES.has(task.status) && !options.signal?.aborted) {
310
+ const read = () => queryTask(config, taskId, options.tool, { deadline: options.deadline, signal: options.signal, ...(options.singleRead ? { retries: 0 } : {}) });
311
+ let task = options.initial ?? await read();
312
+ let readAt = new Date().toISOString();
313
+ for (;;) {
314
+ if (TERMINAL_STATUSES.has(task.status))
315
+ return { task, statusCheck: 'verified', readAt, ended: 'terminal' };
316
+ if (options.signal?.aborted)
317
+ return { task, statusCheck: 'verified', readAt, ended: 'cancelled' };
280
318
  const interval = pollIntervalMs(task.type);
281
- if (Date.now() + interval > options.deadline)
282
- break;
283
- await options.onPoll?.(task);
319
+ if (options.singleRead || remainingMs(options.deadline) < interval + NEXT_READ_MIN_MS) {
320
+ return { task, statusCheck: 'verified', readAt, ended: 'deadline' };
321
+ }
322
+ await boundedPoll(options.onPoll?.(task), remainingMs(options.deadline) - interval - NEXT_READ_MIN_MS);
284
323
  await sleep(interval, options.signal);
285
324
  if (options.signal?.aborted)
286
- break;
287
- task = await queryTask(config, taskId, options.tool);
325
+ return { task, statusCheck: 'verified', readAt, ended: 'cancelled' };
326
+ // Only a late timer gets here with little time left. No read was attempted, so the snapshot is still verified.
327
+ if (remainingMs(options.deadline) < READ_START_MS)
328
+ return { task, statusCheck: 'verified', readAt, ended: 'deadline' };
329
+ try {
330
+ task = await read();
331
+ readAt = new Date().toISOString();
332
+ }
333
+ catch (error) {
334
+ // Never present the earlier snapshot as freshly read.
335
+ const ended = options.signal?.aborted ? 'cancelled' : error instanceof TaskQueryTimeoutError ? 'deadline' : 'read_failed';
336
+ return { task, statusCheck: 'unverified', readAt, ended, readError: error };
337
+ }
288
338
  }
289
- return task;
290
339
  }
@@ -1,4 +1,4 @@
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
  /** Version reported in serverInfo and in the X-Evo-Client-Version header. */
4
- export const MCP_VERSION = '1.9.0';
4
+ export const MCP_VERSION = '1.10.0';
@@ -2,7 +2,7 @@
2
2
  "schema_version": 1,
3
3
  "repository": "Evolink-AI/evolink-mcp",
4
4
  "baseline": "acc9fd43b945e3917b47809fc94f85ba26c7c8db",
5
- "source_sha256": "29ca2f1978406a8791fbbd3aaa17a6b7649ea4c639113c9a35fc4381e80131a0",
5
+ "source_sha256": "6532b781fb30919efbd4d448e07efbbaa15ff15cff4b64ebaafe880db83867c9",
6
6
  "files": {
7
7
  "packages/core/src/branding.ts": "534b944a1370f210a3858c1a85b1a23071aca8e26b7a3e70e4d859ba5b152ff7",
8
8
  "packages/core/src/config.ts": "208496230e22f43817cfb9b3805cde279fcce61a82227dfbd9f63485a33d33c7",
@@ -12,13 +12,13 @@
12
12
  "packages/core/src/data/model-params.ts": "1296c1b85dc0bd5fa1b201269318b5301aeac60a3fb208c198ced3127ad51be3",
13
13
  "packages/core/src/platform-client.ts": "d272d1fbd7939acd69482207f1a75550e4ff8f584deee8f6d0c8ace86e453b6d",
14
14
  "packages/core/src/platform-operations.ts": "3239283b4cff2490dd42ac006d03165ef2843eb05cfaece3572d1aacde2e7e32",
15
- "packages/core/src/request-context.ts": "22ca68d74abc6d5549e20362c6081179d5888f884f74371a95280009d4a59225",
16
- "packages/core/src/server.ts": "22d3ef130ad5f7c906deb7ea02454df6767c0208b56e838b239ba85bec6103ad",
17
- "packages/core/src/services/api-client.ts": "aee5d028506bfe8e090fa9a553635429ba4faf49273ef583187a612b635d4291",
15
+ "packages/core/src/request-context.ts": "9ea80bd59a97fd63571ffae68176f825e444cdd53d7496c608f0a163a01b4f57",
16
+ "packages/core/src/server.ts": "64bc646ebac0256f470bc8022cb2bd05ee426e581c9b6544556d257bd946bed4",
17
+ "packages/core/src/services/api-client.ts": "f9755fd2b0783accb3032b51ee40fa4b02a3306b1b3c02ad91ce3980865f169f",
18
18
  "packages/core/src/services/catalog-client.ts": "c2bcfb0f2780112bcddf6a42537cf9f6264717d0b3685c896790339b0f9bb7df",
19
19
  "packages/core/src/services/error-handler.ts": "fd07d5dbd4cad3b4e75d7192c4d49623d92666fef40bd688646e0f756c208d5a",
20
20
  "packages/core/src/services/file-client.ts": "9bd94da9a0719fba0050be261fb5210397be4e8b9e6ebc8a2e916fcc185fd2d2",
21
- "packages/core/src/services/http-policy.ts": "7e0f6419c833251da7163bd7ac6a7060f149be62cc90c7cf175f66a37c365d58",
21
+ "packages/core/src/services/http-policy.ts": "75853ef3635ca0f2f48e37334d211240bd10ba4b97ed6d892622d808c3e6c977",
22
22
  "packages/core/src/services/media-preview.ts": "89410d8eb9a02e6fb9d9bc0de8a69b48bec7a06039e54569b9fea7e35527b6c4",
23
23
  "packages/core/src/services/model-capabilities.ts": "b41c8b6dd34432cd2e44529e7f40aa1dd7c3b5d0d20e5964b78468517e1979df",
24
24
  "packages/core/src/services/model-catalog.ts": "0cad28a41774ea99ff6caf66860ac33a02e8fab254243368d502935b33842364",
@@ -40,19 +40,19 @@
40
40
  "packages/core/src/tools/check-balance.ts": "f27b269a3c3c838a54fe54005eb72f637ddfdc2982d932901282bbf072d1efca",
41
41
  "packages/core/src/tools/discovery.ts": "50adaf61d2e159a78348661b1b49b0332d47079275f943da67b5f132f8997218",
42
42
  "packages/core/src/tools/estimate-cost.ts": "685ff2cbfcb97ddba51e2f0e0f79681851ffdb194558bef95825e3465c74f3ea",
43
- "packages/core/src/tools/generate.ts": "05d67b8f5d291d6360e463d430dcb8cc8b1462f2e18d18a30b18eb199692c3c7",
43
+ "packages/core/src/tools/generate.ts": "d53b8b42919d3ef02f53c5fc23f8dab32606a029460b67f145ab204be5168ca4",
44
44
  "packages/core/src/tools/get-model.ts": "c322861d2bb0436de28a8eda634ae3d2fbb97dda95fc93e704a3bdcac82f5986",
45
45
  "packages/core/src/tools/get-pricing-rules.ts": "6fdd62f1f09804c6149c423f8203c89b8e9a7c181f661e0d49d7468f7ceb5f00",
46
- "packages/core/src/tools/get-task.ts": "6c656893927d65806c855726568cf574553fffa9b8269efb0a180472358d8799",
47
- "packages/core/src/tools/list-tasks.ts": "1cb1a0fda2b39b544e2813de16393a5603a07cb04b4f9f736446b30367b0a457",
46
+ "packages/core/src/tools/get-task.ts": "41aa5d994c2820096c38c01d69bcea56adfbc6f500314d6858e2ba54aa63520d",
47
+ "packages/core/src/tools/list-tasks.ts": "4f28537439179ae73db2836900ac7196fa7259803f6786ce310c1e77aa3d6c5b",
48
48
  "packages/core/src/tools/prepare-upload.ts": "c58cfb04725cc660e34f68391727e99f726e355f9329d91ced56878212294d40",
49
49
  "packages/core/src/tools/search-models.ts": "3b950140240ac6c5f0dfdc0264cb4b66d0583e05e220c67245b6e8a7616fc55e",
50
- "packages/core/src/tools/shared.ts": "96bf26192a2a8bc1c326a54500761efd6c15959803eacdfe44f5de8ea23d3ed7",
50
+ "packages/core/src/tools/shared.ts": "6c9350d4d5d27203d40ea51a2d9e5037457dcaf2a4e033ae882c36e18cb2a0f1",
51
51
  "packages/core/src/tools/task-billing.ts": "bf0dec37aed3fc5396d653c481b790ea63a413c23fc78e2949f8c288c53f9e12",
52
- "packages/core/src/tools/task-format.ts": "5f6536ce15d42a67fec741dd3c9863960bfc1d0580a3a500da92aa52e2fe63d5",
52
+ "packages/core/src/tools/task-format.ts": "fea6591b9fc7b9bd33862bc154ba28baba163ca022e5b1e7e1480cc52a3289e5",
53
53
  "packages/core/src/tools/task-usage.ts": "ba05d054e1d60d67f6ab75cc6d9169f453c87e0e89c17a2c1be5fc429e8f9f47",
54
54
  "packages/core/src/tools/upload-file.ts": "da6f239d1b1e6a13a7b418d24e738ebabf9823b2656111eeaa70eb247421ad40",
55
- "packages/core/src/version.ts": "f3eee957b447a0ec39b03de0c7ccdb440dda84b00d6454d2b48e50be4a6f6385"
55
+ "packages/core/src/version.ts": "37136bbc2d3059c33d31792130ebfbae3c7b95f0a348f7cc1a5e8beb159ea156"
56
56
  },
57
57
  "artifacts": {
58
58
  "core/src/config.js": "e5f001e6bb30fa3ca49ca1383b3deb83ea495d20079adefad6d0451f5bbee0e3",
@@ -63,11 +63,11 @@
63
63
  "core/src/platform-client.js": "7268a23e0c42ac454bc78bb4a768166670ad3996c13fa88ede03007dbee755e7",
64
64
  "core/src/platform-operations.js": "534da709afd69e664c25e173adb8662644340b7024666036c0c98347e8833cfc",
65
65
  "core/src/request-context.js": "ed22b79db1fc8b20c57f0a58e938ff4a833bb6a75a16d2246f732a41256c21e8",
66
- "core/src/services/api-client.js": "d58656608beaa078233b95e4f2794eab163da78fa82fce3325c823d9477a434b",
66
+ "core/src/services/api-client.js": "5983cdb09e97f3599f00b85a59b7ee1785d296bd61627c916a03be393749c074",
67
67
  "core/src/services/catalog-client.js": "f438fdb13fa9e9ddbf539b265bfcbb77c4d5024835130cbade3b83e9952893cf",
68
68
  "core/src/services/error-handler.js": "edea48a8eaf90b4193a503c0418ba7157acabfe89833a39c1d41bbf568de8355",
69
69
  "core/src/services/file-client.js": "d11798bfddc6637727a874532ad218b5deac58d6bca8f20abcd2c30b132210e4",
70
- "core/src/services/http-policy.js": "c3e6fe080afefdc65a9ec67115e6dc2f4fddb9c0fd58e30d414222e599f6f35b",
70
+ "core/src/services/http-policy.js": "1a78c5d1fa34fec4ef9044efd67e44d30b13a5afdc50e70b394e0e370116a2ff",
71
71
  "core/src/services/model-capabilities.js": "2ad86bc08c82cce82964b18d6187632fc738f8cd17d03de1ef04f27b1e35cfe1",
72
72
  "core/src/services/model-catalog.js": "e25b005d48a38106565919cdfb50abf2b018b92e7d762a88470ba3af1ba2fa06",
73
73
  "core/src/services/model-recommendations.js": "f330f941d26aa9fc127c2f7479cb2be026d6111a3f3066e89442ff29ec33803a",
@@ -85,16 +85,16 @@
85
85
  "core/src/tools/check-balance.js": "75baa61e57e289fd61a45251665df599967ba0beb4b33cc3976280a9d89421bf",
86
86
  "core/src/tools/discovery.js": "6095a2f699fbf465bcae3387b137901ecdbbbb00bbfa6f4b3250a7c293c45b70",
87
87
  "core/src/tools/estimate-cost.js": "bda58bfbafc0c76e4e3354f4b77aa7d9fef2aa5b43e742f611a8630ca5376fb5",
88
- "core/src/tools/generate.js": "1fa64509a860f7c4a7b723ea5ce79d2f8408dc0a3853ce1e76df4c921a47a79f",
88
+ "core/src/tools/generate.js": "249f74487dce95be0acba73382ae785ac71d2cac7e786018d9c53397c14db3c7",
89
89
  "core/src/tools/get-model.js": "84334af0c5c0eb648fbe53a929de241ff1f86faa39c7f091987d0cd532f96976",
90
90
  "core/src/tools/get-pricing-rules.js": "3dcab9b74ec08156a27f34a0930363b7dead5d00bba8e6cdbb47cd68ea76aaad",
91
- "core/src/tools/get-task.js": "a8e67526ebaa381c360667c13cc69e3a3db310ef7b64435da698b0748fe8cb41",
92
- "core/src/tools/list-tasks.js": "791d9b688e0425a9ddc1bb694313f7b94077dee1437254db8ebd363257edee97",
91
+ "core/src/tools/get-task.js": "8803606894bfa0fed3da3177ce17818c03938973108a5b5e0477103b52ba9e9b",
92
+ "core/src/tools/list-tasks.js": "d2ce0d4e9fe1f885c6c3304e6ad9d33e589d6450c8ab680588b021bd2f0e3356",
93
93
  "core/src/tools/search-models.js": "9850b7d2d74a1d69229400d465b21ecb9ede79c75dddeb41787668f418c5bd06",
94
- "core/src/tools/shared.js": "1bbc7ac4a0d8e9bcba382f063f5422269cddf4742389b920503d3bafbb01f414",
94
+ "core/src/tools/shared.js": "3dc775fc92c732bfeac005a3b28874cc919f30831f353c6b1a20bfd19f7005e3",
95
95
  "core/src/tools/task-billing.js": "f49b252afcaf4a6275f5db6ebc8e6380387b2406bd5fc91e7367e3523025af8b",
96
- "core/src/tools/task-format.js": "ac8f8eac7d95b7e25618c78de391f37a9eeb785fee3213d130e7d370cd200fdb",
96
+ "core/src/tools/task-format.js": "13c558fab7278cb62c07df924eb37a0d0f1771fdd0c531b661e8499e7c2393b3",
97
97
  "core/src/tools/task-usage.js": "3aae5d7807efc2c762bf604cf9ecfecf8f9008185bcef584e6d4243404418dc5",
98
- "core/src/version.js": "05d7ca646738513202228de9b9f149b3757efec3b0d970df5474f64f84194813"
98
+ "core/src/version.js": "b0eef643b0b4f37d0894d0856c2575f99158d4dee57292207f3c9b7122e7fbae"
99
99
  }
100
100
  }