@evolinkai/cli 0.11.0 → 0.13.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 (33) hide show
  1. package/README.md +6 -3
  2. package/package.json +2 -2
  3. package/skills/evolink-cli/SKILL.md +5 -3
  4. package/skills/evolink-cli/references/usage-and-budget.md +3 -1
  5. package/src/api.mjs +7 -6
  6. package/src/auth.mjs +14 -3
  7. package/src/cli.mjs +21 -6
  8. package/src/media.mjs +149 -16
  9. package/src/platform/core/src/data/model-constraints.js +9 -0
  10. package/src/platform/core/src/data/model-params.overrides.generated.js +1 -1
  11. package/src/platform/core/src/platform-operations.js +1 -1
  12. package/src/platform/core/src/services/api-client.js +56 -18
  13. package/src/platform/core/src/services/catalog-client.js +28 -2
  14. package/src/platform/core/src/services/http-policy.js +39 -11
  15. package/src/platform/core/src/services/mj-prompt.js +18 -0
  16. package/src/platform/core/src/services/model-capabilities.js +2 -1
  17. package/src/platform/core/src/services/pricing-call-limit.js +40 -0
  18. package/src/platform/core/src/services/pricing-derived.js +59 -0
  19. package/src/platform/core/src/services/pricing-quote-client.js +30 -7
  20. package/src/platform/core/src/services/pricing-rules-client.js +38 -3
  21. package/src/platform/core/src/services/pricing-rules-estimate.js +128 -10
  22. package/src/platform/core/src/tools/estimate-cost.js +26 -10
  23. package/src/platform/core/src/tools/generate.js +27 -12
  24. package/src/platform/core/src/tools/get-model.js +16 -0
  25. package/src/platform/core/src/tools/get-pricing-rules.js +13 -4
  26. package/src/platform/core/src/tools/get-task.js +37 -13
  27. package/src/platform/core/src/tools/list-tasks.js +47 -10
  28. package/src/platform/core/src/tools/search-models.js +4 -1
  29. package/src/platform/core/src/tools/shared.js +15 -1
  30. package/src/platform/core/src/tools/task-format.js +58 -9
  31. package/src/platform/core/src/version.js +1 -1
  32. package/src/platform/source.json +51 -45
  33. package/src/state.mjs +12 -1
@@ -8,9 +8,9 @@ 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
- import { MEDIA_SECONDS_DESCRIPTION, MEDIA_SECONDS_MAX, PAID, errorResult, failure, money, ok, progressReporter, usdOf } from './shared.js';
13
+ import { MEDIA_SECONDS_DESCRIPTION, MEDIA_SECONDS_MAX, PAID, errorResult, failure, money, ok, progressReporter, retryText, usdOf } from './shared.js';
14
14
  import { RESULT_DELIVERY_GUIDANCE, TERMINAL_STATUSES, describeTask, waitForTask } from './task-format.js';
15
15
  import { PAID_GENERATION_GUIDANCE } from '../tool-guidance.js';
16
16
  import { currentRequestCredentials } from '../request-context.js';
