@evolinkai/cli 0.13.0 → 0.14.1

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 (29) hide show
  1. package/README.md +22 -7
  2. package/package.json +1 -1
  3. package/skills/evolink-cli/SKILL.md +21 -7
  4. package/skills/evolink-cli/references/capabilities.md +1 -1
  5. package/skills/evolink-cli/references/media-workflows.md +1 -1
  6. package/skills/evolink-cli/references/usage-and-budget.md +5 -3
  7. package/src/cli.mjs +76 -21
  8. package/src/help.mjs +12 -5
  9. package/src/media.mjs +185 -36
  10. package/src/platform/core/src/data/model-constraints.js +8 -5
  11. package/src/platform/core/src/data/model-params.overrides.generated.js +1 -1
  12. package/src/platform/core/src/services/api-client.js +1 -1
  13. package/src/platform/core/src/services/batch-generation.js +117 -0
  14. package/src/platform/core/src/services/gpt-image-tokens.js +264 -0
  15. package/src/platform/core/src/services/omni-tokens.js +258 -0
  16. package/src/platform/core/src/services/param-validator.js +48 -1
  17. package/src/platform/core/src/services/pricing-call-limit.js +4 -4
  18. package/src/platform/core/src/services/pricing-derived.js +3 -3
  19. package/src/platform/core/src/services/pricing-rules-client.js +23 -5
  20. package/src/platform/core/src/services/pricing-rules-estimate.js +320 -70
  21. package/src/platform/core/src/services/qwen-tts-tokens.js +187 -0
  22. package/src/platform/core/src/tool-guidance.js +25 -2
  23. package/src/platform/core/src/tools/estimate-cost.js +203 -61
  24. package/src/platform/core/src/tools/generate.js +498 -75
  25. package/src/platform/core/src/tools/get-model.js +15 -3
  26. package/src/platform/core/src/tools/get-pricing-rules.js +4 -3
  27. package/src/platform/core/src/tools/shared.js +1 -1
  28. package/src/platform/core/src/version.js +1 -1
  29. package/src/platform/source.json +43 -35
package/src/media.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { hash } from './state.mjs';
3
3
  import { CliError, requireThat, fileError } from './errors.mjs';
