@evolinkai/cli 0.10.3 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -4
- package/package.json +1 -1
- package/skills/evolink-cli/SKILL.md +14 -4
- package/skills/evolink-cli/references/usage-and-budget.md +19 -2
- package/src/api.mjs +8 -6
- package/src/auth.mjs +14 -3
- package/src/cli.mjs +23 -7
- package/src/help.mjs +1 -1
- package/src/media.mjs +161 -19
- package/src/platform/core/src/data/model-constraints.js +27 -0
- package/src/platform/core/src/data/model-params.js +8 -1
- package/src/platform/core/src/data/model-params.overrides.generated.js +4 -0
- package/src/platform/core/src/services/api-client.js +64 -28
- package/src/platform/core/src/services/http-policy.js +41 -12
- package/src/platform/core/src/services/pricing-quote-client.js +16 -2
- package/src/platform/core/src/services/pricing-rules-estimate.js +31 -2
- package/src/platform/core/src/services/public-error.js +1 -1
- package/src/platform/core/src/services/search-usage.js +22 -0
- package/src/platform/core/src/services/seedance-input.js +75 -0
- package/src/platform/core/src/services/task-response.js +176 -0
- package/src/platform/core/src/tool-guidance.js +3 -1
- package/src/platform/core/src/tools/estimate-cost.js +12 -2
- package/src/platform/core/src/tools/generate.js +33 -11
- package/src/platform/core/src/tools/get-model.js +8 -3
- package/src/platform/core/src/tools/get-task.js +40 -15
- package/src/platform/core/src/tools/list-tasks.js +108 -31
- package/src/platform/core/src/tools/shared.js +32 -2
- package/src/platform/core/src/tools/task-format.js +85 -18
- package/src/platform/core/src/version.js +1 -1
- package/src/platform/source.json +45 -37
|
@@ -8,12 +8,13 @@ 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';
|
|
15
15
|
import { PAID_GENERATION_GUIDANCE } from '../tool-guidance.js';
|
|
16
16
|
import { currentRequestCredentials } from '../request-context.js';
|
|
17
|
+
import { prepareSeedanceInput } from '../services/seedance-input.js';
|
|
17
18
|
const PATHS = {
|
|
18
19
|
image: '/v1/images/generations',
|
|
19
20
|
video: '/v1/videos/generations',
|
|
@@ -104,6 +105,7 @@ function registerGenerate(server, config, kind) {
|
|
|
104
105
|
annotations: { title, ...PAID },
|
|
105
106
|
}, async (args, extra) => {
|
|
106
107
|
const started = Date.now();
|
|
108
|
+
const startedMono = monotonicNow();
|
|
107
109
|
const credentials = currentRequestCredentials();
|
|
108
110
|
const unavailable = !credentials?.serviceChannel && !credentials?.apiKey ? credentials?.unavailableReason : undefined;
|
|
109
111
|
if (unavailable)
|
|
@@ -141,9 +143,13 @@ function registerGenerate(server, config, kind) {
|
|
|
141
143
|
charged: 'no',
|
|
142
144
|
});
|
|
143
145
|
}
|
|
146
|
+
const prepared = prepareSeedanceInput(entry, input);
|
|
147
|
+
const effectiveInput = prepared.input;
|
|
144
148
|
const warnings = [];
|
|
145
149
|
if (entry.spec) {
|
|
146
|
-
const validation = validateInput(entry.spec,
|
|
150
|
+
const validation = validateInput(entry.spec, effectiveInput);
|
|
151
|
+
validation.errors.push(...prepared.errors);
|
|
152
|
+
validation.warnings.push(...prepared.warnings);
|
|
147
153
|
if (validation.errors.length > 0) {
|
|
148
154
|
return failure([
|
|
149
155
|
`The input for ${entry.id} has problems; nothing was submitted or charged:`,
|
|
@@ -159,7 +165,7 @@ function registerGenerate(server, config, kind) {
|
|
|
159
165
|
// media_seconds only prices the request; the body below is built from input alone.
|
|
160
166
|
if (args.account_quote)
|
|
161
167
|
throw new QuoteError('quote_refresh_required', 'Refresh the legacy account estimate with estimate_cost and obtain user approval.');
|
|
162
|
-
const rulesEstimate = await createRulesEstimate(entry,
|
|
168
|
+
const rulesEstimate = await createRulesEstimate(entry, effectiveInput, { mediaSeconds: args.media_seconds, pricingParameters: args.pricing_parameters });
|
|
163
169
|
if (args.pricing_quote)
|
|
164
170
|
checkRulesApproval(args.pricing_quote, rulesEstimate);
|
|
165
171
|
const estimate = rulesEstimate.estimate;
|
|
@@ -183,7 +189,7 @@ function registerGenerate(server, config, kind) {
|
|
|
183
189
|
if (estimate.status === 'needs_input')
|
|
184
190
|
throw new QuoteError('quote_usage_required', 'No charge can be estimated yet; supply the missing pricing usage before submission.');
|
|
185
191
|
clientRequestId = args.client_request_id ?? newRunId();
|
|
186
|
-
const body = { ...
|
|
192
|
+
const body = { ...effectiveInput, model: entry.id };
|
|
187
193
|
const submitted = await submitTask(config, {
|
|
188
194
|
path: entry.spec?.path ?? PATHS[kind],
|
|
189
195
|
body,
|
|
@@ -192,24 +198,29 @@ function registerGenerate(server, config, kind) {
|
|
|
192
198
|
});
|
|
193
199
|
acceptedTaskId = submitted.id;
|
|
194
200
|
let task = submitted;
|
|
195
|
-
|
|
196
|
-
|
|
201
|
+
let statusCheck = 'not_requested';
|
|
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) {
|
|
197
205
|
const report = progressReporter(extra, WAIT_MS[kind] / 1000);
|
|
198
206
|
try {
|
|
199
|
-
|
|
207
|
+
const waited = await waitForTask(config, submitted.id, {
|
|
200
208
|
deadline: waitUntil,
|
|
201
209
|
tool: name,
|
|
202
210
|
signal: extra.signal,
|
|
203
|
-
onPoll: current => report((Date.now() - started) / 1000, `${current.status}
|
|
211
|
+
onPoll: current => report((Date.now() - started) / 1000, `${current.status}${current.progress !== undefined ? `, ${current.progress}%` : ''}`),
|
|
204
212
|
});
|
|
213
|
+
task = waited.task;
|
|
214
|
+
statusCheck = waited.statusCheck;
|
|
205
215
|
}
|
|
206
216
|
catch {
|
|
207
217
|
// The task exists; a failed status read must not turn a successful submit into an error.
|
|
208
218
|
task = submitted;
|
|
219
|
+
statusCheck = 'unverified';
|
|
209
220
|
}
|
|
210
221
|
task.usage = { ...submitted.usage, ...task.usage };
|
|
211
222
|
}
|
|
212
|
-
const view = describeTask({ ...task, request_id: task.request_id ?? submitted.request_id });
|
|
223
|
+
const view = describeTask({ ...task, request_id: task.request_id ?? submitted.request_id }, statusCheck);
|
|
213
224
|
const header = submitted.idempotency_replayed
|
|
214
225
|
? `This client_request_id was used before: returning the original task (no new charge).`
|
|
215
226
|
: `Submitted ${entry.id}.`;
|
|
@@ -220,6 +231,12 @@ function registerGenerate(server, config, kind) {
|
|
|
220
231
|
}
|
|
221
232
|
if (estimate.status === 'estimated')
|
|
222
233
|
lines.push(`Estimate before submitting: ${rangeText(estimate)}`);
|
|
234
|
+
if (estimate.search_charges?.length && estimate.status === 'estimated') {
|
|
235
|
+
for (const note of estimate.notes.filter(note => /^(Web|Image) search is enabled\./.test(note)))
|
|
236
|
+
lines.push(`Note: ${note}`);
|
|
237
|
+
}
|
|
238
|
+
for (const applied of prepared.defaults)
|
|
239
|
+
lines.push(`Applied default: ${applied.param}=${applied.value} (${applied.reason}).`);
|
|
223
240
|
if (estimate.status === 'partial') {
|
|
224
241
|
lines.push(`Partial estimate at published rates: ${rangeText(estimate)} (not a total or an upper bound).`);
|
|
225
242
|
for (const extra of estimate.possible_extras)
|
|
@@ -232,15 +249,20 @@ function registerGenerate(server, config, kind) {
|
|
|
232
249
|
lines.push(`client_request_id: ${clientRequestId}`);
|
|
233
250
|
return ok(lines.join('\n'), {
|
|
234
251
|
...view.structured,
|
|
235
|
-
submitted: { model: entry.id, input },
|
|
252
|
+
submitted: { model: entry.id, input: effectiveInput },
|
|
253
|
+
...(prepared.applies ? { effective_input: effectiveInput, defaults_applied: prepared.defaults,
|
|
254
|
+
usage_assumptions: estimate.notes.filter(note => note.startsWith('Web search is enabled.')) } : {}),
|
|
236
255
|
pricing_scope: 'public_default',
|
|
237
256
|
pricing_source: 'pricing_rules',
|
|
238
257
|
amounts: rulesEstimate.amounts,
|
|
239
258
|
final_budget_enforced: false,
|
|
259
|
+
...(estimate.search_charges?.length ? { search_charges: estimate.search_charges, estimate,
|
|
260
|
+
amount_scope: estimate.status === 'partial' ? 'known_components_subtotal' : 'expected_usage_estimate' } : {}),
|
|
240
261
|
client_request_id: clientRequestId,
|
|
262
|
+
submission_state: 'accepted',
|
|
241
263
|
replayed: submitted.idempotency_replayed === true,
|
|
242
264
|
...(typeof reserved === 'number' ? { reserved_credits: reserved, reserved_usd: usdOf(reserved) } : {}),
|
|
243
|
-
...(estimate.status === 'estimated' ? { estimate: { min_usd: estimate.min_usd, max_usd: estimate.max_usd } } : {}),
|
|
265
|
+
...(estimate.status === 'estimated' && !estimate.search_charges?.length ? { estimate: { min_usd: estimate.min_usd, max_usd: estimate.max_usd } } : {}),
|
|
244
266
|
...(estimate.status === 'partial' ? { estimate } : {}),
|
|
245
267
|
...(warnings.length ? { warnings } : {}),
|
|
246
268
|
}, view.resources);
|
|
@@ -9,6 +9,7 @@ import { trackedLink } from '../services/utm.js';
|
|
|
9
9
|
import { READ_ONLY, errorResult, failure, ok } from './shared.js';
|
|
10
10
|
import { modelTitle } from './search-models.js';
|
|
11
11
|
import { referenceInputs } from '../services/model-capabilities.js';
|
|
12
|
+
import { seedanceInputRules } from '../services/seedance-input.js';
|
|
12
13
|
function value(v) {
|
|
13
14
|
return JSON.stringify(v);
|
|
14
15
|
}
|
|
@@ -60,6 +61,7 @@ export function registerGetModel(server, config) {
|
|
|
60
61
|
return failure(`Unknown model "${model}".${suggestions.length ? ` Did you mean: ${suggestions.join(', ')}?` : ''} Use search_models to find model IDs.`, { error: { category: 'not_found', param: 'model' }, suggestions });
|
|
61
62
|
}
|
|
62
63
|
const { spec, priced } = entry;
|
|
64
|
+
const modelRules = seedanceInputRules(entry);
|
|
63
65
|
const title = modelTitle(entry);
|
|
64
66
|
const lines = [`${entry.id} (${entry.kind})${title ? ` — ${title}` : ''}`, `Generate with: generate_${entry.kind}`];
|
|
65
67
|
const structured = {
|
|
@@ -89,8 +91,9 @@ export function registerGetModel(server, config) {
|
|
|
89
91
|
parameters: spec.params,
|
|
90
92
|
constraints: spec.constraints,
|
|
91
93
|
example_input: spec.example,
|
|
92
|
-
parameters_source: modelParamsMeta(),
|
|
93
|
-
input_schema: spec.inputSchema?.schema,
|
|
94
|
+
parameters_source: modelParamsMeta(entry.id),
|
|
95
|
+
input_schema: modelRules && spec.inputSchema ? { ...spec.inputSchema.schema, 'x-evolink-model-rules': modelRules } : spec.inputSchema?.schema,
|
|
96
|
+
...(modelRules ? { model_input_rules: modelRules } : {}),
|
|
94
97
|
response_schema: spec.responseSchema?.schema,
|
|
95
98
|
schema_info: {
|
|
96
99
|
dialect: spec.inputSchema?.dialect,
|
|
@@ -99,13 +102,15 @@ export function registerGetModel(server, config) {
|
|
|
99
102
|
response_scope: 'generation_submission_response_not_final_task_result',
|
|
100
103
|
omitted_fields: { input: ['model', 'callback_url'], response: ['task_info.can_cancel'] },
|
|
101
104
|
additional_runtime_constraints: spec.constraints,
|
|
102
|
-
source: modelParamsMeta(),
|
|
105
|
+
source: modelParamsMeta(entry.id),
|
|
103
106
|
validation_scope: 'documented_schema_plus_runtime_constraints',
|
|
104
107
|
runtime_constraints_source: 'reviewed_gateway_supplements',
|
|
105
108
|
},
|
|
106
109
|
reference_inputs: referenceInputs(spec),
|
|
107
110
|
});
|
|
108
111
|
lines.push('Schemas are versioned official OpenAPI references. response_schema describes submission, not necessarily the final task output. Apply the additional runtime constraints above.');
|
|
112
|
+
if (modelRules)
|
|
113
|
+
lines.push('Model-specific rules: draft=true uses quality=480p when omitted and rejects another quality. These rules apply only to this resolved model and generation endpoint.', ...(modelRules.search_usage ? [modelRules.search_usage] : []), ...(modelRules.duration_usage ? [modelRules.duration_usage] : []));
|
|
109
114
|
}
|
|
110
115
|
else {
|
|
111
116
|
lines.push('', 'Parameters for this model are not documented here; the gateway checks the input when you submit.');
|
|
@@ -1,57 +1,82 @@
|
|
|
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 {
|
|
5
|
-
import {
|
|
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.',
|
|
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.',
|
|
18
32
|
'Never call generate_image, generate_video or generate_audio again to check progress: that creates and charges a new task.',
|
|
19
33
|
RESULT_DELIVERY_GUIDANCE,
|
|
20
34
|
].join(' '),
|
|
21
35
|
inputSchema: {
|
|
22
36
|
task_id: z.string().regex(TASK_ID).describe('task_id returned by generate_image, generate_video or generate_audio'),
|
|
23
37
|
wait_seconds: z.number().int().min(0).max(MAX_WAIT_SECONDS).default(30)
|
|
24
|
-
.describe('How long this call may wait for the task to finish (0–45 s, default 30). Use 0 for
|
|
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).'),
|
|
25
39
|
},
|
|
26
40
|
annotations: { title: 'Get task status and results', ...READ_ONLY },
|
|
27
41
|
}, async ({ task_id, wait_seconds }, extra) => {
|
|
28
|
-
const started =
|
|
42
|
+
const started = monotonicNow();
|
|
29
43
|
const waitSeconds = Math.min(wait_seconds ?? 30, MAX_WAIT_SECONDS);
|
|
30
44
|
const report = progressReporter(extra, waitSeconds);
|
|
31
45
|
let lastReport = -PROGRESS_EVERY_SECONDS;
|
|
32
46
|
try {
|
|
33
|
-
const
|
|
34
|
-
|
|
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,
|
|
35
52
|
tool: 'get_task',
|
|
36
53
|
signal: extra.signal,
|
|
37
54
|
onPoll: async (current) => {
|
|
38
|
-
const elapsed = (
|
|
55
|
+
const elapsed = (monotonicNow() - started) / 1000;
|
|
39
56
|
if (elapsed - lastReport < PROGRESS_EVERY_SECONDS)
|
|
40
57
|
return;
|
|
41
58
|
lastReport = elapsed;
|
|
42
|
-
await report(elapsed, `${current.status}
|
|
59
|
+
await report(elapsed, `${current.status}${current.progress !== undefined ? `, ${current.progress}%` : ''}`);
|
|
43
60
|
},
|
|
44
61
|
});
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
view.
|
|
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 } : {}) });
|
|
50
75
|
}
|
|
51
76
|
return ok(view.lines.join('\n'), view.structured, view.resources);
|
|
52
77
|
}
|
|
53
78
|
catch (error) {
|
|
54
|
-
return errorResult(error);
|
|
79
|
+
return errorResult(error, { phase: 'query', taskId: task_id });
|
|
55
80
|
}
|
|
56
81
|
});
|
|
57
82
|
}
|
|
@@ -3,10 +3,18 @@
|
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { listTasks, queryTasks } from '../services/api-client.js';
|
|
5
5
|
import { publicTaskErrorCode } from '../services/error-handler.js';
|
|
6
|
-
import {
|
|
6
|
+
import { parseBatchTasks } from '../services/task-response.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';
|
|
7
9
|
import { TASK_ID } from './get-task.js';
|
|
8
10
|
import { RESULT_DELIVERY_GUIDANCE, RESULT_DELIVERY_INSTRUCTIONS, RESULT_LINK_HOURS, resultDeliveryMarkdown, resultLinks, resultResources, taskOutputs } from './task-format.js';
|
|
9
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
|
+
}
|
|
10
18
|
/** ISO 8601, unix seconds, or relative such as 30m, 2h, 1d. */
|
|
11
19
|
export function parseSince(value, now = Date.now()) {
|
|
12
20
|
const trimmed = value.trim();
|
|
@@ -25,7 +33,9 @@ export function parseSince(value, now = Date.now()) {
|
|
|
25
33
|
}
|
|
26
34
|
function rowFromTask(task) {
|
|
27
35
|
const row = { task_id: task.id, status: task.status, model: task.model, type: task.type, progress: task.progress };
|
|
28
|
-
if (task.
|
|
36
|
+
if (task.response_warnings?.length)
|
|
37
|
+
row.response_warnings = task.response_warnings;
|
|
38
|
+
if (task.created !== undefined)
|
|
29
39
|
row.created_at = new Date(task.created * 1000).toISOString();
|
|
30
40
|
const links = resultLinks(task);
|
|
31
41
|
if (links.length > 0)
|
|
@@ -46,7 +56,9 @@ function rowFromTask(task) {
|
|
|
46
56
|
return row;
|
|
47
57
|
}
|
|
48
58
|
function rowLine(row) {
|
|
49
|
-
const parts = [`- ${row.task_id}`, row.status
|
|
59
|
+
const parts = [`- ${row.task_id}`, `${row.status}${!['completed', 'failed'].includes(row.status) && row.progress !== undefined ? ` ${row.progress}%` : ''}`];
|
|
60
|
+
if (row.model)
|
|
61
|
+
parts.push(row.model);
|
|
50
62
|
if (row.created_at)
|
|
51
63
|
parts.push(row.created_at);
|
|
52
64
|
if (row.charged_credits !== undefined)
|
|
@@ -66,6 +78,8 @@ export function registerListTasks(server, config) {
|
|
|
66
78
|
'since and until filter only the selected page by creation time. total is the server count before these time filters; an empty page does not prove a submission was absent.',
|
|
67
79
|
'Use it to recover tasks after a lost connection or a timed-out submit before submitting anything again.',
|
|
68
80
|
'Recent tasks cover the whole EvoLink account, newest first.',
|
|
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.',
|
|
69
83
|
RESULT_DELIVERY_GUIDANCE,
|
|
70
84
|
].join(' '),
|
|
71
85
|
inputSchema: {
|
|
@@ -84,7 +98,7 @@ export function registerListTasks(server, config) {
|
|
|
84
98
|
.describe('Without task_ids: how many recent tasks to return (1–50, default 20).'),
|
|
85
99
|
},
|
|
86
100
|
annotations: { title: 'List generation tasks', ...READ_ONLY },
|
|
87
|
-
}, async ({ task_ids, status, type, model, page: pageNumber, since, until, limit }) => {
|
|
101
|
+
}, async ({ task_ids, status, type, model, page: pageNumber, since, until, limit }, extra) => {
|
|
88
102
|
try {
|
|
89
103
|
if (task_ids && [status, type, model, pageNumber, since, until].some(value => value !== undefined)) {
|
|
90
104
|
return failure('Choose task_ids or list filters, not both.', { error: { category: 'invalid_request' } });
|
|
@@ -92,17 +106,25 @@ export function registerListTasks(server, config) {
|
|
|
92
106
|
if (task_ids && task_ids.length > 0) {
|
|
93
107
|
const unique = [...new Set(task_ids)];
|
|
94
108
|
const tasks = await queryTasks(config, unique);
|
|
95
|
-
const rows = tasks.map(rowFromTask);
|
|
96
|
-
const
|
|
97
|
-
const missing = unique.filter(id => !found.has(id));
|
|
109
|
+
const rows = tasks.tasks.map(rowFromTask);
|
|
110
|
+
const missing = tasks.missing;
|
|
98
111
|
const lines = [`${rows.length} of ${unique.length} tasks found.`, ...rows.map(rowLine)];
|
|
99
112
|
if (missing.length > 0)
|
|
100
|
-
lines.push(`Not
|
|
113
|
+
lines.push(`Not verified or absent from this response: ${missing.join(', ')}. This does not prove the tasks were never submitted. Query these original IDs again; do not generate again.`);
|
|
114
|
+
if (tasks.issues.length)
|
|
115
|
+
lines.push('Some task responses were invalid or conflicting and were omitted. Verified tasks are retained.');
|
|
116
|
+
if (rows.some(row => row.response_warnings))
|
|
117
|
+
lines.push('Some optional fields were omitted; missing values do not mean zero. See response_warnings.');
|
|
118
|
+
const websiteCheck = missing.length > 0 || tasks.issues.length > 0 || rows.some(row => row.response_warnings || ['failed', 'cancelled'].includes(row.status));
|
|
119
|
+
if (websiteCheck)
|
|
120
|
+
lines.push(DASHBOARD_CHECK_GUIDANCE);
|
|
101
121
|
if (rows.some(row => row.results))
|
|
102
122
|
lines.push(`Result links expire after ${RESULT_LINK_HOURS} hours.`);
|
|
103
123
|
if (rows.some(row => row.results))
|
|
104
124
|
lines.push(`Next step: ${RESULT_DELIVERY_INSTRUCTIONS}`);
|
|
105
|
-
return ok(lines.join('\n'), { tasks: rows, missing
|
|
125
|
+
return ok(lines.join('\n'), { tasks: rows, missing, partial: missing.length > 0 || tasks.issues.length > 0, issues: tasks.issues,
|
|
126
|
+
...(websiteCheck ? dashboardCheck() : {}),
|
|
127
|
+
}, rows.flatMap(row => resultResources(row.task_id, row.results ?? [])));
|
|
106
128
|
}
|
|
107
129
|
const now = Date.now();
|
|
108
130
|
let sinceMs;
|
|
@@ -120,52 +142,107 @@ export function registerListTasks(server, config) {
|
|
|
120
142
|
}
|
|
121
143
|
const pageSize = limit ?? 20;
|
|
122
144
|
const page = await listTasks(config, { status, type, model, page: pageNumber, pageSize });
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
145
|
+
// Compact rows have the same identity/state boundary, but do not need detail-only fields.
|
|
146
|
+
const compact = parseBatchTasks({ data: page.data.map(item => item && typeof item === 'object'
|
|
147
|
+
? { ...item, created: item.created_at, usage: { credits_used: item.credits_used } } : item) }, page.data.flatMap(item => item && typeof item.id === 'string' ? [item.id] : []));
|
|
148
|
+
let items = compact.tasks;
|
|
149
|
+
const issues = [...compact.issues];
|
|
150
|
+
if (sinceMs !== undefined || untilMs !== undefined) {
|
|
151
|
+
items = items.filter(item => {
|
|
152
|
+
if (item.created === undefined) {
|
|
153
|
+
issues.push({ task_id: item.id, code: 'task_creation_time_unverified' });
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
return (sinceMs === undefined || item.created * 1000 >= sinceMs) && (untilMs === undefined || item.created * 1000 <= untilMs);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
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.
|
|
161
|
+
const finished = items.filter(item => item.status === 'completed' && page.data.some(raw => raw?.id === item.id && raw.has_results === true) || item.status === 'failed')
|
|
130
162
|
.map(item => item.id).slice(0, MAX_IDS);
|
|
131
163
|
const details = new Map();
|
|
164
|
+
const reasons = new Map();
|
|
165
|
+
let detailsError;
|
|
132
166
|
if (finished.length > 0) {
|
|
133
|
-
|
|
134
|
-
|
|
167
|
+
try {
|
|
168
|
+
const batch = await queryTasks(config, finished, 'list_tasks', { deadline: monotonicNow() + detailsBudgetMs, signal: extra?.signal });
|
|
169
|
+
for (const task of batch.tasks)
|
|
170
|
+
details.set(task.id, task);
|
|
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');
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
issues.push({ code: 'task_details_unavailable' });
|
|
178
|
+
detailsError = errorSummary(error);
|
|
179
|
+
for (const id of finished)
|
|
180
|
+
reasons.set(id, 'read_failed');
|
|
181
|
+
}
|
|
135
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');
|
|
136
188
|
const rows = items.map(item => {
|
|
137
189
|
const detailed = details.get(item.id);
|
|
138
190
|
if (detailed)
|
|
139
191
|
return rowFromTask(detailed);
|
|
140
|
-
const row =
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
};
|
|
148
|
-
if (typeof item.credits_used === 'number' && item.status === 'completed') {
|
|
149
|
-
row.charged_credits = item.credits_used;
|
|
150
|
-
row.charged_usd = usdOf(item.credits_used);
|
|
192
|
+
const row = rowFromTask(item);
|
|
193
|
+
// Compact pages do not establish a detailed execution error code.
|
|
194
|
+
delete row.error_code;
|
|
195
|
+
const reason = reasons.get(item.id);
|
|
196
|
+
if (reason) {
|
|
197
|
+
row.details_available = false;
|
|
198
|
+
row.details_reason = reason;
|
|
151
199
|
}
|
|
152
200
|
return row;
|
|
153
201
|
});
|
|
154
202
|
const filters = [status && `status ${status}`, type && `type ${type}`, model && `model ${model}`, since && `since ${since}`, until && `until ${until}`].filter(Boolean).join(', ');
|
|
155
203
|
const lines = [`${rows.length} recent task${rows.length === 1 ? '' : 's'} on this account${filters ? ` (${filters})` : ''}, newest first:`];
|
|
156
204
|
lines.push(...(rows.length > 0 ? rows.map(rowLine) : ['(none)']));
|
|
205
|
+
if (issues.length || detailsMissing.length)
|
|
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
|
+
}
|
|
216
|
+
if (rows.some(row => row.response_warnings))
|
|
217
|
+
lines.push('Some optional fields were omitted; missing values do not mean zero. See response_warnings.');
|
|
218
|
+
const websiteCheck = issues.length > 0 || detailsMissing.length > 0 || rows.some(row => row.response_warnings || ['failed', 'cancelled'].includes(row.status));
|
|
219
|
+
if (websiteCheck)
|
|
220
|
+
lines.push(DASHBOARD_CHECK_GUIDANCE);
|
|
157
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}.`);
|
|
158
226
|
lines.push(`Page ${page.page}; ${page.total} tasks before page-local time filtering.${nextPage ? ` Continue with page ${nextPage}.` : ''}`);
|
|
159
227
|
if (rows.some(row => row.results))
|
|
160
228
|
lines.push(`Result links expire after ${RESULT_LINK_HOURS} hours.`);
|
|
161
229
|
if (rows.some(row => row.results))
|
|
162
230
|
lines.push(`Next step: ${RESULT_DELIVERY_INSTRUCTIONS}`);
|
|
163
231
|
return ok(lines.join('\n'), { tasks: rows, total: page.total, page: page.page, page_size: page.page_size,
|
|
164
|
-
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',
|
|
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 } : {}),
|
|
236
|
+
...(websiteCheck ? dashboardCheck() : {}),
|
|
165
237
|
}, rows.flatMap(row => resultResources(row.task_id, row.results ?? [])));
|
|
166
238
|
}
|
|
167
239
|
catch (error) {
|
|
168
|
-
|
|
240
|
+
const result = errorResult(error, { phase: 'query' });
|
|
241
|
+
if (task_ids) {
|
|
242
|
+
result.structuredContent = { ...result.structuredContent, requested_task_ids: [...new Set(task_ids)],
|
|
243
|
+
phase: 'query', status_check: 'unverified' };
|
|
244
|
+
}
|
|
245
|
+
return result;
|
|
169
246
|
}
|
|
170
247
|
});
|
|
171
248
|
}
|
|
@@ -5,14 +5,19 @@ 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, 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
|
+
import { TaskResponseError } from '../services/task-response.js';
|
|
10
11
|
/** Free lookups: clients can run them without asking. */
|
|
11
12
|
export const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
12
13
|
/** Spends the user's balance and cannot be undone: clients ask before running it. */
|
|
13
14
|
export const PAID = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false };
|
|
14
15
|
/** Changes stored state without spending money (uploads). */
|
|
15
16
|
export const WRITES = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
|
|
17
|
+
export const DASHBOARD_CHECK_GUIDANCE = `Check your task and account records in the EvoLink Dashboard: ${DASHBOARD_URL}. Sign in with the same EvoLink account and keep the original task ID. This link does not confirm completion, charges or refunds.`;
|
|
18
|
+
export function dashboardCheck() {
|
|
19
|
+
return { dashboard_url: DASHBOARD_URL, dashboard_guidance: DASHBOARD_CHECK_GUIDANCE };
|
|
20
|
+
}
|
|
16
21
|
/** The media_seconds argument of estimate_cost and the generate tools. */
|
|
17
22
|
export const MEDIA_SECONDS_MAX = 3_600;
|
|
18
23
|
export const MEDIA_SECONDS_DESCRIPTION = 'Only for models billed per second that have no duration parameter (get_model explains which length is billed): usually the input video or audio length; for generated audio with unknown duration, only an expected output length for an illustrative estimate. It is not sent to the model, and EvoLink charges by the measured duration. It cannot establish max_cost_usd for unknown output duration or for per-second video requests with video_urls, video_url or source_task_id, whose billing is not fully covered by published prices.';
|
|
@@ -44,6 +49,12 @@ export function usdOf(credits) {
|
|
|
44
49
|
return Number((credits / CREDITS_PER_USD).toFixed(6));
|
|
45
50
|
}
|
|
46
51
|
function infoFor(error) {
|
|
52
|
+
if (error instanceof TaskResponseError)
|
|
53
|
+
return {
|
|
54
|
+
status: 0, category: 'server_error', code: error.code, message: error.message,
|
|
55
|
+
next_step: 'Retry the free query with the original task ID. Its status, charge and refund are unverified; do not generate again.',
|
|
56
|
+
retryable: true, request_id: error.requestId,
|
|
57
|
+
};
|
|
47
58
|
if (error instanceof SubmissionNotStartedError)
|
|
48
59
|
return infoFor(error.cause);
|
|
49
60
|
if (error instanceof ApiHttpError && error.info)
|
|
@@ -60,6 +71,11 @@ function infoFor(error) {
|
|
|
60
71
|
retryable: true,
|
|
61
72
|
};
|
|
62
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
|
+
};
|
|
63
79
|
if (error instanceof RequestTimeoutError || error instanceof TypeError) {
|
|
64
80
|
return { status: 0, category: 'server_error', message: 'EvoLink did not respond in time.', next_step: 'Retry in a minute.', retryable: true };
|
|
65
81
|
}
|
|
@@ -81,12 +97,20 @@ function infoFor(error) {
|
|
|
81
97
|
retryable: false,
|
|
82
98
|
};
|
|
83
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
|
+
}
|
|
84
105
|
/** Converts a thrown error into a tool error with a category and a concrete next step. */
|
|
85
106
|
export function errorResult(error, context = {}) {
|
|
86
107
|
const info = infoFor(error);
|
|
87
108
|
const requestId = publicIdentifier(info.request_id);
|
|
88
109
|
const clientRequestId = publicIdentifier(context.clientRequestId);
|
|
89
|
-
const taskId = publicIdentifier(context.taskId);
|
|
110
|
+
const taskId = publicIdentifier(context.taskId ?? (error instanceof TaskResponseError ? error.taskId : undefined));
|
|
111
|
+
const queryUnverified = context.phase === 'query' || error instanceof TaskResponseError;
|
|
112
|
+
if (queryUnverified && taskId)
|
|
113
|
+
info.next_step = `Query the original task ${taskId} again. This read could not verify its latest status, charge or refund. Do not generate again to recover it.`;
|
|
90
114
|
const label = `${info.category}${info.code ? `, ${info.code}` : ''}${info.status ? `, HTTP ${info.status}` : ''}`;
|
|
91
115
|
const lines = info.headline ? [info.headline] : [`Error (${label}): ${info.message}`];
|
|
92
116
|
let charged;
|
|
@@ -110,6 +134,9 @@ export function errorResult(error, context = {}) {
|
|
|
110
134
|
lines.push(beforeSubmit ? 'Nothing was submitted or charged.' : 'Nothing was submitted or charged. Gateway admission rejected the generation before dispatch.');
|
|
111
135
|
}
|
|
112
136
|
lines.push(`Next step: ${info.next_step}`);
|
|
137
|
+
const websiteCheck = queryUnverified || charged === 'unknown';
|
|
138
|
+
if (websiteCheck)
|
|
139
|
+
lines.push(DASHBOARD_CHECK_GUIDANCE);
|
|
113
140
|
// No HTTP status: the request timed out or the connection dropped, so the upload's outcome is unknown.
|
|
114
141
|
if (context.upload && info.category === 'server_error' && !info.status) {
|
|
115
142
|
lines.push('The upload may not have finished. Calling upload_file again is safe.');
|
|
@@ -124,6 +151,9 @@ export function errorResult(error, context = {}) {
|
|
|
124
151
|
...(submissionState ? { submission_state: submissionState } : {}),
|
|
125
152
|
...(clientRequestId && context.paid ? { client_request_id: clientRequestId } : {}),
|
|
126
153
|
...(taskId ? { task_id: taskId } : {}),
|
|
154
|
+
...(websiteCheck ? dashboardCheck() : {}),
|
|
155
|
+
...(queryUnverified ? { phase: 'query', status_check: 'unverified',
|
|
156
|
+
...(error instanceof TaskResponseError && error.rawStatus ? { raw_status: error.rawStatus } : {}) } : {}),
|
|
127
157
|
});
|
|
128
158
|
}
|
|
129
159
|
/** Sends a progress notification when the client asked for them; failures are ignored. */
|