@@ -51,7 +51,7 @@ function rangeText(estimate) {
51
51
  /** Why max_cost_usd could not be checked, and what the assistant can do next. */
52
52
  function uncheckedCap(estimate, pricingWarning) {
53
53
  if (estimate.uncheckable_reason === 'usage')
54
- return ['published pricing rules need additional billing usage to calculate a complete estimate', `Provide the missing expected or measured usage in pricing_parameters. ${estimate.possible_extras.join(' ')}`];
54
+ return ['published pricing rules need additional billing usage to calculate a complete estimate', `Provide the missing expected or measured usage. ${(estimate.usage_help ?? estimate.possible_extras).join(' ')}`];
55
55
  if (estimate.uncheckable_reason === 'output_duration') {
56
56
  return ['the generated output duration is not fixed, so the declared seconds cannot establish an upper bound', 'Use an explicit duration if the model accepts it; otherwise ask the user whether to proceed without a cap.'];
57
57
  }
@@ -91,7 +91,7 @@ function registerGenerate(server, config, kind) {
91
91
  model: z.string().min(1).max(128).describe(`${kind[0].toUpperCase()}${kind.slice(1)} model ID from search_models.`),
92
92
  // The cap is checked in the handler: a schema limit makes the SDK answer with a bare validation error.
93
93
  prompt: z.string().optional().describe(`Shortcut for input.prompt; up to ${PROMPT_SHORTCUT_MAX.toLocaleString('en-US')} characters (get_model lists the model's own limit).`),
94
- input: z.record(z.unknown()).optional()
94
+ input: z.record(z.string(), z.unknown()).optional()
95
95
  .describe('Model parameters exactly as listed by get_model, e.g. {"prompt":"…","quality":"1080p"}. Do not put model or callback_url here.'),
96
96
  client_request_id: z.string().regex(CLIENT_REQUEST_ID_PATTERN).optional()
97
97
  .describe('Optional idempotency key (16–96 characters: letters, digits, . _ -). Reuse the same value only to retry the same request after a network error or timeout.'),
@@ -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)
@@ -164,7 +165,8 @@ function registerGenerate(server, config, kind) {
164
165
  // media_seconds only prices the request; the body below is built from input alone.
165
166
  if (args.account_quote)
166
167
  throw new QuoteError('quote_refresh_required', 'Refresh the legacy account estimate with estimate_cost and obtain user approval.');
167
- const rulesEstimate = await createRulesEstimate(entry, effectiveInput, { mediaSeconds: args.media_seconds, pricingParameters: args.pricing_parameters });
168
+ const rulesEstimate = await createRulesEstimate(entry, effectiveInput, { mediaSeconds: args.media_seconds, pricingParameters: args.pricing_parameters,
169
+ purpose: 'generation', signal: extra.signal });
168
170
  if (args.pricing_quote)
169
171
  checkRulesApproval(args.pricing_quote, rulesEstimate);
170
172
  const estimate = rulesEstimate.estimate;
@@ -185,8 +187,14 @@ function registerGenerate(server, config, kind) {
185
187
  });
186
188
  }
187
189
  }
188
- if (estimate.status === 'needs_input')
189
- throw new QuoteError('quote_usage_required', 'No charge can be estimated yet; supply the missing pricing usage before submission.');
190
+ if (estimate.status === 'needs_input') {
191
+ return failure([`No total can be estimated for ${entry.id} yet, so nothing was submitted or charged. The total depends on:`,
192
+ ...(estimate.usage_help ?? []).map(line => `- ${line}`),
193
+ 'Estimate again with this usage and get the user\'s approval before generating.'].join('\n'), {
194
+ error: { category: 'estimate_unavailable', code: 'quote_usage_required' },
195
+ missing_usage: estimate.missing_usage, usage_help: estimate.usage_help, charged: 'no', submission_state: 'not_submitted'
196
+ });
197
+ }
190
198
  clientRequestId = args.client_request_id ?? newRunId();
191
199
  const body = { ...effectiveInput, model: entry.id };