4
- import { APPROVAL_TTL_MS, rulesBudgetExceeded } from './platform/core/src/services/pricing-rules-estimate.js';
4
+ import { APPROVAL_TTL_MS, REFERENCE_BUDGET_FACTOR, priceRose, referenceBudgetExceeded, 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
7
  import { dashboardCheck } from './platform/core/src/tools/shared.js';
@@ -15,6 +15,69 @@ const MIN_ROUND_MS = 300;
15
15
  /** Drift ignored when the time left becomes whole seconds; the shared core still ends each round at the deadline. */
16
16
  const ROUND_DRIFT_MS = 50;
17
17
  const WAIT_STOPS_LOCAL = 'Stopping does not cancel the task.';
18
+ /**
19
+ * EvoLink keeps a request ID's outcome for 24 hours (agent idempotency); after that the same ID could start a second
20
+ * paid task. Recovery with the original ID stays an hour inside that window, counted from the first submission.
21
+ */
22
+ export const RECOVERY_WINDOW_MS = 23 * 60 * 60_000;
23
+ /** Saved states that tasks resume replays with the original request ID. */
24
+ const RECOVERABLE = ['submitting', 'outcome_unknown', 'partial'];
25
+
26
+ /** A quote for several inputs of one model (estimate --inputs-file), submitted in one call. */
27
+ const isBatch = quote => Array.isArray(quote.args?.inputs);
28
+
29
+ /**
30
+ * A quote holds until its expires_at, 24 hours after the estimate at most. Past it a first submission needs a new
31
+ * estimate and approval; recovery cannot replay it either, so the user checks what already went through first.
32
+ */
33
+ function expiredQuote(quote, id, resume) {
34
+ const at = new Date(quote.expires_at).toISOString(), batch = isBatch(quote), ids = quote.task_ids ?? [];
35
+ const list = 'evolink tasks list --since 2d', collect = ids.length ? `evolink tasks batch --ids ${ids.join(',')}` : undefined;
36
+ const message = !resume ? `This quote expired at ${at}. Refresh it with evolink estimate --refresh-quote ${id} and obtain the user's approval again. Nothing was submitted.`
37
+ : batch ? `This quote expired at ${at}, so its batch cannot be finished with it. Check ${collect ? `${collect} and ${list}` : list} first to see which inputs went through; then estimate only the inputs that did not and, after the user approves, submit them as a new batch. Nothing was submitted.`
38
+ : `This quote expired at ${at}, so its submission cannot be recovered with it. Check ${list} first to see whether it went through; only if it did not, estimate it again and, after the user approves, submit it as a new generation. Nothing was submitted.`;
39
+ return new CliError('quote_expired', message, { quote_id: id, client_request_id: quote.client_request_id, expired_at: at, submission_allowed: false,
40
+ ...(ids.length ? { task_ids: ids } : {}), next_step: resume ? collect ?? list : `evolink estimate --refresh-quote ${id}`, ...(resume ? dashboardCheck() : {}) });
41
+ }
42
+
43
+ /**
44
+ * Whether a fresh estimate still matches the approved quote: the same input at the approved price or lower. With the
45
+ * core's approval record that is its request hash and total, whatever else changed in the rules. Without one on both
46
+ * sides (an older service, or rules that cannot be read now), any change to the estimate needs a new approval.
47
+ */
48
+ export function approvalHolds(fresh, quote) {
49
+ const approved = quote.args?.pricing_quote, now = fresh.pricing_quote;
50
+ if (approved && now) {
51
+ return { input: approved.request_hash === now.request_hash && approved.model_id === now.model_id && approved.batch_items === now.batch_items,
52
+ rose: priceRose(approved, now) };
53
+ }
54
+ const account = quote.account_quote, current = fresh.account_quote;
55
+ if (account && current) return { input: account.request_hash === current.request_hash, rose: compareDecimal(current.quote.amount, account.quote.amount) > 0 };
56
+ return { input: true, rose: priceFingerprint(fresh) !== quote.fingerprint, byFingerprint: true };
57
+ }
58
+
59
+ /** The shared core's batch result names its own tool calls; for the CLI these lines name the CLI commands instead. */
60
+ export function cliBatchText(text, id, taskIds) {
61
+ return (text ?? '').split('\n').map(line => {
62
+ if (line.startsWith('Collect the results with list_tasks')) return `Collect the results with evolink tasks batch --ids ${taskIds.join(',')}; it is free and read-only.`;
63
+ if (line.startsWith('To finish the batch, call ')) {
64
+ // tasks resume replays the request ID for 23 of the gateway's 24 hours (RECOVERY_WINDOW_MS).
65
+ return line.replace(/^To finish the batch, call \S+ again with client_request_id "[^"]*" and exactly the same inputs/, `To finish the batch, run evolink tasks resume --quote ${id}`)
66
+ .replace(' within 24 hours of its first submission', ' within 23 hours of its first submission');
67
+ }
68
+ if (line.startsWith('The outcome of ')) {
69
+ return line.replace(/retry later with the same client_request_id and inputs, or check list_tasks\.$/, `run evolink tasks resume --quote ${id} later, or check evolink tasks list --since 30m.`);
70
+ }
71
+ if (line.startsWith('Never resubmit ')) return 'Never resubmit accepted, not-submitted or unknown-outcome inputs with a new estimate or generate command: that creates and charges new tasks.';
72
+ return line;
73
+ }).join('\n');
74
+ }
75
+
76
+ /** The shared core's refusal of a replayed approval, before anything is sent: its price rose, or it expired. */
77
+ function replayRefusal(error) {
78
+ const code = error?.details?.error?.code;
79
+ return ['price_changed', 'quote_expired'].includes(code) && error.details.charged === 'no' ? code : undefined;
80
+ }
18
81
 
19
82
  function interrupted(taskId) {
20
83
  return new CliError('interrupted', 'Stopped waiting locally. The EvoLink task continues.', { task_id: taskId }, 130);
@@ -56,6 +119,7 @@ function quoteError(error, cap) {
56
119
  export function priceFingerprint(quote) {
57
120
  return hash({ model: quote.model, type: quote.type, input_valid: quote.input_valid, estimate: quote.estimate,
58
121
  ...(quote.effective_input ? { effective_input: quote.effective_input } : {}),
122
+ ...(Array.isArray(quote.items) ? { items: quote.items.map(item => item.effective_input ?? null) } : {}),
59
123
  warnings: quote.warnings, pricing_warning: quote.pricing_warning, pricing_scope: quote.pricing_scope,
60
124
  rules: quote.pricing_quote && { fingerprint: quote.pricing_quote.fingerprint, request_hash: quote.pricing_quote.request_hash, total_uc: quote.pricing_quote.total_uc },
61
125
  account: quote.account_quote && { request_hash: quote.account_quote.request_hash, parameters: quote.account_quote.parameters,
@@ -67,7 +131,7 @@ export function checkEstimate(quote, cap) {
67
131
  requireThat(quote.enough_limit !== false, 'insufficient_limit', 'The EvoLink MCP or API key spending limit does not cover this estimate. Adjust that limit; this is not the account balance.', { limit_scope: quote.limit_scope });
68
132
  requireThat(quote.enough_daily_limit !== false, 'insufficient_daily_limit', 'The daily spending limit does not cover this estimate. Wait for its reset or adjust that limit; this is not the account balance.');
69
133
  requireThat(quote.enough_balance !== false, 'insufficient_balance', 'The EvoLink account balance does not cover this estimate.');
70
- if (quote.estimate?.status === 'estimated') {
134
+ if (quote.estimate?.status === 'estimated' || quote.estimate?.status === 'token_billed' && quote.estimate.max_usd !== undefined) {
71
135
  const { min_usd, max_usd } = quote.estimate;
72
136
  requireThat(Number.isFinite(max_usd) && max_usd >= 0 && (min_usd === undefined || Number.isFinite(min_usd) && min_usd >= 0 && min_usd <= max_usd),
73
137
  'estimate_unavailable', 'The service returned an invalid price range. Obtain a valid quote before submission.');
@@ -75,12 +139,17 @@ export function checkEstimate(quote, cap) {
75
139
  if (cap !== undefined) {
76
140
  requireThat(Number.isFinite(cap) && cap > 0 && cap <= 10_000, 'invalid_cap', 'max-cost-usd must be greater than 0 and at most 10000.');
77
141
  requireThat(quote.input_valid === true, 'uncheckable_input', 'The service could not validate the model input. The CLI cannot submit this request with a spending cap.', { problems: quote.problems });
78
- requireThat(quote.estimate?.status === 'estimated' && Number.isFinite(quote.estimate.max_usd),
142
+ // A token-billed reference price settles at actual usage: the budget must cover the core's allowance above it.
143
+ const reference = quote.estimate?.status === 'token_billed' && Number.isFinite(quote.estimate.max_usd)
144
+ && quote.estimate.uncheckable_reason === undefined && quote.pricing_quote;
145
+ requireThat(reference || quote.estimate?.status === 'estimated' && Number.isFinite(quote.estimate.max_usd),
79
146
  'uncheckable_cap', 'This request has no complete cost estimate. The CLI cannot submit it with a spending cap.', { estimate: quote.estimate });
80
- const withinBudget = quote.pricing_quote ? !rulesBudgetExceeded(quote.pricing_quote.total_uc, cap) : quote.account_quote
147
+ const withinBudget = reference ? !referenceBudgetExceeded(quote.pricing_quote.total_uc, cap) : quote.pricing_quote ? !rulesBudgetExceeded(quote.pricing_quote.total_uc, cap) : quote.account_quote
81
148
  ? compareDecimal(quote.account_quote.quote.amount, String(cap)) <= 0
82
149
  : quote.estimate.max_usd <= cap;
83
- requireThat(withinBudget, 'cost_exceeds_cap', 'The estimated cost exceeds max-cost-usd.', { estimate: quote.estimate, max_cost_usd: cap });
150
+ requireThat(withinBudget, 'cost_exceeds_cap', reference
151
+ ? `The reference price is billed by actual token usage, and ${REFERENCE_BUDGET_FACTOR} times it exceeds max-cost-usd.`
152
+ : 'The estimated cost exceeds max-cost-usd.', { estimate: quote.estimate, max_cost_usd: cap });
84
153
  }
85
154
  // The core names each missing usage in MCP terms; say once how they map to CLI options.
86
155
  requireThat(quote.estimate?.status !== 'needs_input' || !quote.estimate.usage_help?.length, 'estimate_unavailable', [
@@ -121,7 +190,7 @@ export class Media {
121
190
  ...(quote.effective_input ? { effective_input: quote.effective_input, defaults_applied: quote.defaults_applied } : {}),
122
191
  created_at: this.now(), expires_at: expires, ...(quote.account_quote ? { backend_estimate_id: quote.account_quote.quote.estimate_id,
123
192
  server_expires_at: serverExpiry, account_quote: quote.account_quote } : {}), state: 'quoted', client_request_id: `cli-${randomUUID()}` };
124
- 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(),
193
+ const view = { ...quote, quote_id: id, ...(input.inputs ? { inputs: input.inputs } : { input: input.input || {} }), ...(max_cost_usd !== undefined ? { max_cost_usd, cap_source: 'user' } : {}), expires_at: new Date(stored.expires_at).toISOString(),
125
194
  requires_confirmation: true, next_step: `After the user approves, run evolink generate ${quote.type} --quote ${id} --confirm.` };
126
195
  return { stored, view };
127
196
  }
@@ -137,7 +206,7 @@ export class Media {
137
206
  // Checked before and again after the estimate, under the lock that submission and recovery share: a submission
138
207
  // or another refresh while the estimate ran means no new submittable quote is saved.
139
208
  const before = await this.state.lock(lock, () => this.refreshable(intentId));
140
- const { account_quote, pricing_quote, ...args } = before.args;
209
+ const { account_quote, pricing_quote, skip_estimate, ...args } = before.args;
141
210
  const { stored, view } = await this.prepareQuote(args);
142
211
  return this.state.lock(lock, async () => {
143
212
  const current = await this.refreshable(intentId);
@@ -163,7 +232,8 @@ export class Media {
163
232
  'This submission has started. Recover its original task instead of refreshing its quote.', {
164
233
  quote_id: active.id, client_request_id: active.client_request_id, submission_allowed: false,
165
234
  ...(active.task_id ? { task_id: active.task_id, recovery: `evolink tasks get ${active.task_id}` }
166
- : ['submitting', 'outcome_unknown'].includes(active.state) ? { recovery: `evolink tasks resume --quote ${active.id}` } : {}) });
235
+ : active.task_ids?.length && active.state === 'submitted' ? { task_ids: active.task_ids, recovery: `evolink tasks batch --ids ${active.task_ids.join(',')}` }
236
+ : RECOVERABLE.includes(active.state) ? { recovery: `evolink tasks resume --quote ${active.id}` } : {}) });
167
237
  return active;
168
238
  }
169
239
  /** Only the generation's current quote may be submitted or recovered; any other names the current one or its task. */
@@ -179,7 +249,10 @@ export class Media {
179
249
  if (active?.task_id) throw new CliError('quote_superseded',
180
250
  `This quote was replaced by quote ${activeId}, which was already submitted as task ${active.task_id}. Do not generate again.`,
181
251
  { ...details, task_id: active.task_id, recovery: `evolink tasks get ${active.task_id}` });
182
- if (['submitting', 'outcome_unknown'].includes(active?.state)) throw new CliError('quote_superseded',
252
+ if (active?.state === 'submitted' && active.task_ids?.length) throw new CliError('quote_superseded',
253
+ `This quote was replaced by quote ${activeId}, which was already submitted as ${active.task_ids.length} tasks. Do not generate again.`,
254
+ { ...details, task_ids: active.task_ids, recovery: `evolink tasks batch --ids ${active.task_ids.join(',')}` });
255
+ if (RECOVERABLE.includes(active?.state)) throw new CliError('quote_superseded',
183
256
  `This quote was replaced by quote ${activeId}, whose submission is unverified. Recover that quote; do not create a new request.`,
184
257
  { ...details, recovery: `evolink tasks resume --quote ${activeId}` });
185
258
  throw new CliError('quote_superseded', `This quote was replaced by quote ${activeId}. Show the user that quote and obtain approval for it.`,
@@ -193,6 +266,19 @@ export class Media {
193
266
  requireThat(quote.args_hash === hash(quote.args), 'quote_changed', 'The saved request changed. Estimate again.');
194
267
  return quote;
195
268
  }
269
+ /**
270
+ * Generation without a quote, only when the user explicitly opted out of estimates (skip_estimate). The saved record
271
+ * has its own request ID, so tasks resume recovers an uncertain submission and a retry never submits twice.
272
+ */
273
+ async direct(kind, args) {
274
+ requireThat(['image', 'video', 'audio'].includes(kind), 'invalid_type', 'Choose image, video or audio.');
275
+ const { binding } = await this.client.credentials.access();
276
+ const id = randomUUID(), submitArgs = { ...args, skip_estimate: true };
277
+ await this.state.write('quotes', id, { id, server: this.server, binding, args: submitArgs,
278
+ ...(this.client.apiUrl ? { backend: 'platform', api_origin: this.client.apiUrl.origin } : {}),
279
+ type: kind, args_hash: hash(submitArgs), skip_estimate: true, created_at: this.now(), state: 'quoted', client_request_id: `cli-${randomUUID()}` });
280
+ return this.generate(kind, id, { confirmed: true });
281
+ }
196
282
  async generate(kind, id, { confirmed = false, resume = false } = {}) {
197
283
  requireThat(['image', 'video', 'audio'].includes(kind), 'invalid_type', 'Choose image, video or audio.');
198
284
  requireThat(confirmed || resume, 'confirmation_required', 'Show the quote to the user and obtain approval before adding --confirm.');
@@ -201,7 +287,11 @@ export class Media {
201
287
  return this.state.lock(`quote-${intentId}`, async () => {
202
288
  const quote = await this.load(id);
203
289
  requireThat(quote.type === kind, 'quote_type_mismatch', 'Use the media type shown in the saved quote.');
290
+ const batch = isBatch(quote);
204
291
  if (quote.task_id) return { ...await this.client.call('get_task', { task_id: quote.task_id, wait_seconds: 0 }), quote_id: id, recovered: true };
292
+ // A batch whose every input was accepted is read back, never submitted again.
293
+ if (batch && quote.state === 'submitted') return { ...await this.client.call('list_tasks', { task_ids: quote.task_ids }), quote_id: id,
294
+ client_request_id: quote.client_request_id, task_ids: quote.task_ids, recovered: true };
205
295
  await this.requireActive(quote, kind);
206
296
  requireThat(quote.state !== 'refused', 'submission_refused',
207
297
  '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.',
@@ -210,39 +300,56 @@ export class Media {
210
300
  'This quote has never been submitted. After user approval, use generate with this same quote; tasks resume only recovers an uncertain submission.',
211
301
  { quote_id: id, client_request_id: quote.client_request_id, submission_allowed: false,
212
302
  next_step: `After user approval, run evolink generate ${kind} --quote ${id} --confirm.` });
213
- requireThat(resume ? ['submitting', 'outcome_unknown'].includes(quote.state) : quote.state === 'quoted',
214
- 'submission_already_started', 'A submission already started. Use tasks resume with this quote; do not create a new request ID.', { quote_id: id, client_request_id: quote.client_request_id });
215
- requireThat(this.now() < quote.expires_at, 'quote_expired', 'The quote expired. Check recent tasks before preparing another submission.', { quote_id: id, client_request_id: quote.client_request_id });
216
- const { max_cost_usd, account_quote, pricing_quote, ...checkArgs } = quote.args;
217
- let fresh;
218
- try {
219
- // Preserve the original approved request during uncertain submission recovery.
220
- fresh = resume && (account_quote || pricing_quote) ? { model: quote.args.model, type: quote.type, input_valid: true, estimate: quote.estimate, account_quote, pricing_quote }
221
- : await this.client.call('estimate_cost', checkArgs);
222
- requireThat(resume && (account_quote || pricing_quote) || priceFingerprint(fresh) === quote.fingerprint, 'price_changed', 'The quote changed. Estimate again and obtain approval for the new quote.', { estimate: fresh.estimate });
223
- checkEstimate(fresh, max_cost_usd);
224
- } catch (error) { throw quoteError(error, max_cost_usd); }
225
- if (!resume && fresh.pricing_quote) {
226
- const expires = Date.parse(fresh.pricing_quote.expires_at);
227
- requireThat(Number.isFinite(expires) && expires > this.now(), 'quote_expired', 'The refreshed estimate expired before submission.');
228
- quote.args.pricing_quote = fresh.pricing_quote;
229
- quote.server_expires_at = expires;
230
- quote.args_hash = hash(quote.args);
231
- }
232
- if (!resume && fresh.account_quote) {
233
- const expires = Date.parse(fresh.account_quote.quote.expires_at);
234
- requireThat(Number.isFinite(expires) && expires > this.now(), 'quote_expired', 'The refreshed account quote expired before submission.');
235
- quote.args.account_quote = fresh.account_quote; quote.account_quote = fresh.account_quote;
236
- quote.backend_estimate_id = fresh.account_quote.quote.estimate_id; quote.server_expires_at = expires;
237
- quote.args_hash = hash(quote.args);
303
+ requireThat(resume ? RECOVERABLE.includes(quote.state) : quote.state === 'quoted',
304
+ 'submission_already_started', 'A submission already started. Use tasks resume with this quote; do not create a new request ID.',
305
+ { quote_id: id, client_request_id: quote.client_request_id, recovery: `evolink tasks resume --quote ${id}` });
306
+ // Past the gateway's 24 hours the original request ID no longer prevents a second paid task.
307
+ if (resume) requireThat(this.now() < (quote.approved_at ?? quote.created_at) + RECOVERY_WINDOW_MS, 'recovery_window_passed',
308
+ 'This request ID was first submitted more than 23 hours ago. EvoLink keeps a request ID for 24 hours, so replaying it now could create and charge a new task. Check recent tasks with evolink tasks list --since 2d instead.',
309
+ { quote_id: id, client_request_id: quote.client_request_id, submission_allowed: false, ...dashboardCheck() });
310
+ if (!quote.skip_estimate && this.now() >= quote.expires_at) throw expiredQuote(quote, id, resume);
311
+ const { max_cost_usd, account_quote, pricing_quote, skip_estimate, ...checkArgs } = quote.args;
312
+ // skip_estimate: the user opted out of estimates; the shared core still refuses invalid input and an unpriceable budget.
313
+ if (!quote.skip_estimate) {
314
+ let fresh;
315
+ try {
316
+ // Recovery sends the original approved request, which the shared core checks against the current price itself.
317
+ const replay = resume && (account_quote || pricing_quote);
318
+ fresh = replay ? { model: quote.args.model, type: quote.type, input_valid: true, estimate: quote.estimate, account_quote, pricing_quote }
319
+ : await this.client.call('estimate_cost', checkArgs);
320
+ if (!replay) {
321
+ const held = approvalHolds(fresh, quote);
322
+ requireThat(held.input, 'quote_input_changed', 'The input as EvoLink reads it changed since the quote. Estimate again and obtain approval for the new quote.', { estimate: fresh.estimate });
323
+ requireThat(!held.rose, 'price_changed', held.byFingerprint ? 'The quote changed. Estimate again and obtain approval for the new quote.'
324
+ : 'The price rose since the quote was approved. Estimate again and obtain approval for the new quote.', { estimate: fresh.estimate });
325
+ }
326
+ checkEstimate(fresh, max_cost_usd);
327
+ } catch (error) { throw quoteError(error, max_cost_usd); }
328
+ if (!resume && fresh.pricing_quote) {
329
+ const expires = Date.parse(fresh.pricing_quote.expires_at);
330
+ requireThat(Number.isFinite(expires) && expires > this.now(), 'quote_expired', 'The refreshed estimate expired before submission.');
331
+ quote.args.pricing_quote = fresh.pricing_quote;
332
+ quote.server_expires_at = expires;
333
+ quote.args_hash = hash(quote.args);
334
+ }
335
+ if (!resume && fresh.account_quote) {
336
+ const expires = Date.parse(fresh.account_quote.quote.expires_at);
337
+ requireThat(Number.isFinite(expires) && expires > this.now(), 'quote_expired', 'The refreshed account quote expired before submission.');
338
+ quote.args.account_quote = fresh.account_quote; quote.account_quote = fresh.account_quote;
339
+ quote.backend_estimate_id = fresh.account_quote.quote.estimate_id; quote.server_expires_at = expires;
340
+ quote.args_hash = hash(quote.args);
341
+ }
238
342
  }
343
+ const previous = quote.state;
239
344
  quote.state = 'submitting';
240
345
  quote.approved_at ??= this.now();
241
346
  await this.state.write('quotes', id, quote);
347
+ const { pricing_source, ...generationArgs } = quote.args;
348
+ const request = { ...generationArgs, client_request_id: quote.client_request_id };
349
+ if (batch) return this.submitBatch(kind, id, quote, request, { resume, previous });
242
350
  let result;
243
351
  try {
244
- const { pricing_source, ...generationArgs } = quote.args;
245
- result = await this.client.call(`generate_${kind}`, { ...generationArgs, client_request_id: quote.client_request_id });
352
+ result = await this.client.call(`generate_${kind}`, request);
246
353
  requireThat(typeof result.task_id === 'string' && result.task_id.length > 0, 'outcome_unknown', 'The submission returned no task ID. Recover with the original quote.');
247
354
  } catch (e) {
248
355
  // Acceptance survives later read/format failures; recovery must query this ID, never POST again.
@@ -259,6 +366,11 @@ export class Media {
259
366
  }
260
367
  quote.state = !resume && e.details?.charged === 'no' && ['not_submitted', 'rejected'].includes(e.details?.submission_state) ? 'refused' : 'outcome_unknown';
261
368
  await this.state.write('quotes', id, quote);
369
+ // The shared core refused the replay before sending it: the approval no longer holds (price or age).
370
+ const approval = resume && replayRefusal(e);
371
+ if (approval) throw new CliError(approval, `${approval === 'price_changed' ? 'The price rose since the quote was approved' : 'The quote expired'}, so the replay was not sent, and the original submission remains unverified. Check evolink tasks list --since 2d first to see whether it went through; only if it did not, estimate it again and, after the user approves, submit it as a new generation.`,
372
+ { ...(e.details || {}), charged: 'unknown', submission_state: 'outcome_unknown', quote_id: id, client_request_id: quote.client_request_id, submission_allowed: false,
373
+ next_step: 'evolink tasks list --since 2d', ...dashboardCheck() }, e.exitCode);
262
374
  throw new CliError(resume ? 'outcome_unknown' : e.code || 'outcome_unknown', resume ? 'The original submission remains unverified. The replay could not proceed; check recent tasks with the original request ID before preparing any new generation.' : e.message, { ...(e.details || {}), ...(quote.state === 'outcome_unknown' ? { charged: 'unknown', submission_state: 'outcome_unknown' } : {}), quote_id: id, client_request_id: quote.client_request_id,
263
375
  recovery: `evolink tasks resume --quote ${id}` }, e.exitCode);
264
376
  }
@@ -268,6 +380,43 @@ export class Media {
268
380
  return { ...result, quote_id: id, client_request_id: quote.client_request_id };
269
381
  });
270
382
  }
383
+ /**
384
+ * Submits a batch quote's inputs in one shared-core call and records each input's outcome. The same request ID and
385
+ * inputs (tasks resume) later return accepted inputs without a new charge and submit only those still to finish.
386
+ */
387
+ async submitBatch(kind, id, quote, request, { resume, previous }) {
388
+ let result, failure;
389
+ try { result = await this.client.call(`generate_${kind}`, request); } catch (error) { failure = error; }
390
+ const outcome = result ?? failure?.details ?? {};
391
+ const items = Array.isArray(outcome.items) ? outcome.items : undefined;
392
+ // Refused before any input was sent, so this call charged nothing; inputs accepted earlier keep their tasks.
393
+ const refusedBefore = !items && failure?.details?.charged === 'no' && ['not_submitted', 'rejected'].includes(failure.details.submission_state);
394
+ if (items) {
395
+ quote.items = items.map(item => ({ index: item.index, client_request_id: item.client_request_id, submission_state: item.submission_state,
396
+ ...(typeof item.task_id === 'string' ? { task_id: item.task_id } : {}), ...(typeof item.finishable === 'boolean' ? { finishable: item.finishable } : {}) }));
397
+ quote.task_ids = items.flatMap(item => item.submission_state === 'accepted' && typeof item.task_id === 'string' ? [item.task_id] : []);
398
+ // partial: the same request ID can still finish or verify some input. Refusals it would only get again close
399
+ // the batch: submitted when some input was accepted, refused when none was.
400
+ quote.state = quote.task_ids.length === quote.args.inputs.length ? 'submitted'
401
+ : items.some(item => item.submission_state === 'outcome_unknown' || item.finishable) ? 'partial' : quote.task_ids.length ? 'submitted' : 'refused';
402
+ } else quote.state = refusedBefore ? (resume ? (previous === 'partial' ? 'partial' : 'outcome_unknown') : 'refused') : 'outcome_unknown';
403
+ await this.state.write('quotes', id, quote);
404
+ const taskIds = quote.task_ids ?? [];
405
+ const view = { ...outcome, quote_id: id, client_request_id: quote.client_request_id, task_ids: taskIds, text: cliBatchText(outcome.text, id, taskIds),
406
+ ...(taskIds.length ? { collect: `evolink tasks batch --ids ${taskIds.join(',')}` } : {}),
407
+ ...(RECOVERABLE.includes(quote.state) ? { recovery: `evolink tasks resume --quote ${id}` } : {}) };
408
+ if (result) return view;
409
+ if (items) throw new CliError(failure.code || 'batch_not_submitted', failure.message, view, failure.exitCode);
410
+ // The shared core refused the replay before sending anything because the approval no longer holds (price or age).
411
+ const approval = resume && refusedBefore && replayRefusal(failure);
412
+ const check = `${taskIds.length ? `evolink tasks batch --ids ${taskIds.join(',')} and ` : ''}evolink tasks list --since 2d`;
413
+ throw new CliError(approval || (resume && !refusedBefore ? 'outcome_unknown' : failure.code || 'outcome_unknown'), approval
414
+ ? `${approval === 'price_changed' ? 'The total price rose since the quote was approved' : 'The quote expired'}, so nothing was sent. Check ${check} first to see which inputs went through; then estimate only the inputs that did not and, after the user approves, submit them as a new batch.`
415
+ : resume && !refusedBefore ? 'The batch submission remains unverified. The replay could not proceed; check recent tasks with the original request ID before preparing any new generation.' : failure.message, {
416
+ ...view, ...(quote.state === 'outcome_unknown' ? { charged: 'unknown', submission_state: 'outcome_unknown' } : {}),
417
+ ...(refusedBefore && quote.state === 'partial' ? { items: quote.items, next_step: 'This call submitted nothing. Accepted inputs keep their tasks (task_ids). Resolve the error; then finish the rest with tasks resume, or estimate them again as a new batch if their price or input changed.' } : {}),
418
+ }, failure.exitCode);
419
+ }
271
420
  async resume(id) {
272
421
  const quote = await this.load(id);
273
422
  return this.generate(quote.type, id, { resume: true });
@@ -41,21 +41,24 @@ export function withModelConstraints(model) {
41
41
  if (properties)
42
42
  properties.duration = { type: 'integer', anyOf: model.params.duration.anyOf, description: model.params.duration.description, default: model.params.duration.default };
43
43
  }
44
- // mintlify-docs kling-v4-video-edit.json: duration is 3-30 seconds or "auto" (as long as the input video);
45
- // the generated index keeps the range but leaves any string open.
46
- if (model.model === 'kling-v4-video-edit') {
47
- const anyOf = [{ type: 'integer', minimum: 3, maximum: 30 }, { type: 'string', enum: ['auto'] }];
44
+ // mintlify-docs kling-v4-video-edit.json and kling-v4-flash-video-edit.json: duration is 3-30 (Flash 3-20) seconds
45
+ // or "auto" (as long as the input video); the generated index keeps the range but leaves any string open.
46
+ const klingEditMaximum = { 'kling-v4-video-edit': 30, 'kling-v4-flash-video-edit': 20 }[model.model];
47
+ if (klingEditMaximum) {
48
+ const anyOf = [{ type: 'integer', minimum: 3, maximum: klingEditMaximum }, { type: 'string', enum: ['auto'] }];
48
49
  model.params.duration = { ...model.params.duration, anyOf };
49
50
  const properties = model.inputSchema?.schema.properties;
50
51
  if (properties)
51
52
  properties.duration = { anyOf, description: model.params.duration.description, default: model.params.duration.default };
52
53
  }
53
- if (['gpt-image-2', 'gpt-image-2.5-flare', 'gpt-image-2.5-sunburst', 'gpt-image-2-beta'].includes(model.model)) {
54
+ if (['gpt-image-2', 'gpt-image-2.5-flare', 'gpt-image-2.5-sunburst', 'gpt-image-2.6-flare', 'gpt-image-2.6-sunburst', 'gpt-image-2-beta'].includes(model.model)) {
54
55
  model.constraints = { ...model.constraints, imageSize: {
55
56
  param: 'size', allowed: ['auto', '1:1', '1:2', '2:1', '1:3', '3:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '9:21', '21:9'],
56
57
  allowPixels: model.model !== 'gpt-image-2-beta', step: 16, minEdge: 16, maxEdge: 3840,
57
58
  minPixels: 655360, maxPixels: 8294400, maxRatio: 3,
58
59
  ...(model.model === 'gpt-image-2-beta' ? { ratioResolution: '1K' } : {}),
60
+ // GPT Image 2.6 GIF (unified_images_gpt_image26.go): size is each frame's, auto or pixels, never a ratio.
61
+ ...(model.model.startsWith('gpt-image-2.6') ? { frames: { outputFormat: 'gif', step: 16, minEdge: 16, maxEdge: 3840 } } : {}),
59
62
  } };
60
63
  const properties = model.inputSchema?.schema.properties;
61
64
  if (properties)