@evolinkai/cli 0.12.0 → 0.14.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 (35) hide show
  1. package/README.md +20 -6
  2. package/package.json +2 -2
  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 +148 -37
  10. package/src/platform/core/src/data/model-constraints.js +13 -1
  11. package/src/platform/core/src/data/model-params.overrides.generated.js +1 -1
  12. package/src/platform/core/src/platform-operations.js +1 -1
  13. package/src/platform/core/src/services/api-client.js +1 -1
  14. package/src/platform/core/src/services/batch-generation.js +117 -0
  15. package/src/platform/core/src/services/catalog-client.js +28 -2
  16. package/src/platform/core/src/services/gpt-image-tokens.js +264 -0
  17. package/src/platform/core/src/services/mj-prompt.js +18 -0
  18. package/src/platform/core/src/services/model-capabilities.js +2 -1
  19. package/src/platform/core/src/services/omni-tokens.js +245 -0
  20. package/src/platform/core/src/services/param-validator.js +48 -1
  21. package/src/platform/core/src/services/pricing-call-limit.js +40 -0
  22. package/src/platform/core/src/services/pricing-derived.js +59 -0
  23. package/src/platform/core/src/services/pricing-quote-client.js +30 -7
  24. package/src/platform/core/src/services/pricing-rules-client.js +56 -3
  25. package/src/platform/core/src/services/pricing-rules-estimate.js +376 -59
  26. package/src/platform/core/src/tool-guidance.js +25 -2
  27. package/src/platform/core/src/tools/estimate-cost.js +220 -63
  28. package/src/platform/core/src/tools/generate.js +505 -71
  29. package/src/platform/core/src/tools/get-model.js +28 -0
  30. package/src/platform/core/src/tools/get-pricing-rules.js +15 -5
  31. package/src/platform/core/src/tools/search-models.js +4 -1
  32. package/src/platform/core/src/tools/shared.js +5 -1
  33. package/src/platform/core/src/version.js +1 -1
  34. package/src/platform/source.json +54 -42
  35. package/src/state.mjs +12 -1
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, 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,39 @@ 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
+ /** A first submission of an expired quote whose input and price were unchanged says so in its result. */
30
+ function withExpiry(view, quote) {
31
+ if (!quote) return view;
32
+ const at = new Date(quote.expires_at).toISOString();
33
+ const line = `The quote expired at ${at}, but its input and price are unchanged, so it was submitted under the original approval.`;
34
+ return { ...view, approval_expired: true, quote_expired_at: at, text: view.text ? `${view.text}\n${line}` : line };
35
+ }
36
+
37
+ /** The shared core's batch result names its own tool calls; for the CLI these lines name the CLI commands instead. */
38
+ export function cliBatchText(text, id, taskIds) {
39
+ return (text ?? '').split('\n').map(line => {
40
+ 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.`;
41
+ if (line.startsWith('To finish the batch, call ')) {
42
+ 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}`);
43
+ }
44
+ if (line.startsWith('The outcome of ')) {
45
+ 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.`);
46
+ }
47
+ 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.';
48
+ return line;
49
+ }).join('\n');
50
+ }
18
51
 
19
52
  function interrupted(taskId) {
20
53
  return new CliError('interrupted', 'Stopped waiting locally. The EvoLink task continues.', { task_id: taskId }, 130);
@@ -56,6 +89,7 @@ function quoteError(error, cap) {
56
89
  export function priceFingerprint(quote) {
57
90
  return hash({ model: quote.model, type: quote.type, input_valid: quote.input_valid, estimate: quote.estimate,
58
91
  ...(quote.effective_input ? { effective_input: quote.effective_input } : {}),
92
+ ...(Array.isArray(quote.items) ? { items: quote.items.map(item => item.effective_input ?? null) } : {}),
59
93
  warnings: quote.warnings, pricing_warning: quote.pricing_warning, pricing_scope: quote.pricing_scope,
60
94
  rules: quote.pricing_quote && { fingerprint: quote.pricing_quote.fingerprint, request_hash: quote.pricing_quote.request_hash, total_uc: quote.pricing_quote.total_uc },
61
95
  account: quote.account_quote && { request_hash: quote.account_quote.request_hash, parameters: quote.account_quote.parameters,
@@ -67,7 +101,7 @@ export function checkEstimate(quote, cap) {
67
101
  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
102
  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
103
  requireThat(quote.enough_balance !== false, 'insufficient_balance', 'The EvoLink account balance does not cover this estimate.');
70
- if (quote.estimate?.status === 'estimated') {
104
+ if (quote.estimate?.status === 'estimated' || quote.estimate?.status === 'token_billed' && quote.estimate.max_usd !== undefined) {
71
105
  const { min_usd, max_usd } = quote.estimate;
72
106
  requireThat(Number.isFinite(max_usd) && max_usd >= 0 && (min_usd === undefined || Number.isFinite(min_usd) && min_usd >= 0 && min_usd <= max_usd),
73
107
  'estimate_unavailable', 'The service returned an invalid price range. Obtain a valid quote before submission.');
@@ -75,13 +109,24 @@ export function checkEstimate(quote, cap) {
75
109
  if (cap !== undefined) {
76
110
  requireThat(Number.isFinite(cap) && cap > 0 && cap <= 10_000, 'invalid_cap', 'max-cost-usd must be greater than 0 and at most 10000.');
77
111
  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),
112
+ // A token-billed reference price settles at actual usage: the budget must cover the core's allowance above it.
113
+ const reference = quote.estimate?.status === 'token_billed' && Number.isFinite(quote.estimate.max_usd)
114
+ && quote.estimate.uncheckable_reason === undefined && quote.pricing_quote;
115
+ requireThat(reference || quote.estimate?.status === 'estimated' && Number.isFinite(quote.estimate.max_usd),
79
116
  '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
117
+ const withinBudget = reference ? !referenceBudgetExceeded(quote.pricing_quote.total_uc, cap) : quote.pricing_quote ? !rulesBudgetExceeded(quote.pricing_quote.total_uc, cap) : quote.account_quote
81
118
  ? compareDecimal(quote.account_quote.quote.amount, String(cap)) <= 0
82
119
  : 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 });
120
+ requireThat(withinBudget, 'cost_exceeds_cap', reference
121
+ ? `The reference price is billed by actual token usage, and ${REFERENCE_BUDGET_FACTOR} times it exceeds max-cost-usd.`
122
+ : 'The estimated cost exceeds max-cost-usd.', { estimate: quote.estimate, max_cost_usd: cap });
84
123
  }
124
+ // The core names each missing usage in MCP terms; say once how they map to CLI options.
125
+ requireThat(quote.estimate?.status !== 'needs_input' || !quote.estimate.usage_help?.length, 'estimate_unavailable', [
126
+ 'The total cannot be estimated yet, so no quote was saved. It depends on:', ...(quote.estimate?.usage_help ?? []).map(line => `- ${line}`),
127
+ 'In the CLI, media_seconds is --media-seconds and pricing_parameters is --pricing-parameters (a JSON object).'].join('\n'),
128
+ // A copy: the redaction of error details shows an object it has already printed as "[truncated]".
129
+ { estimate: quote.estimate, missing_usage: [...(quote.estimate?.missing_usage ?? [])] });
85
130
  requireThat(['estimated', 'partial', 'token_billed'].includes(quote.estimate?.status), 'estimate_unavailable', 'Complete the estimate input or choose a model with pricing before submission.', { estimate: quote.estimate });
86
131
  }
87
132
 
@@ -115,7 +160,7 @@ export class Media {
115
160
  ...(quote.effective_input ? { effective_input: quote.effective_input, defaults_applied: quote.defaults_applied } : {}),
116
161
  created_at: this.now(), expires_at: expires, ...(quote.account_quote ? { backend_estimate_id: quote.account_quote.quote.estimate_id,
117
162
  server_expires_at: serverExpiry, account_quote: quote.account_quote } : {}), state: 'quoted', client_request_id: `cli-${randomUUID()}` };
118
- const view = { ...quote, quote_id: id, input: input.input || {}, ...(max_cost_usd !== undefined ? { max_cost_usd, cap_source: 'user' } : {}), expires_at: new Date(stored.expires_at).toISOString(),
163
+ 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(),
119
164
  requires_confirmation: true, next_step: `After the user approves, run evolink generate ${quote.type} --quote ${id} --confirm.` };
120
165
  return { stored, view };
121
166
  }
@@ -131,7 +176,7 @@ export class Media {
131
176
  // Checked before and again after the estimate, under the lock that submission and recovery share: a submission
132
177
  // or another refresh while the estimate ran means no new submittable quote is saved.
133
178
  const before = await this.state.lock(lock, () => this.refreshable(intentId));
134
- const { account_quote, pricing_quote, ...args } = before.args;
179
+ const { account_quote, pricing_quote, skip_estimate, ...args } = before.args;
135
180
  const { stored, view } = await this.prepareQuote(args);
136
181
  return this.state.lock(lock, async () => {
137
182
  const current = await this.refreshable(intentId);
@@ -157,7 +202,8 @@ export class Media {
157
202
  'This submission has started. Recover its original task instead of refreshing its quote.', {
158
203
  quote_id: active.id, client_request_id: active.client_request_id, submission_allowed: false,
159
204
  ...(active.task_id ? { task_id: active.task_id, recovery: `evolink tasks get ${active.task_id}` }
160
- : ['submitting', 'outcome_unknown'].includes(active.state) ? { recovery: `evolink tasks resume --quote ${active.id}` } : {}) });
205
+ : active.task_ids?.length && active.state === 'submitted' ? { task_ids: active.task_ids, recovery: `evolink tasks batch --ids ${active.task_ids.join(',')}` }
206
+ : RECOVERABLE.includes(active.state) ? { recovery: `evolink tasks resume --quote ${active.id}` } : {}) });
161
207
  return active;
162
208
  }
163
209
  /** Only the generation's current quote may be submitted or recovered; any other names the current one or its task. */
@@ -173,7 +219,10 @@ export class Media {
173
219
  if (active?.task_id) throw new CliError('quote_superseded',
174
220
  `This quote was replaced by quote ${activeId}, which was already submitted as task ${active.task_id}. Do not generate again.`,
175
221
  { ...details, task_id: active.task_id, recovery: `evolink tasks get ${active.task_id}` });
176
- if (['submitting', 'outcome_unknown'].includes(active?.state)) throw new CliError('quote_superseded',
222
+ if (active?.state === 'submitted' && active.task_ids?.length) throw new CliError('quote_superseded',
223
+ `This quote was replaced by quote ${activeId}, which was already submitted as ${active.task_ids.length} tasks. Do not generate again.`,
224
+ { ...details, task_ids: active.task_ids, recovery: `evolink tasks batch --ids ${active.task_ids.join(',')}` });
225
+ if (RECOVERABLE.includes(active?.state)) throw new CliError('quote_superseded',
177
226
  `This quote was replaced by quote ${activeId}, whose submission is unverified. Recover that quote; do not create a new request.`,
178
227
  { ...details, recovery: `evolink tasks resume --quote ${activeId}` });
179
228
  throw new CliError('quote_superseded', `This quote was replaced by quote ${activeId}. Show the user that quote and obtain approval for it.`,
@@ -187,6 +236,19 @@ export class Media {
187
236
  requireThat(quote.args_hash === hash(quote.args), 'quote_changed', 'The saved request changed. Estimate again.');
188
237
  return quote;
189
238
  }
239
+ /**
240
+ * Generation without a quote, only when the user explicitly opted out of estimates (skip_estimate). The saved record
241
+ * has its own request ID, so tasks resume recovers an uncertain submission and a retry never submits twice.
242
+ */
243
+ async direct(kind, args) {
244
+ requireThat(['image', 'video', 'audio'].includes(kind), 'invalid_type', 'Choose image, video or audio.');
245
+ const { binding } = await this.client.credentials.access();
246
+ const id = randomUUID(), submitArgs = { ...args, skip_estimate: true };
247
+ await this.state.write('quotes', id, { id, server: this.server, binding, args: submitArgs,
248
+ ...(this.client.apiUrl ? { backend: 'platform', api_origin: this.client.apiUrl.origin } : {}),
249
+ type: kind, args_hash: hash(submitArgs), skip_estimate: true, created_at: this.now(), state: 'quoted', client_request_id: `cli-${randomUUID()}` });
250
+ return this.generate(kind, id, { confirmed: true });
251
+ }
190
252
  async generate(kind, id, { confirmed = false, resume = false } = {}) {
191
253
  requireThat(['image', 'video', 'audio'].includes(kind), 'invalid_type', 'Choose image, video or audio.');
192
254
  requireThat(confirmed || resume, 'confirmation_required', 'Show the quote to the user and obtain approval before adding --confirm.');
@@ -195,7 +257,11 @@ export class Media {
195
257
  return this.state.lock(`quote-${intentId}`, async () => {
196
258
  const quote = await this.load(id);
197
259
  requireThat(quote.type === kind, 'quote_type_mismatch', 'Use the media type shown in the saved quote.');
260
+ const batch = isBatch(quote);
198
261
  if (quote.task_id) return { ...await this.client.call('get_task', { task_id: quote.task_id, wait_seconds: 0 }), quote_id: id, recovered: true };
262
+ // A batch whose every input was accepted is read back, never submitted again.
263
+ if (batch && quote.state === 'submitted') return { ...await this.client.call('list_tasks', { task_ids: quote.task_ids }), quote_id: id,
264
+ client_request_id: quote.client_request_id, task_ids: quote.task_ids, recovered: true };
199
265
  await this.requireActive(quote, kind);
200
266
  requireThat(quote.state !== 'refused', 'submission_refused',
201
267
  '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.',
@@ -204,39 +270,51 @@ export class Media {
204
270
  'This quote has never been submitted. After user approval, use generate with this same quote; tasks resume only recovers an uncertain submission.',
205
271
  { quote_id: id, client_request_id: quote.client_request_id, submission_allowed: false,
206
272
  next_step: `After user approval, run evolink generate ${kind} --quote ${id} --confirm.` });
207
- requireThat(resume ? ['submitting', 'outcome_unknown'].includes(quote.state) : quote.state === 'quoted',
208
- 'submission_already_started', 'A submission already started. Use tasks resume with this quote; do not create a new request ID.', { quote_id: id, client_request_id: quote.client_request_id });
209
- requireThat(this.now() < quote.expires_at, 'quote_expired', 'The quote expired. Check recent tasks before preparing another submission.', { quote_id: id, client_request_id: quote.client_request_id });
210
- const { max_cost_usd, account_quote, pricing_quote, ...checkArgs } = quote.args;
211
- let fresh;
212
- try {
213
- // Preserve the original approved request during uncertain submission recovery.
214
- fresh = resume && (account_quote || pricing_quote) ? { model: quote.args.model, type: quote.type, input_valid: true, estimate: quote.estimate, account_quote, pricing_quote }
215
- : await this.client.call('estimate_cost', checkArgs);
216
- 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 });
217
- checkEstimate(fresh, max_cost_usd);
218
- } catch (error) { throw quoteError(error, max_cost_usd); }
219
- if (!resume && fresh.pricing_quote) {
220
- const expires = Date.parse(fresh.pricing_quote.expires_at);
221
- requireThat(Number.isFinite(expires) && expires > this.now(), 'quote_expired', 'The refreshed estimate expired before submission.');
222
- quote.args.pricing_quote = fresh.pricing_quote;
223
- quote.server_expires_at = expires;
224
- quote.args_hash = hash(quote.args);
225
- }
226
- if (!resume && fresh.account_quote) {
227
- const expires = Date.parse(fresh.account_quote.quote.expires_at);
228
- requireThat(Number.isFinite(expires) && expires > this.now(), 'quote_expired', 'The refreshed account quote expired before submission.');
229
- quote.args.account_quote = fresh.account_quote; quote.account_quote = fresh.account_quote;
230
- quote.backend_estimate_id = fresh.account_quote.quote.estimate_id; quote.server_expires_at = expires;
231
- quote.args_hash = hash(quote.args);
273
+ requireThat(resume ? RECOVERABLE.includes(quote.state) : quote.state === 'quoted',
274
+ 'submission_already_started', 'A submission already started. Use tasks resume with this quote; do not create a new request ID.',
275
+ { quote_id: id, client_request_id: quote.client_request_id, recovery: `evolink tasks resume --quote ${id}` });
276
+ // Past the gateway's 24 hours the original request ID no longer prevents a second paid task.
277
+ if (resume) requireThat(this.now() < (quote.approved_at ?? quote.created_at) + RECOVERY_WINDOW_MS, 'recovery_window_passed',
278
+ '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.',
279
+ { quote_id: id, client_request_id: quote.client_request_id, submission_allowed: false, ...dashboardCheck() });
280
+ // An expired quote still holds for its unchanged input and price: the fresh estimate below refuses a changed one.
281
+ const expired = !resume && !quote.skip_estimate && this.now() >= quote.expires_at;
282
+ const { max_cost_usd, account_quote, pricing_quote, skip_estimate, ...checkArgs } = quote.args;
283
+ // skip_estimate: the user opted out of estimates; the shared core still refuses invalid input and an unpriceable budget.
284
+ if (!quote.skip_estimate) {
285
+ let fresh;
286
+ try {
287
+ // Preserve the original approved request during uncertain submission recovery.
288
+ fresh = resume && (account_quote || pricing_quote) ? { model: quote.args.model, type: quote.type, input_valid: true, estimate: quote.estimate, account_quote, pricing_quote }
289
+ : await this.client.call('estimate_cost', checkArgs);
290
+ 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 });
291
+ checkEstimate(fresh, max_cost_usd);
292
+ } catch (error) { throw quoteError(error, max_cost_usd); }
293
+ if (!resume && fresh.pricing_quote) {
294
+ const expires = Date.parse(fresh.pricing_quote.expires_at);
295
+ requireThat(Number.isFinite(expires) && expires > this.now(), 'quote_expired', 'The refreshed estimate expired before submission.');
296
+ quote.args.pricing_quote = fresh.pricing_quote;
297
+ quote.server_expires_at = expires;
298
+ quote.args_hash = hash(quote.args);
299
+ }
300
+ if (!resume && fresh.account_quote) {
301
+ const expires = Date.parse(fresh.account_quote.quote.expires_at);
302
+ requireThat(Number.isFinite(expires) && expires > this.now(), 'quote_expired', 'The refreshed account quote expired before submission.');
303
+ quote.args.account_quote = fresh.account_quote; quote.account_quote = fresh.account_quote;
304
+ quote.backend_estimate_id = fresh.account_quote.quote.estimate_id; quote.server_expires_at = expires;
305
+ quote.args_hash = hash(quote.args);
306
+ }
232
307
  }
308
+ const previous = quote.state;
233
309
  quote.state = 'submitting';
234
310
  quote.approved_at ??= this.now();
235
311
  await this.state.write('quotes', id, quote);
312
+ const { pricing_source, ...generationArgs } = quote.args;
313
+ const request = { ...generationArgs, client_request_id: quote.client_request_id };
314
+ if (batch) return this.submitBatch(kind, id, quote, request, { resume, previous, expired });
236
315
  let result;
237
316
  try {
238
- const { pricing_source, ...generationArgs } = quote.args;
239
- result = await this.client.call(`generate_${kind}`, { ...generationArgs, client_request_id: quote.client_request_id });
317
+ result = await this.client.call(`generate_${kind}`, request);
240
318
  requireThat(typeof result.task_id === 'string' && result.task_id.length > 0, 'outcome_unknown', 'The submission returned no task ID. Recover with the original quote.');
241
319
  } catch (e) {
242
320
  // Acceptance survives later read/format failures; recovery must query this ID, never POST again.
@@ -259,9 +337,42 @@ export class Media {
259
337
  quote.state = 'submitted';
260
338
  quote.task_id = result.task_id;
261
339
  await this.state.write('quotes', id, quote);
262
- return { ...result, quote_id: id, client_request_id: quote.client_request_id };
340
+ return withExpiry({ ...result, quote_id: id, client_request_id: quote.client_request_id }, expired && quote);
263
341
  });
264
342
  }
343
+ /**
344
+ * Submits a batch quote's inputs in one shared-core call and records each input's outcome. The same request ID and
345
+ * inputs (tasks resume) later return accepted inputs without a new charge and submit only those still to finish.
346
+ */
347
+ async submitBatch(kind, id, quote, request, { resume, previous, expired }) {
348
+ let result, failure;
349
+ try { result = await this.client.call(`generate_${kind}`, request); } catch (error) { failure = error; }
350
+ const outcome = result ?? failure?.details ?? {};
351
+ const items = Array.isArray(outcome.items) ? outcome.items : undefined;
352
+ // Refused before any input was sent, so this call charged nothing; inputs accepted earlier keep their tasks.
353
+ const refusedBefore = !items && failure?.details?.charged === 'no' && ['not_submitted', 'rejected'].includes(failure.details.submission_state);
354
+ if (items) {
355
+ quote.items = items.map(item => ({ index: item.index, client_request_id: item.client_request_id, submission_state: item.submission_state,
356
+ ...(typeof item.task_id === 'string' ? { task_id: item.task_id } : {}), ...(typeof item.finishable === 'boolean' ? { finishable: item.finishable } : {}) }));
357
+ quote.task_ids = items.flatMap(item => item.submission_state === 'accepted' && typeof item.task_id === 'string' ? [item.task_id] : []);
358
+ // partial: the same request ID can still finish or verify some input. Refusals it would only get again close
359
+ // the batch: submitted when some input was accepted, refused when none was.
360
+ quote.state = quote.task_ids.length === quote.args.inputs.length ? 'submitted'
361
+ : items.some(item => item.submission_state === 'outcome_unknown' || item.finishable) ? 'partial' : quote.task_ids.length ? 'submitted' : 'refused';
362
+ } else quote.state = refusedBefore ? (resume ? (previous === 'partial' ? 'partial' : 'outcome_unknown') : 'refused') : 'outcome_unknown';
363
+ await this.state.write('quotes', id, quote);
364
+ const taskIds = quote.task_ids ?? [];
365
+ const view = { ...outcome, quote_id: id, client_request_id: quote.client_request_id, task_ids: taskIds, text: cliBatchText(outcome.text, id, taskIds),
366
+ ...(taskIds.length ? { collect: `evolink tasks batch --ids ${taskIds.join(',')}` } : {}),
367
+ ...(RECOVERABLE.includes(quote.state) ? { recovery: `evolink tasks resume --quote ${id}` } : {}) };
368
+ if (result) return withExpiry(view, expired && quote);
369
+ if (items) throw new CliError(failure.code || 'batch_not_submitted', failure.message, view, failure.exitCode);
370
+ throw new CliError(resume && !refusedBefore ? 'outcome_unknown' : failure.code || 'outcome_unknown', resume && !refusedBefore
371
+ ? '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, {
372
+ ...view, ...(quote.state === 'outcome_unknown' ? { charged: 'unknown', submission_state: 'outcome_unknown' } : {}),
373
+ ...(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.' } : {}),
374
+ }, failure.exitCode);
375
+ }
265
376
  async resume(id) {
266
377
  const quote = await this.load(id);
267
378
  return this.generate(quote.type, id, { resume: true });
@@ -41,12 +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
- if (['gpt-image-2', 'gpt-image-2.5-flare', 'gpt-image-2.5-sunburst', 'gpt-image-2-beta'].includes(model.model)) {
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'] }];
49
+ model.params.duration = { ...model.params.duration, anyOf };
50
+ const properties = model.inputSchema?.schema.properties;
51
+ if (properties)
52
+ properties.duration = { anyOf, description: model.params.duration.description, default: model.params.duration.default };
53
+ }
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)) {
45
55
  model.constraints = { ...model.constraints, imageSize: {
46
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'],
47
57
  allowPixels: model.model !== 'gpt-image-2-beta', step: 16, minEdge: 16, maxEdge: 3840,
48
58
  minPixels: 655360, maxPixels: 8294400, maxRatio: 3,
49
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 } } : {}),
50
62
  } };
51
63
  const properties = model.inputSchema?.schema.properties;
52
64
  if (properties)