192
200
  const submitted = await submitTask(config, {
@@ -198,17 +206,19 @@ function registerGenerate(server, config, kind) {
198
206
  acceptedTaskId = submitted.id;
199
207
  let task = submitted;
200
208
  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) {
209
+ // The post-submit wait has its own deadline; it never bounds or interrupts the paid submission above.
210
+ const waitUntil = startedMono + WAIT_MS[kind];
211
+ if ((!task.status || !TERMINAL_STATUSES.has(task.status)) && WAIT_MS[kind] > 0 && remainingMs(waitUntil) > 3_000) {
203
212
  const report = progressReporter(extra, WAIT_MS[kind] / 1000);
204
213
  try {
205
- task = await waitForTask(config, submitted.id, {
214
+ const waited = await waitForTask(config, submitted.id, {
206
215
  deadline: waitUntil,
207
216
  tool: name,
208
217
  signal: extra.signal,
209
218
  onPoll: current => report((Date.now() - started) / 1000, `${current.status}${current.progress !== undefined ? `, ${current.progress}%` : ''}`),
210
219
  });
211
- statusCheck = 'verified';
220
+ task = waited.task;
221
+ statusCheck = waited.statusCheck;
212
222
  }
213
223
  catch {
214
224
  // The task exists; a failed status read must not turn a successful submit into an error.
@@ -266,7 +276,12 @@ function registerGenerate(server, config, kind) {
266
276
  }
267
277
  catch (error) {
268
278
  if (error instanceof PricingRulesError)
269
- return failure('The pricing rules could not be verified. Nothing was submitted or charged.', { error: { category: 'estimate_unavailable', code: error.code }, charged: 'no', submission_state: 'not_submitted' });
279
+ return failure(error.code === 'rate_limit_exceeded'
280
+ ? `The platform is limiting pricing requests right now, so the price could not be checked and nothing was submitted or charged. Try again in ${retryText(error.retryAfter)}.`
281
+ : 'The pricing rules could not be verified. Nothing was submitted or charged.', {
282
+ error: { category: 'estimate_unavailable', code: error.code, ...(error.retryAfter !== undefined ? { retry_after_seconds: error.retryAfter } : {}) },
283
+ charged: 'no', submission_state: 'not_submitted'
284
+ });
270
285
  if (error instanceof QuoteError)
271
286
  return failure(`${error.message} Nothing was submitted or charged.`, { error: { category: 'estimate_unavailable', code: error.code }, charged: 'no', submission_state: 'not_submitted' });
272
287
  // clientRequestId is set right before the submit, so it also tells whether a request may have gone out.
@@ -4,6 +4,8 @@ import { z } from 'zod';
4
4
  import { modelParamsMeta } from '../data/model-params.js';
5
5
  import { resolveModel, suggestModels } from '../services/model-catalog.js';
6
6
  import { billedByMediaLength, formatPrice } from '../services/pricing-client.js';
7
+ import { cachedPricingRules } from '../services/pricing-rules-client.js';
8
+ import { billingUsageHelp } from '../services/pricing-rules-estimate.js';
7
9
  import { formatUsd } from '../services/error-handler.js';
8
10
  import { trackedLink } from '../services/utm.js';
9
11
  import { READ_ONLY, errorResult, failure, ok } from './shared.js';
@@ -37,6 +39,15 @@ export function describeParam(name, spec, indent = '') {
37
39
  }
38
40
  return lines;
39
41
  }
42
+ /**
43
+ * The rules name the usage a total needs. Only the full list the catalog has just cached for the prices is read, so
44
+ * get_model asks the platform for nothing more; without it, estimate_cost still reports missing usage itself.
45
+ */
46
+ function billingUsage(entry) {
47
+ const body = cachedPricingRules({ view: 'full' });
48
+ const rule = body && 'models' in body ? body.models.find(model => model.model_id === entry.id.toLowerCase()) : undefined;
49
+ return rule?.policy_source === 'published' && rule.pricing_status === 'available' ? billingUsageHelp(rule, entry) : [];
50
+ }
40
51
  function priceLine(price) {
41
52
  const minimum = price.min_charge_usd !== undefined ? ` (minimum $${formatUsd(price.min_charge_usd)} per task)` : '';
42
53
  const factors = price.multipliers ? ` (resolution factors ${Object.entries(price.multipliers).map(([k, v]) => `${k} ×${v}`).join(', ')})` : '';
@@ -142,6 +153,11 @@ export function registerGetModel(server, config) {
142
153
  else {
143
154
  lines.push(catalog.pricingWarning ?? 'Pricing data is unavailable in this catalog.');
144
155
  }
156
+ const usage = billingUsage(entry);
157
+ if (usage.length) {
158
+ lines.push('Billing usage (estimate_cost needs these for a total and names any that are missing):', ...usage.map(line => `- ${line}`));
159
+ structured.billing_usage = usage;
160
+ }
145
161
  if (catalog.pricingWarning)
146
162
  structured.pricing_warning = catalog.pricingWarning;
147
163
  return ok(lines.join('\n'), structured);
@@ -3,16 +3,24 @@
3
3
  import { currentRequestCredentials } from '../request-context.js';
4
4
  import { RequestTimeoutError } from '../services/http-policy.js';
5
5
  import { getPricingRules, PricingRulesError, PricingRulesQuery } from '../services/pricing-rules-client.js';
6
- import { failure, ok, READ_ONLY } from './shared.js';
7
- export function registerPricingRules(server) {
6
+ import { pricingCallLimitReached } from '../services/pricing-call-limit.js';
7
+ import { failure, ok, READ_ONLY, retryText } from './shared.js';
8
+ export function registerPricingRules(server, config) {
8
9
  server.registerTool('get_pricing_rules', {
9
10
  title: 'Read public pricing rules',
10
11
  description: 'Read schema-2 public default pricing rules, decimal-string rates including fractional UC, minimum charges, tiers and optional full expressions. Free and anonymous upstream. The returned price_selection, when present, identifies route-priority prices or legacy minimum configuration prices. Coverage follows the returned published policies and supported legacy text adapters, including media when available. These are public reference rates, not account prices, live availability, a task quote, a bill or a final spending cap. Do not substitute these rules for media estimate_cost or assume empty media results are free.',
11
12
  inputSchema: PricingRulesQuery.shape,
12
13
  annotations: { title: 'Read public pricing rules', ...READ_ONLY },
13
14
  }, async (input) => {
15
+ const over = pricingCallLimitReached('get_pricing_rules');
16
+ if (over)
17
+ return failure(`This account already made ${over.limit} get_pricing_rules calls in the last minute, the most allowed. Wait ${retryText(over.retryAfterSeconds)}, then try again. No quote or spending limit was established.`, {
18
+ error: { category: 'rate_limited', code: 'pricing_calls_per_minute', retryable: true, retry_after: over.retryAfterSeconds },
19
+ charged: 'no', quote_established: false, final_budget_enforced: false
20
+ });
14
21
  try {
15
- const { body, source } = await getPricingRules(input);
22
+ // Hosted: rules stay valid until their own fresh_until, and a burst of lookups must not spend the shared per-IP limit.
23
+ const { body, source } = await getPricingRules(input, config.reusePricingRules ? { reuseUntilFresh: true } : {});
16
24
  const models = 'model' in body ? [body.model] : body.models;
17
25
  const selection = body.meta.price_selection ?? 'configured_minimum';
18
26
  const warnings = [
@@ -46,7 +54,8 @@ export function registerPricingRules(server) {
46
54
  return failure(safeError.status === 404
47
55
  ? 'No public pricing rules are published for this model and filters. This does not mean the model is free or unavailable.'
48
56
  : safeError.code === 'interrupted' ? 'Public pricing rules lookup was interrupted. No quote or spending limit was established.'
49
- : safeError.message, { error: { category: safeError.code === 'interrupted' ? 'interrupted'
57
+ : safeError.code === 'rate_limit_exceeded' ? `The platform is limiting pricing requests right now. Try again in ${retryText(safeError.retryAfter)}. No quote or spending limit was established.`
58
+ : safeError.message, { error: { category: safeError.code === 'interrupted' ? 'interrupted'
50
59
  : safeError.status === 404 ? 'not_found' : safeError.status === 429 ? 'rate_limit' : 'server_error',
51
60
  code: safeError.code, status: safeError.status,
52
61
  retryable: safeError.status === 429 || safeError.status >= 500
@@ -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
  }
@@ -7,9 +7,12 @@ import { trackedLink } from '../services/utm.js';
7
7
  import { MODEL_SELECTION_GUIDANCE, modelPreference } from '../services/model-recommendations.js';
8
8
  import { referenceInputs } from '../services/model-capabilities.js';
9
9
  import { READ_ONLY, errorResult, ok } from './shared.js';
10
+ // Assistant-facing text is English by default; a catalog name in Chinese, Japanese or Korean is left out and the ID shown.
11
+ const CJK = /[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af\uff00-\uffef]/;
12
+ const english = (text) => text && !CJK.test(text) ? text : undefined;
10
13
  export function modelTitle(entry) {
11
14
  const title = entry.spec?.title?.replace(/\s+(interface|api)$/i, '').trim();
12
- return title || entry.title || entry.priced?.description?.slice(0, 120) || undefined;
15
+ return title || english(entry.title) || english(entry.priced?.description?.slice(0, 120)) || undefined;
13
16
  }
14
17
  /** Every term must appear somewhere; matches in the model ID count most. */
15
18
  export function scoreModel(entry, terms) {
@@ -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);
@@ -161,6 +171,10 @@ export function progressReporter(extra, totalSeconds) {
161
171
  }).catch(() => undefined);
162
172
  };
163
173
  }
174
+ /** "N seconds" from a Retry-After, or about a minute (the platform's limit window) when it gave none. */
175
+ export function retryText(seconds) {
176
+ return seconds === undefined ? 'about a minute' : `${seconds} second${seconds === 1 ? '' : 's'}`;
177
+ }
164
178
  export function sleep(ms, signal) {
165
179
  return new Promise(resolve => {
166
180
  if (signal?.aborted) {
@@ -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.11.0';