@evolinkai/cli 0.13.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 (28) hide show
  1. package/README.md +20 -6
  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 +142 -37
  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 +245 -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 +266 -67
  21. package/src/platform/core/src/tool-guidance.js +25 -2
  22. package/src/platform/core/src/tools/estimate-cost.js +201 -60
  23. package/src/platform/core/src/tools/generate.js +497 -75
  24. package/src/platform/core/src/tools/get-model.js +15 -3
  25. package/src/platform/core/src/tools/get-pricing-rules.js +4 -3
  26. package/src/platform/core/src/tools/shared.js +1 -1
  27. package/src/platform/core/src/version.js +1 -1
  28. package/src/platform/source.json +41 -35
@@ -2,15 +2,17 @@
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
4
  import { submitTask } from '../services/api-client.js';
5
+ import { BATCH_REQUEST_ID_MAX, BATCH_SUBMIT_CONCURRENCY, MAX_BATCH_ITEMS, batchTotal, checkBatchApproval, keptRefusal, keyConflict, refusedBeforeRunning, submitBatch } from '../services/batch-generation.js';
5
6
  import { resolveModel, suggestModels } from '../services/model-catalog.js';
6
7
  import { formatIssues, validateInput } from '../services/param-validator.js';
7
8
  import { formatEstimateRange } from '../services/pricing-client.js';
8
9
  import { ApprovedAccountQuote, QuoteParameters, QuoteError } from '../services/pricing-quote-client.js';
9
- import { ApprovedRulesEstimate, createRulesEstimate, checkRulesApproval, rulesBudgetExceeded } from '../services/pricing-rules-estimate.js';
10
+ import { ApprovedRulesEstimate, REFERENCE_BUDGET_FACTOR, amountsForUC, calculateRulesEstimate, createRulesEstimate, checkRulesApproval, readPricingRulesFor, referenceAllowance, referenceBudgetExceeded, rulesBudgetExceeded } from '../services/pricing-rules-estimate.js';
10
11
  import { PricingRulesError } from '../services/pricing-rules-client.js';
12
+ import { isOmniTokenModel } from '../services/omni-tokens.js';
11
13
  import { CLIENT_REQUEST_ID_PATTERN, monotonicNow, newRunId, remainingMs } from '../services/http-policy.js';
12
14
  import { formatUsd } from '../services/error-handler.js';
13
- import { MEDIA_SECONDS_DESCRIPTION, MEDIA_SECONDS_MAX, PAID, errorResult, failure, money, ok, progressReporter, retryText, usdOf } from './shared.js';
15
+ import { DASHBOARD_CHECK_GUIDANCE, MEDIA_SECONDS_DESCRIPTION, MEDIA_SECONDS_MAX, PAID, dashboardCheck, errorResult, failure, money, ok, progressReporter, retryText, usdOf } from './shared.js';
14
16
  import { RESULT_DELIVERY_GUIDANCE, TERMINAL_STATUSES, describeTask, waitForTask } from './task-format.js';
15
17
  import { PAID_GENERATION_GUIDANCE } from '../tool-guidance.js';
16
18
  import { currentRequestCredentials } from '../request-context.js';
@@ -22,15 +24,17 @@ const PATHS = {
22
24
  };
23
25
  /** Images usually finish in seconds, so the tool waits for them; video and audio return the task at once. */
24
26
  const WAIT_MS = { image: 40_000, video: 0, audio: 0 };
27
+ /** The longest post-submit wait wait_seconds may ask for, so the call stays within clients' tool-call limits. */
28
+ const MAX_WAIT_SECONDS = 40;
25
29
  const DESCRIPTIONS = {
26
30
  image: 'Generate or edit images with an EvoLink image model. PAID: charges the user\'s EvoLink balance.',
27
31
  video: 'Generate a video with an EvoLink video model (text-to-video, image-to-video, reference, edit, extend). PAID: charges the user\'s EvoLink balance.',
28
32
  audio: 'Generate music, songs or speech with an EvoLink audio model. PAID: charges the user\'s EvoLink balance.',
29
33
  };
30
34
  const AFTER = {
31
- image: 'Waits up to 40 s and returns the image links when ready; otherwise returns the task_id for get_task.',
32
- video: 'Returns a task_id at once (videos take minutes); then call get_task, which can wait up to 45 s per call.',
33
- audio: 'Returns a task_id at once; then call get_task, which can wait up to 45 s per call.',
35
+ image: 'Waits up to 40 s (wait_seconds) and returns the image links when ready; otherwise returns the task_id for get_task.',
36
+ video: 'Returns a task_id at once (videos take minutes) unless wait_seconds is set; then call get_task (each call waits up to 45 s).',
37
+ audio: 'Returns a task_id at once unless wait_seconds is set; then call get_task (each call waits up to 45 s).',
34
38
  };
35
39
  function description(kind) {
36
40
  return [
@@ -45,9 +49,73 @@ function description(kind) {
45
49
  }
46
50
  /** Longest prompt accepted through the prompt shortcut. */
47
51
  const PROMPT_SHORTCUT_MAX = 20_000;
52
+ function inputSchema(kind) {
53
+ return {
54
+ model: z.string().min(1).max(128).describe(`${kind[0].toUpperCase()}${kind.slice(1)} model ID from search_models.`),
55
+ // The cap is checked in the handler: a schema limit makes the SDK answer with a bare validation error.
56
+ prompt: z.string().optional().describe(`Shortcut for input.prompt; up to ${PROMPT_SHORTCUT_MAX.toLocaleString('en-US')} characters (get_model lists the model's own limit).`),
57
+ input: z.record(z.string(), z.unknown()).optional()
58
+ .describe('Model parameters exactly as listed by get_model, e.g. {"prompt":"…","quality":"1080p"}. Do not put model or callback_url here.'),
59
+ // The leading max() lets zod stop at an oversized array instead of checking every element.
60
+ inputs: z.array(z.record(z.string(), z.unknown())).max(MAX_BATCH_ITEMS).min(1).optional()
61
+ .describe(`Several tasks of this model at once (1–${MAX_BATCH_ITEMS}), each item like input. One pricing_quote from estimate_cost with the same inputs, in the same order, approves the whole batch; every item is submitted right away (up to ${BATCH_SUBMIT_CONCURRENCY} at a time) and the result lists each item's task_id or error. Collect the results with list_tasks (task_ids). To finish a batch, call again with the same client_request_id and exactly the same inputs within 24 hours: the items the result lists to finish (not submitted, or refused and since fixed) are then submitted, and accepted items return their original tasks without a new charge. Never resubmit accepted, not-submitted or unknown-outcome items under a new client_request_id: that creates and charges new tasks. media_seconds and pricing_parameters apply to every item. Pass input or inputs, not both.`),
62
+ client_request_id: z.string().regex(CLIENT_REQUEST_ID_PATTERN).optional()
63
+ .describe(`Optional idempotency key (16–96 characters: letters, digits, . _ -; with inputs at most ${BATCH_REQUEST_ID_MAX}, since each item adds .NN). Reuse the same value only to retry the same request after a network error or timeout, or to finish a batch with exactly the same inputs.`),
64
+ max_cost_usd: z.number().positive().max(10_000).optional()
65
+ .describe(`Compatibility option for a budget explicitly specified by the user. Compare the submission estimate against that budget; never derive this value from the estimate. This does not limit the final charge. Refuses when the estimate is incomplete or exceeds the budget; a token-billed reference price must fit ${REFERENCE_BUDGET_FACTOR} times over. With inputs it applies to the batch total.`),
66
+ account_quote: ApprovedAccountQuote.optional().describe('Legacy approval. Refresh with estimate_cost and obtain user approval before using the new pricing rules.'),
67
+ pricing_quote: ApprovedRulesEstimate.optional().describe('Client approval record from estimate_cost, for exactly this input (or these inputs). Rechecked against fresh pricing rules before submission; past its expires_at it still applies while the input and price are unchanged. Does not bind final settlement.'),
68
+ pricing_parameters: QuoteParameters.optional().describe('The same explicit billing usage passed to estimate_cost.'),
69
+ media_seconds: z.number().positive().max(MEDIA_SECONDS_MAX).optional().describe(MEDIA_SECONDS_DESCRIPTION),
70
+ wait_seconds: z.number().int().min(0).max(MAX_WAIT_SECONDS).optional()
71
+ .describe(`Seconds to wait for the result after submitting, 0–${MAX_WAIT_SECONDS} (default ${WAIT_MS[kind] / 1000}; with inputs only 0). 0 returns the task_id right after submission: use it when submitting several tasks, then collect them with list_tasks.`),
72
+ skip_estimate: z.boolean().optional().describe('Only when the user has explicitly said not to estimate or not to confirm (for example "generate directly", "no need to estimate", "from now on just generate"); never on your own initiative. Submits without an approved estimate, also when the price cannot be computed or a pricing_quote changed, and says so in the result; the task is charged by actual usage. Invalid input and an explicit max_cost_usd are still checked.'),
73
+ };
74
+ }
75
+ const argsSchema = (kind) => z.object(inputSchema(kind));
76
+ /** What lowers a reference price: GPT Image's output settings, or a Gemini Omni video's resolution, length and media. */
77
+ const lowerReference = (model) => isOmniTokenModel(model) ? 'quality, duration, images or input videos' : 'size, quality, count or reference images';
48
78
  function rangeText(estimate) {
49
79
  return formatEstimateRange(estimate) ?? 'unknown';
50
80
  }
81
+ /**
82
+ * Why the price could not be computed, when skip_estimate may set that aside: rules that are missing, unreadable or
83
+ * limited, or usage known only once the task runs. Input problems and a cancelled call are never set aside.
84
+ */
85
+ function unpriced(error) {
86
+ if (error instanceof PricingRulesError) {
87
+ if (error.code === 'interrupted')
88
+ return undefined;
89
+ if (error.code === 'rate_limit_exceeded')
90
+ return { reason: 'rules_rate_limited', why: 'the platform was limiting pricing requests, so the price was not checked' };
91
+ if (error.code === 'not_found')
92
+ return { reason: 'no_published_rule', why: 'no published price is available for this model' };
93
+ return { reason: 'rules_unavailable', why: 'the pricing rules could not be read, so the price was not checked' };
94
+ }
95
+ if (!(error instanceof QuoteError))
96
+ return undefined;
97
+ if (error.code === 'pricing_rules_unavailable')
98
+ return { reason: 'no_published_rule', why: 'no published price is available for this model and input' };
99
+ if (error.code === 'quote_usage_required')
100
+ return { reason: 'needs_input', why: `no total can be estimated before the task runs (it depends on ${error.param ?? 'usage measured when it runs'})` };
101
+ if (error.code === 'search_pricing_unavailable')
102
+ return { reason: 'search_price_unverified', why: 'the unit price of the enabled search could not be verified' };
103
+ if (error.code === 'invalid_pricing_expression')
104
+ return { reason: 'rules_unavailable', why: 'the published pricing rules could not be evaluated' };
105
+ return undefined;
106
+ }
107
+ /**
108
+ * A pricing_quote that no longer matches, set aside by skip_estimate: the result names the approved and the current
109
+ * price (`now`, undefined when no total can be computed before the task runs).
110
+ */
111
+ function changedApproval(error, approval, now, batch = false) {
112
+ if (error.code === 'quote_input_changed') {
113
+ return { reason: 'quote_input_changed', why: batch ? `the pricing_quote was for different inputs${now ? `; the estimate of these inputs is ${now}` : ''}`
114
+ : `the pricing_quote was for a different input${now ? `; this input's estimate is ${now}` : ''}` };
115
+ }
116
+ return { reason: 'price_changed', why: `the price changed after it was approved (approved ${money(Number(amountsForUC(approval.total_uc).credits))}, now ${now ?? 'not computable before the task runs'})`,
117
+ approved: approval.total_uc };
118
+ }
51
119
  /** Why max_cost_usd could not be checked, and what the assistant can do next. */
52
120
  function uncheckedCap(estimate, pricingWarning) {
53
121
  if (estimate.uncheckable_reason === 'usage')
@@ -77,6 +145,36 @@ function uncheckedCap(estimate, pricingWarning) {
77
145
  const note = estimate.notes[0] ?? pricingWarning ?? 'no price could be found for it';
78
146
  return [note.replace(/[.\s]+$/, ''), 'Ask the user whether to proceed without a cap.'];
79
147
  }
148
+ /** The catalog entry of a generate tool's model, or the refusal to return. */
149
+ async function generationModel(config, kind, model) {
150
+ const { catalog, entry } = await resolveModel(model, config, { fresh: true, allowStale: false, skipPricing: true });
151
+ if (!entry) {
152
+ const suggestions = suggestModels(catalog, model, kind);
153
+ return { refused: failure(`Unknown ${kind} model "${model}".${suggestions.length ? ` Did you mean: ${suggestions.join(', ')}?` : ''} Use search_models to find model IDs. Nothing was submitted or charged.`, { error: { category: 'not_found', param: 'model' }, suggestions, charged: 'no' }) };
154
+ }
155
+ if (entry.kind !== kind) {
156
+ return { refused: failure(`${entry.id} is ${entry.kind === 'video' ? 'a' : 'an'} ${entry.kind} model; use generate_${entry.kind}. Nothing was submitted or charged.`, {
157
+ error: { category: 'invalid_request', param: 'model' },
158
+ use_tool: `generate_${entry.kind}`,
159
+ charged: 'no',
160
+ }) };
161
+ }
162
+ return { catalog, entry };
163
+ }
164
+ /** An input as generate_* submits it, with the problems that stop it and the warnings it carries. */
165
+ function checkGenerationInput(entry, input) {
166
+ const prepared = prepareSeedanceInput(entry, input);
167
+ const errors = [], warnings = [];
168
+ if (entry.spec) {
169
+ const validation = validateInput(entry.spec, prepared.input);
170
+ errors.push(...validation.errors, ...prepared.errors);
171
+ warnings.push(...[...validation.warnings, ...prepared.warnings].map(issue => `${issue.param} ${issue.problem}`));
172
+ }
173
+ else {
174
+ warnings.push('This model\'s parameters are not documented here, so the input was not checked before sending.');
175
+ }
176
+ return { prepared, effectiveInput: prepared.input, errors, warnings };
177
+ }
80
178
  export function registerGenerateTools(server, config) {
81
179
  for (const kind of ['image', 'video', 'audio'])
82
180
  registerGenerate(server, config, kind);
@@ -87,21 +185,7 @@ function registerGenerate(server, config, kind) {
87
185
  server.registerTool(name, {
88
186
  title,
89
187
  description: description(kind),
90
- inputSchema: {
91
- model: z.string().min(1).max(128).describe(`${kind[0].toUpperCase()}${kind.slice(1)} model ID from search_models.`),
92
- // The cap is checked in the handler: a schema limit makes the SDK answer with a bare validation error.
93
- prompt: z.string().optional().describe(`Shortcut for input.prompt; up to ${PROMPT_SHORTCUT_MAX.toLocaleString('en-US')} characters (get_model lists the model's own limit).`),
94
- input: z.record(z.string(), z.unknown()).optional()
95
- .describe('Model parameters exactly as listed by get_model, e.g. {"prompt":"…","quality":"1080p"}. Do not put model or callback_url here.'),
96
- client_request_id: z.string().regex(CLIENT_REQUEST_ID_PATTERN).optional()
97
- .describe('Optional idempotency key (16–96 characters: letters, digits, . _ -). Reuse the same value only to retry the same request after a network error or timeout.'),
98
- max_cost_usd: z.number().positive().max(10_000).optional()
99
- .describe('Compatibility option for a budget explicitly specified by the user. Compare the submission estimate against that budget; never derive this value from the estimate. This does not limit the final charge. Refuses when the estimate is incomplete or exceeds the budget.'),
100
- account_quote: ApprovedAccountQuote.optional().describe('Legacy approval. Refresh with estimate_cost and obtain user approval before using the new pricing rules.'),
101
- pricing_quote: ApprovedRulesEstimate.optional().describe('Client approval record from estimate_cost, for exactly this input. Rechecked against fresh pricing rules before submission; does not bind final settlement.'),
102
- pricing_parameters: QuoteParameters.optional().describe('The same explicit billing usage passed to estimate_cost.'),
103
- media_seconds: z.number().positive().max(MEDIA_SECONDS_MAX).optional().describe(MEDIA_SECONDS_DESCRIPTION),
104
- },
188
+ inputSchema: inputSchema(kind),
105
189
  annotations: { title, ...PAID },
106
190
  }, async (args, extra) => {
107
191
  const started = Date.now();
@@ -112,6 +196,8 @@ function registerGenerate(server, config, kind) {
112
196
  return failure(`${unavailable} Nothing was submitted or charged.`, {
113
197
  error: { category: 'unauthorized' }, charged: 'no',
114
198
  });
199
+ if (args.inputs !== undefined)
200
+ return generateBatch(config, kind, args, extra, startedMono);
115
201
  const input = { ...(args.input ?? {}) };
116
202
  if (args.prompt !== undefined) {
117
203
  if (input.prompt !== undefined && input.prompt !== args.prompt) {
@@ -131,47 +217,58 @@ function registerGenerate(server, config, kind) {
131
217
  let clientRequestId;
132
218
  let acceptedTaskId;
133
219
  try {
134
- const { catalog, entry } = await resolveModel(args.model, config, { fresh: true, allowStale: false, skipPricing: true });
135
- if (!entry) {
136
- const suggestions = suggestModels(catalog, args.model, kind);
137
- return failure(`Unknown ${kind} model "${args.model}".${suggestions.length ? ` Did you mean: ${suggestions.join(', ')}?` : ''} Use search_models to find model IDs. Nothing was submitted or charged.`, { error: { category: 'not_found', param: 'model' }, suggestions, charged: 'no' });
220
+ const resolved = await generationModel(config, kind, args.model);
221
+ if ('refused' in resolved)
222
+ return resolved.refused;
223
+ const { catalog, entry } = resolved;
224
+ const { prepared, effectiveInput, errors, warnings } = checkGenerationInput(entry, input);
225
+ if (errors.length > 0) {
226
+ return failure([
227
+ `The input for ${entry.id} has problems; nothing was submitted or charged:`,
228
+ ...formatIssues(errors),
229
+ 'get_model lists every parameter with its allowed values.',
230
+ ].join('\n'), { error: { category: 'invalid_request' }, problems: errors, charged: 'no' });
138
231
  }
139
- if (entry.kind !== kind) {
140
- return failure(`${entry.id} is ${entry.kind === 'video' ? 'a' : 'an'} ${entry.kind} model; use generate_${entry.kind}. Nothing was submitted or charged.`, {
141
- error: { category: 'invalid_request', param: 'model' },
142
- use_tool: `generate_${entry.kind}`,
143
- charged: 'no',
144
- });
232
+ // media_seconds only prices the request; the body below is built from input alone.
233
+ const skip = args.skip_estimate === true;
234
+ if (args.account_quote && !skip)
235
+ throw new QuoteError('quote_refresh_required', 'Refresh the legacy account estimate with estimate_cost and obtain user approval.');
236
+ let rulesEstimate;
237
+ let skipped;
238
+ try {
239
+ rulesEstimate = await createRulesEstimate(entry, effectiveInput, { mediaSeconds: args.media_seconds, pricingParameters: args.pricing_parameters,
240
+ purpose: 'generation', signal: extra.signal });
145
241
  }
146
- const prepared = prepareSeedanceInput(entry, input);
147
- const effectiveInput = prepared.input;
148
- const warnings = [];
149
- if (entry.spec) {
150
- const validation = validateInput(entry.spec, effectiveInput);
151
- validation.errors.push(...prepared.errors);
152
- validation.warnings.push(...prepared.warnings);
153
- if (validation.errors.length > 0) {
154
- return failure([
155
- `The input for ${entry.id} has problems; nothing was submitted or charged:`,
156
- ...formatIssues(validation.errors),
157
- 'get_model lists every parameter with its allowed values.',
158
- ].join('\n'), { error: { category: 'invalid_request' }, problems: validation.errors, charged: 'no' });
159
- }
160
- warnings.push(...validation.warnings.map(issue => `${issue.param} ${issue.problem}`));
242
+ catch (error) {
243
+ // The user asked to generate without an estimate: a price that cannot be computed no longer stops it.
244
+ skipped = skip && !extra.signal.aborted ? unpriced(error) : undefined;
245
+ if (!skipped)
246
+ throw error;
161
247
  }
162
- else {
163
- warnings.push('This model\'s parameters are not documented here, so the input was not checked before sending.');
248
+ let approvalExpired = false;
249
+ if (args.pricing_quote && rulesEstimate) {
250
+ try {
251
+ approvalExpired = checkRulesApproval(args.pricing_quote, rulesEstimate).expired;
252
+ }
253
+ catch (error) {
254
+ if (!skip || !(error instanceof QuoteError))
255
+ throw error;
256
+ skipped = changedApproval(error, args.pricing_quote, rulesEstimate.estimate.status === 'needs_input' ? undefined : money(Number(rulesEstimate.amounts.credits)));
257
+ }
164
258
  }
165
- // media_seconds only prices the request; the body below is built from input alone.
166
- if (args.account_quote)
167
- throw new QuoteError('quote_refresh_required', 'Refresh the legacy account estimate with estimate_cost and obtain user approval.');
168
- const rulesEstimate = await createRulesEstimate(entry, effectiveInput, { mediaSeconds: args.media_seconds, pricingParameters: args.pricing_parameters,
169
- purpose: 'generation', signal: extra.signal });
170
- if (args.pricing_quote)
171
- checkRulesApproval(args.pricing_quote, rulesEstimate);
172
- const estimate = rulesEstimate.estimate;
259
+ const estimate = rulesEstimate?.estimate;
260
+ // A reference price is settled at actual token usage, so a budget must leave room above it.
261
+ const reference = estimate?.status === 'token_billed' && estimate.max_usd !== undefined && estimate.uncheckable_reason === undefined;
262
+ const allowance = reference && rulesEstimate ? referenceAllowance(rulesEstimate.amounts.uc) : undefined;
173
263
  if (args.max_cost_usd !== undefined) {
174
- if (estimate.uncheckable_reason !== undefined || estimate.status !== 'estimated' || estimate.max_usd === undefined) {
264
+ // skip_estimate sets aside the estimate, never the user's own budget.
265
+ if (!rulesEstimate || !estimate) {
266
+ return failure(`max_cost_usd cannot be checked for ${entry.id}: ${skipped?.why ?? 'no price could be computed'}. Nothing was submitted or charged. skip_estimate does not set aside the user's budget: ask the user whether to proceed without the cap.`, {
267
+ error: { category: 'invalid_request', param: 'max_cost_usd' },
268
+ charged: 'no',
269
+ });
270
+ }
271
+ if (!reference && (estimate.uncheckable_reason !== undefined || estimate.status !== 'estimated' || estimate.max_usd === undefined)) {
175
272
  const [reason, next] = uncheckedCap(estimate, catalog.pricingWarning);
176
273
  return failure(`max_cost_usd cannot be checked for ${entry.id}: ${reason}. Nothing was submitted or charged. ${next}`, {
177
274
  error: { category: 'invalid_request', param: 'max_cost_usd' },
@@ -179,7 +276,14 @@ function registerGenerate(server, config, kind) {
179
276
  charged: 'no',
180
277
  });
181
278
  }
182
- if (rulesBudgetExceeded(rulesEstimate.amounts.uc, args.max_cost_usd)) {
279
+ if (allowance && referenceBudgetExceeded(rulesEstimate.amounts.uc, args.max_cost_usd)) {
280
+ return failure(`The reference price ${rangeText(estimate)} is billed by actual token usage, and ${REFERENCE_BUDGET_FACTOR} times it ($${allowance.usd}, ${allowance.credits} credits) is above max_cost_usd $${args.max_cost_usd}. Nothing was submitted or charged. Lower the ${lowerReference(entry.id)}, or ask the user to raise the cap.`, {
281
+ error: { category: 'invalid_request', param: 'max_cost_usd' },
282
+ estimate, budget_check: { factor: REFERENCE_BUDGET_FACTOR, amounts: allowance },
283
+ charged: 'no',
284
+ });
285
+ }
286
+ if (!allowance && rulesBudgetExceeded(rulesEstimate.amounts.uc, args.max_cost_usd)) {
183
287
  return failure(`The estimated cost ${rangeText(estimate)} is above max_cost_usd $${formatUsd(args.max_cost_usd)}. Nothing was submitted or charged. Lower the duration, count or quality, or ask the user to raise the cap.`, {
184
288
  error: { category: 'invalid_request', param: 'max_cost_usd' },
185
289
  estimate,
@@ -187,14 +291,19 @@ function registerGenerate(server, config, kind) {
187
291
  });
188
292
  }
189
293
  }
190
- if (estimate.status === 'needs_input') {
191
- return failure([`No total can be estimated for ${entry.id} yet, so nothing was submitted or charged. The total depends on:`,
192
- ...(estimate.usage_help ?? []).map(line => `- ${line}`),
193
- 'Estimate again with this usage and get the user\'s approval before generating.'].join('\n'), {
194
- error: { category: 'estimate_unavailable', code: 'quote_usage_required' },
195
- missing_usage: estimate.missing_usage, usage_help: estimate.usage_help, charged: 'no', submission_state: 'not_submitted'
196
- });
294
+ if (estimate?.status === 'needs_input') {
295
+ if (!skip) {
296
+ return failure([`No total can be estimated for ${entry.id} yet, so nothing was submitted or charged. The total depends on:`,
297
+ ...(estimate.usage_help ?? []).map(line => `- ${line}`),
298
+ 'Estimate again with this usage and get the user\'s approval before generating.'].join('\n'), {
299
+ error: { category: 'estimate_unavailable', code: 'quote_usage_required' },
300
+ missing_usage: estimate.missing_usage, usage_help: estimate.usage_help, charged: 'no', submission_state: 'not_submitted'
301
+ });
302
+ }
303
+ skipped ??= { reason: 'needs_input', why: `no total can be estimated before the task runs (it depends on ${estimate.missing_usage?.join(', ') ?? 'usage measured when it runs'})` };
197
304
  }
305
+ // An approved pricing_quote that still matches means nothing was skipped.
306
+ const estimateSkipped = skip && !(args.pricing_quote && rulesEstimate && !skipped);
198
307
  clientRequestId = args.client_request_id ?? newRunId();
199
308
  const body = { ...effectiveInput, model: entry.id };
200
309
  const submitted = await submitTask(config, {
@@ -207,9 +316,10 @@ function registerGenerate(server, config, kind) {
207
316
  let task = submitted;
208
317
  let statusCheck = 'not_requested';
209
318
  // The post-submit wait has its own deadline; it never bounds or interrupts the paid submission above.
210
- const waitUntil = startedMono + WAIT_MS[kind];
211
- if ((!task.status || !TERMINAL_STATUSES.has(task.status)) && WAIT_MS[kind] > 0 && remainingMs(waitUntil) > 3_000) {
212
- const report = progressReporter(extra, WAIT_MS[kind] / 1000);
319
+ const waitMs = args.wait_seconds !== undefined ? args.wait_seconds * 1000 : WAIT_MS[kind];
320
+ const waitUntil = startedMono + waitMs;
321
+ if ((!task.status || !TERMINAL_STATUSES.has(task.status)) && waitMs > 0 && remainingMs(waitUntil) > 3_000) {
322
+ const report = progressReporter(extra, waitMs / 1000);
213
323
  try {
214
324
  const waited = await waitForTask(config, submitted.id, {
215
325
  deadline: waitUntil,
@@ -236,15 +346,31 @@ function registerGenerate(server, config, kind) {
236
346
  if (typeof reserved === 'number' && reserved > 0 && !lines.some(line => line.startsWith('Reserved:')) && task.status !== 'completed') {
237
347
  lines.push(`Reserved: ${money(reserved)}`);
238
348
  }
239
- if (estimate.status === 'estimated')
349
+ if (estimateSkipped) {
350
+ if (!skipped)
351
+ lines.push('Submitted at the user\'s request without an approved estimate (skip_estimate).');
352
+ else if (skipped.reason === 'price_changed' || skipped.reason === 'quote_input_changed')
353
+ lines.push(`Submitted at the user's request (skip_estimate) although ${skipped.why}.`);
354
+ else
355
+ lines.push(`Price check skipped at the user's request (skip_estimate): ${skipped.why}. The task is charged by actual usage.`);
356
+ if (!(typeof reserved === 'number' && reserved > 0) && task.status !== 'completed')
357
+ lines.push('get_task shows the charge when the task finishes.');
358
+ }
359
+ if (approvalExpired)
360
+ lines.push(`The approved estimate expired at ${args.pricing_quote.expires_at}, but the input and price are unchanged, so it was submitted under that approval.`);
361
+ if (estimate?.status === 'estimated')
240
362
  lines.push(`Estimate before submitting: ${rangeText(estimate)}`);
241
- if (estimate.search_charges?.length && estimate.status === 'estimated') {
363
+ if (reference && estimate)
364
+ lines.push(`Reference price before submitting: ${rangeText(estimate)}. Billed by actual token usage; the final charge is settled when the task finishes.`);
365
+ if (allowance && args.max_cost_usd !== undefined)
366
+ lines.push(`max_cost_usd $${args.max_cost_usd} covers ${REFERENCE_BUDGET_FACTOR} times the reference price ($${allowance.usd}, ${allowance.credits} credits). This was checked before submitting; it does not limit the final charge.`);
367
+ if (estimate?.search_charges?.length && estimate.status === 'estimated') {
242
368
  for (const note of estimate.notes.filter(note => /^(Web|Image) search is enabled\./.test(note)))
243
369
  lines.push(`Note: ${note}`);
244
370
  }
245
371
  for (const applied of prepared.defaults)
246
372
  lines.push(`Applied default: ${applied.param}=${applied.value} (${applied.reason}).`);
247
- if (estimate.status === 'partial') {
373
+ if (estimate?.status === 'partial') {
248
374
  lines.push(`Partial estimate at published rates: ${rangeText(estimate)} (not a total or an upper bound).`);
249
375
  for (const extra of estimate.possible_extras)
250
376
  lines.push(`May also charge: ${extra}`);
@@ -258,19 +384,25 @@ function registerGenerate(server, config, kind) {
258
384
  ...view.structured,
259
385
  submitted: { model: entry.id, input: effectiveInput },
260
386
  ...(prepared.applies ? { effective_input: effectiveInput, defaults_applied: prepared.defaults,
261
- usage_assumptions: estimate.notes.filter(note => note.startsWith('Web search is enabled.')) } : {}),
387
+ usage_assumptions: (estimate?.notes ?? []).filter(note => note.startsWith('Web search is enabled.')) } : {}),
262
388
  pricing_scope: 'public_default',
263
389
  pricing_source: 'pricing_rules',
264
- amounts: rulesEstimate.amounts,
390
+ ...(rulesEstimate && estimate?.status !== 'needs_input' ? { amounts: rulesEstimate.amounts } : {}),
265
391
  final_budget_enforced: false,
266
- ...(estimate.search_charges?.length ? { search_charges: estimate.search_charges, estimate,
392
+ ...(estimate?.search_charges?.length ? { search_charges: estimate.search_charges, estimate,
267
393
  amount_scope: estimate.status === 'partial' ? 'known_components_subtotal' : 'expected_usage_estimate' } : {}),
268
394
  client_request_id: clientRequestId,
269
395
  submission_state: 'accepted',
270
396
  replayed: submitted.idempotency_replayed === true,
397
+ ...(approvalExpired ? { approval_expired: true } : {}),
398
+ ...(estimateSkipped ? { estimate_skipped: true, estimate_skip_reason: skipped?.reason ?? 'none' } : {}),
399
+ ...(skipped?.approved ? { approved_amounts: amountsForUC(skipped.approved) } : {}),
271
400
  ...(typeof reserved === 'number' ? { reserved_credits: reserved, reserved_usd: usdOf(reserved) } : {}),
272
- ...(estimate.status === 'estimated' && !estimate.search_charges?.length ? { estimate: { min_usd: estimate.min_usd, max_usd: estimate.max_usd } } : {}),
273
- ...(estimate.status === 'partial' ? { estimate } : {}),
401
+ ...(estimate?.status === 'estimated' && !estimate.search_charges?.length ? { estimate: { min_usd: estimate.min_usd, max_usd: estimate.max_usd } } : {}),
402
+ ...(estimate?.status === 'partial' ? { estimate } : {}),
403
+ ...(reference && estimate ? { estimate: { status: estimate.status, min_usd: estimate.min_usd, max_usd: estimate.max_usd, total_known: false,
404
+ reference_usage: estimate.reference_usage } } : {}),
405
+ ...(allowance && args.max_cost_usd !== undefined ? { budget_check: { factor: REFERENCE_BUDGET_FACTOR, amounts: allowance, max_cost_usd: args.max_cost_usd } } : {}),
274
406
  ...(warnings.length ? { warnings } : {}),
275
407
  }, view.resources);
276
408
  }
@@ -290,3 +422,293 @@ function registerGenerate(server, config, kind) {
290
422
  }
291
423
  });
292
424
  }
425
+ const itemList = (indexes) => indexes.map(index => `inputs[${index}]`).join(', ');
426
+ /**
427
+ * A batch item's outcome, classified like a single submission. An item that never started, or that the gateway rate
428
+ * limited on every attempt (it releases the key), is not submitted; a refusal that ran nothing is fixed and finished
429
+ * with the same client_request_id, unless the gateway keeps it for the key. An item whose key was used for a different
430
+ * input is refused: the same call would conflict again.
431
+ */
432
+ function itemReport(submission, cancelled) {
433
+ const index = submission.index, at = `inputs[${index}]`, base = { index, client_request_id: submission.requestId };
434
+ const task = submission.receipt;
435
+ if (task) {
436
+ const reserved = task.usage?.credits_reserved, replayed = task.idempotency_replayed === true;
437
+ const held = typeof reserved === 'number' && reserved > 0 ? reserved : undefined;
438
+ return { index, state: 'accepted', finishable: false, taskId: task.id, reserved: held, replayed,
439
+ line: `- ${at}: task ${task.id}, ${task.status ?? 'accepted'}${held ? `; reserved ${money(held)}` : ''}${replayed ? ' (submitted earlier with this client_request_id: the original task, no new charge)' : ''}`,
440
+ structured: { ...base, submission_state: 'accepted', task_id: task.id, ...(task.status ? { status: task.status } : {}), replayed,
441
+ ...(typeof reserved === 'number' ? { reserved_credits: reserved, reserved_usd: usdOf(reserved) } : {}) } };
442
+ }
443
+ if (!submission.started) {
444
+ return { index, state: 'not_submitted', finishable: true,
445
+ line: `- ${at}: not submitted (${cancelled ? 'the call was cancelled' : 'the batch ran out of time'}). Nothing was charged for it.`,
446
+ structured: { ...base, submission_state: 'not_submitted', charged: 'no', finishable: true, reason: cancelled ? 'cancelled' : 'deadline', retryable: true } };
447
+ }
448
+ const failed = errorResult(submission.error, { paid: true, clientRequestId: submission.requestId, phase: 'submit_started' })
449
+ .structuredContent;
450
+ const info = failed.error;
451
+ // Nothing ran either way, so nothing was charged; but the same key with this input conflicts every time.
452
+ const refused = refusedBeforeRunning(submission);
453
+ if (refused && keyConflict(submission)) {
454
+ return { index, state: 'rejected', finishable: false, conflict: true, error: info,
455
+ line: `- ${at}: refused (idempotency_conflict, HTTP 409): ${at} differs from what this client_request_id submitted earlier. Pass exactly the same inputs to finish the batch; a different input is a new task that needs a new estimate, approval and client_request_id. Nothing was charged for it.`,
456
+ structured: { ...base, submission_state: 'rejected', charged: 'no', finishable: false,
457
+ error: { category: 'idempotency_conflict', code: 'idempotency_conflict', status: 409,
458
+ message: `${at} differs from what this client_request_id submitted earlier.`, retryable: false } } };
459
+ }
460
+ const state = refused || failed.submission_state === 'not_submitted' ? 'not_submitted'
461
+ : failed.submission_state === 'rejected' ? 'rejected' : 'outcome_unknown';
462
+ const kept = state === 'rejected' && keptRefusal(info.code);
463
+ const finishable = state === 'not_submitted' || state === 'rejected' && !kept;
464
+ const label = `${info.category}${info.code ? `, ${info.code}` : ''}${info.status ? `, HTTP ${info.status}` : ''}`;
465
+ const verb = state === 'outcome_unknown' ? 'outcome unknown' : state === 'rejected' ? 'refused' : 'not submitted';
466
+ return { index, state, finishable, error: info,
467
+ line: `- ${at}: ${verb} (${label}): ${info.headline ?? info.message}${state === 'outcome_unknown' ? ' Whether a charge was made is unknown.' : ' Nothing was charged for it.'}${kept
468
+ ? ' The gateway keeps this refusal for this client_request_id for 24 hours: once it is fixed, submit this input separately, as a new task with a new estimate, approval and client_request_id.' : ''}`,
469
+ structured: { ...base, submission_state: state, charged: state === 'outcome_unknown' ? 'unknown' : 'no', ...(state === 'outcome_unknown' ? {} : { finishable }),
470
+ error: { category: info.category, ...(info.code ? { code: info.code } : {}), ...(info.status ? { status: info.status } : {}), message: info.message,
471
+ retryable: state === 'not_submitted' || (info.retryable && !kept), ...(info.retry_after_seconds !== undefined ? { retry_after_seconds: info.retry_after_seconds } : {}),
472
+ ...(info.request_id ? { request_id: info.request_id } : {}) } } };
473
+ }
474
+ /**
475
+ * Several inputs for one model: every input is checked first, the rules are read once, one batch approval (or
476
+ * skip_estimate) covers them all and max_cost_usd the total; then the items are submitted together (submitBatch).
477
+ */
478
+ async function generateBatch(config, kind, args, extra, startedMono) {
479
+ const name = `generate_${kind}`, inputs = args.inputs, count = inputs.length, batch = { items: count };
480
+ const refuse = (param, text) => failure(`${text} Nothing was submitted or charged.`, { error: { category: 'invalid_request', param }, charged: 'no', batch });
481
+ if (args.input !== undefined)
482
+ return refuse('inputs', 'Pass input for one task or inputs for a batch, not both.');
483
+ if (args.prompt !== undefined)
484
+ return refuse('prompt', 'The prompt shortcut is for one input; with inputs, put each prompt in its item.');
485
+ if (args.wait_seconds)
486
+ return refuse('wait_seconds', 'wait_seconds is not used with inputs: a batch returns as soon as its items are submitted; collect the results with list_tasks (task_ids).');
487
+ if (args.client_request_id !== undefined && args.client_request_id.length > BATCH_REQUEST_ID_MAX) {
488
+ return refuse('client_request_id', `With inputs, client_request_id has at most ${BATCH_REQUEST_ID_MAX} characters, since each item adds .NN to it.`);
489
+ }
490
+ let batchId;
491
+ try {
492
+ const resolved = await generationModel(config, kind, args.model);
493
+ if ('refused' in resolved)
494
+ return resolved.refused;
495
+ const { catalog, entry } = resolved;
496
+ const checked = inputs.map(item => checkGenerationInput(entry, item));
497
+ const problems = checked.flatMap((item, index) => item.errors.map(issue => ({ ...issue, param: `inputs[${index}].${issue.param}` })));
498
+ if (problems.length > 0) {
499
+ return failure([`Some inputs for ${entry.id} have problems; nothing was submitted or charged:`, ...formatIssues(problems),
500
+ 'get_model lists every parameter with its allowed values.'].join('\n'), { error: { category: 'invalid_request' }, problems, charged: 'no', batch });
501
+ }
502
+ const skipEstimate = args.skip_estimate === true;
503
+ if (args.account_quote && !skipEstimate)
504
+ throw new QuoteError('quote_refresh_required', 'Refresh the legacy account estimate with estimate_cost and obtain user approval.');
505
+ // One read of the rules prices every input. skip_estimate sets aside a price that cannot be computed, batch-wide
506
+ // (unreadable rules) or for single inputs; anything else stops the whole batch.
507
+ let batchSkipped;
508
+ const itemSkipped = inputs.map(() => undefined);
509
+ let rules;
510
+ try {
511
+ rules = (await readPricingRulesFor(entry, { purpose: 'generation', signal: extra.signal })).body;
512
+ }
513
+ catch (error) {
514
+ batchSkipped = skipEstimate && !extra.signal.aborted ? unpriced(error) : undefined;
515
+ if (!batchSkipped)
516
+ throw error;
517
+ }
518
+ const priced = rules ? checked.map((item, index) => {
519
+ try {
520
+ return calculateRulesEstimate(rules, entry, item.effectiveInput, { mediaSeconds: args.media_seconds, pricingParameters: args.pricing_parameters });
521
+ }
522
+ catch (error) {
523
+ itemSkipped[index] = skipEstimate ? unpriced(error) : undefined;
524
+ if (!itemSkipped[index])
525
+ throw error instanceof QuoteError ? new QuoteError(error.code, `inputs[${index}]: ${error.message}`, error.param) : error;
526
+ return undefined;
527
+ }
528
+ }) : [];
529
+ const estimates = rules && priced.every(item => item !== undefined) ? priced : undefined;
530
+ const total = estimates ? batchTotal(entry.id, estimates) : undefined;
531
+ let expiredApproval = false;
532
+ if (args.pricing_quote && total) {
533
+ try {
534
+ expiredApproval = checkBatchApproval(args.pricing_quote, total.approval).expired;
535
+ }
536
+ catch (error) {
537
+ if (!skipEstimate || !(error instanceof QuoteError))
538
+ throw error;
539
+ batchSkipped = changedApproval(error, args.pricing_quote, total.status === 'needs_input' ? undefined : money(Number(total.amounts.credits)), true);
540
+ }
541
+ }
542
+ // A batch reference price is settled at actual token usage, so a budget must leave room above it.
543
+ const tokenBilled = total !== undefined && estimates.every(item => item.estimate.status === 'token_billed' && item.estimate.max_usd !== undefined
544
+ && item.estimate.uncheckable_reason === undefined);
545
+ const budgetRoom = tokenBilled ? referenceAllowance(total.amounts.uc) : undefined;
546
+ if (args.max_cost_usd !== undefined) {
547
+ // skip_estimate sets aside the estimate, never the user's own budget.
548
+ if (!total || !estimates) {
549
+ const first = itemSkipped.findIndex(Boolean);
550
+ return failure(`max_cost_usd cannot be checked for ${batchSkipped || first < 0 ? '' : `inputs[${first}] of `}${entry.id}: ${batchSkipped?.why ?? itemSkipped[first]?.why ?? 'no price could be computed'}. Nothing was submitted or charged. skip_estimate does not set aside the user's budget: ask the user whether to proceed without the cap.`, {
551
+ error: { category: 'invalid_request', param: 'max_cost_usd' }, charged: 'no', batch
552
+ });
553
+ }
554
+ const open = tokenBilled ? -1 : estimates.findIndex(item => item.estimate.uncheckable_reason !== undefined || item.estimate.status !== 'estimated' || item.estimate.max_usd === undefined);
555
+ if (open >= 0) {
556
+ const [reason, next] = uncheckedCap(estimates[open].estimate, catalog.pricingWarning);
557
+ return failure(`max_cost_usd cannot be checked for inputs[${open}] of ${entry.id}: ${reason}. Nothing was submitted or charged. ${next}`, {
558
+ error: { category: 'invalid_request', param: 'max_cost_usd' }, estimate: total.estimate, charged: 'no', batch
559
+ });
560
+ }
561
+ if (budgetRoom && referenceBudgetExceeded(total.amounts.uc, args.max_cost_usd)) {
562
+ return failure(`The reference price of the batch, ${rangeText(total.estimate)}, is billed by actual token usage, and ${REFERENCE_BUDGET_FACTOR} times it ($${budgetRoom.usd}, ${budgetRoom.credits} credits) is above max_cost_usd $${args.max_cost_usd}. Nothing was submitted or charged. Use fewer inputs, or lower the ${lowerReference(entry.id)}, or ask the user to raise the cap.`, {
563
+ error: { category: 'invalid_request', param: 'max_cost_usd' }, estimate: total.estimate, budget_check: { factor: REFERENCE_BUDGET_FACTOR, amounts: budgetRoom }, charged: 'no', batch
564
+ });
565
+ }
566
+ if (!budgetRoom && rulesBudgetExceeded(total.amounts.uc, args.max_cost_usd)) {
567
+ return failure(`The estimated cost of the batch, ${rangeText(total.estimate)}, is above max_cost_usd $${formatUsd(args.max_cost_usd)}. Nothing was submitted or charged. Use fewer inputs, or lower the duration, count or quality, or ask the user to raise the cap.`, {
568
+ error: { category: 'invalid_request', param: 'max_cost_usd' }, estimate: total.estimate, charged: 'no', batch
569
+ });
570
+ }
571
+ }
572
+ if (total && total.needsInput.length > 0) {
573
+ if (!skipEstimate) {
574
+ return failure([`No total can be estimated for ${itemList(total.needsInput)} of ${entry.id} yet, so nothing was submitted or charged. The total depends on:`,
575
+ ...(total.estimate.usage_help ?? []).map(line => `- ${line}`),
576
+ 'Estimate again with this usage and get the user\'s approval before generating.'].join('\n'), {
577
+ error: { category: 'estimate_unavailable', code: 'quote_usage_required' }, missing_usage: total.estimate.missing_usage,
578
+ usage_help: total.estimate.usage_help, charged: 'no', submission_state: 'not_submitted', batch
579
+ });
580
+ }
581
+ for (const index of total.needsInput) {
582
+ itemSkipped[index] ??= { reason: 'needs_input', why: `no total can be estimated before the task runs (it depends on ${estimates[index].estimate.missing_usage?.join(', ') ?? 'usage measured when it runs'})` };
583
+ }
584
+ }
585
+ const someItemsSkipped = itemSkipped.some(Boolean);
586
+ // An approved batch pricing_quote that still matches means nothing was skipped.
587
+ const skippedBatch = skipEstimate && !(args.pricing_quote && total && !batchSkipped && !someItemsSkipped);
588
+ const skipReasons = batchSkipped ? batchSkipped.reason : someItemsSkipped
589
+ ? [...new Set(itemSkipped.flatMap(item => item ? [item.reason] : []))].sort().join(',') : 'none';
590
+ batchId = args.client_request_id ?? newRunId();
591
+ const token = extra._meta?.progressToken;
592
+ const submissions = await submitBatch(config, { path: entry.spec?.path ?? PATHS[kind], bodies: checked.map(item => ({ ...item.effectiveInput, model: entry.id })),
593
+ batchId, tool: name, startedMono, signal: extra.signal,
594
+ onSubmitted: done => {
595
+ if (token !== undefined)
596
+ void extra.sendNotification({ method: 'notifications/progress',
597
+ params: { progressToken: token, progress: done, total: count, message: `Submitted ${done} of ${count}` } }).catch(() => undefined);
598
+ } });
599
+ const reports = submissions.map(item => itemReport(item, extra.signal.aborted));
600
+ const accepted = reports.filter(report => report.state === 'accepted');
601
+ const tally = (state) => reports.filter(report => report.state === state).length;
602
+ // Only these can still be finished with this client_request_id; an unknown outcome is retried later or looked up.
603
+ const finishing = reports.filter(report => report.finishable).map(report => report.index);
604
+ const unknown = reports.filter(report => report.state === 'outcome_unknown').map(report => report.index);
605
+ const counts = { items: count, accepted: accepted.length, replayed: accepted.filter(report => report.replayed).length,
606
+ not_submitted: tally('not_submitted'), rejected: tally('rejected'), outcome_unknown: tally('outcome_unknown'), finishable: finishing.length };
607
+ const taskIds = accepted.map(report => report.taskId);
608
+ const heldCredits = accepted.reduce((sum, report) => sum + (report.reserved ?? 0), 0);
609
+ const lines = [`Submitted ${accepted.length} of ${count} input${count === 1 ? '' : 's'} to ${entry.id}.`];
610
+ if (counts.replayed)
611
+ lines.push(`${counts.replayed} of them had been submitted earlier with this client_request_id: the original task${counts.replayed === 1 ? ' was' : 's were'} returned without a new charge.`);
612
+ lines.push(...reports.map(report => report.line));
613
+ if (heldCredits > 0)
614
+ lines.push(`Reserved in total: ${money(heldCredits)} (each final charge is settled when its task finishes).`);
615
+ if (skippedBatch) {
616
+ if (!batchSkipped && !someItemsSkipped)
617
+ lines.push('Submitted at the user\'s request without an approved estimate (skip_estimate).');
618
+ else if (batchSkipped?.reason === 'price_changed' || batchSkipped?.reason === 'quote_input_changed')
619
+ lines.push(`Submitted at the user's request (skip_estimate) although ${batchSkipped.why}.`);
620
+ else if (batchSkipped)
621
+ lines.push(`Price check skipped at the user's request (skip_estimate): ${batchSkipped.why}. The tasks are charged by actual usage.`);
622
+ const whys = [...new Set(itemSkipped.flatMap(item => item ? [item.why] : []))];
623
+ for (const why of whys)
624
+ lines.push(`Price check skipped at the user's request (skip_estimate) for ${itemList(itemSkipped.flatMap((item, index) => item?.why === why ? [index] : []))}: ${why}. Charged by actual usage.`);
625
+ if (accepted.some(report => !report.reserved))
626
+ lines.push('list_tasks or get_task shows each charge when its task finishes.');
627
+ }
628
+ if (expiredApproval)
629
+ lines.push(`The approved estimate expired at ${args.pricing_quote.expires_at}, but the inputs and price are unchanged, so the batch was submitted under that approval.`);
630
+ if (total?.status === 'estimated')
631
+ lines.push(`Estimate before submitting: ${rangeText(total.estimate)} for ${count} input${count === 1 ? '' : 's'}.`);
632
+ if (tokenBilled && total)
633
+ lines.push(`Reference price before submitting: ${rangeText(total.estimate)} for ${count} input${count === 1 ? '' : 's'}. Billed by actual token usage; each final charge is settled when its task finishes.`);
634
+ if (budgetRoom && args.max_cost_usd !== undefined)
635
+ lines.push(`max_cost_usd $${args.max_cost_usd} covers ${REFERENCE_BUDGET_FACTOR} times the batch reference price ($${budgetRoom.usd}, ${budgetRoom.credits} credits). This was checked before submitting; it does not limit the final charge.`);
636
+ if (total?.status === 'partial') {
637
+ lines.push(`Partial estimate at published rates: ${rangeText(total.estimate)} for ${count} inputs (not a total or an upper bound; partial for ${itemList(total.partial)}).`);
638
+ for (const item of total.estimate.possible_extras)
639
+ lines.push(`May also charge: ${item}`);
640
+ }
641
+ checked.forEach((item, index) => {
642
+ for (const applied of item.prepared.defaults)
643
+ lines.push(`Applied default: inputs[${index}].${applied.param}=${applied.value} (${applied.reason}).`);
644
+ });
645
+ const warnings = [...new Set(checked.flatMap((item, index) => item.warnings.map(warning => entry.spec ? `inputs[${index}].${warning}` : warning)))];
646
+ for (const warning of warnings)
647
+ lines.push(`Warning: ${warning}`);
648
+ if (taskIds.length)
649
+ lines.push(`Collect the results with list_tasks (task_ids: ${taskIds.join(', ')}); it is free and read-only.`);
650
+ if (finishing.length) {
651
+ const fixFirst = reports.some(report => report.finishable && report.state === 'rejected');
652
+ lines.push(`To finish the batch, call ${name} again with client_request_id "${batchId}" and exactly the same inputs within 24 hours${fixFirst ? ', after fixing what the refused inputs need' : ''}: ${itemList(finishing)} will then be submitted, and accepted items return their original tasks without a new charge.`);
653
+ }
654
+ if (unknown.length)
655
+ lines.push(`The outcome of ${itemList(unknown)} is unknown: retry later with the same client_request_id and inputs, or check list_tasks.`);
656
+ if (accepted.length < count)
657
+ lines.push('Never resubmit accepted, not-submitted or unknown-outcome inputs under a new client_request_id: that creates and charges new tasks.');
658
+ // Each distinct next step once, with the refused inputs it applies to.
659
+ const steps = new Map();
660
+ for (const report of reports) {
661
+ if (report.state === 'rejected' && !report.conflict && report.error)
662
+ steps.set(report.error.next_step, [...(steps.get(report.error.next_step) ?? []), report.index]);
663
+ }
664
+ if (steps.size)
665
+ lines.push('Next steps for refused inputs:', ...[...steps].map(([step, indexes]) => `- ${itemList(indexes)}: ${step}`));
666
+ if (counts.outcome_unknown)
667
+ lines.push(DASHBOARD_CHECK_GUIDANCE);
668
+ lines.push(`client_request_id: ${batchId}`);
669
+ const structured = {
670
+ model: entry.id,
671
+ type: kind,
672
+ batch: { client_request_id: batchId, ...counts },
673
+ items: reports.map(report => report.structured),
674
+ task_ids: taskIds,
675
+ pricing_scope: 'public_default',
676
+ pricing_source: 'pricing_rules',
677
+ ...(total && total.status !== 'needs_input' ? { amounts: total.amounts } : {}),
678
+ final_budget_enforced: false,
679
+ client_request_id: batchId,
680
+ submission_state: accepted.length === count ? 'accepted' : accepted.length ? 'partial'
681
+ : counts.outcome_unknown ? 'outcome_unknown' : counts.rejected ? 'rejected' : 'not_submitted',
682
+ ...(expiredApproval ? { approval_expired: true } : {}),
683
+ ...(skippedBatch ? { estimate_skipped: true, estimate_skip_reason: skipReasons } : {}),
684
+ ...(batchSkipped?.approved ? { approved_amounts: amountsForUC(batchSkipped.approved) } : {}),
685
+ ...(heldCredits > 0 ? { reserved_credits: heldCredits, reserved_usd: usdOf(heldCredits) } : {}),
686
+ ...(total?.status === 'estimated' ? { estimate: { min_usd: total.estimate.min_usd, max_usd: total.estimate.max_usd } } : {}),
687
+ ...(total?.status === 'partial' ? { estimate: total.estimate } : {}),
688
+ ...(tokenBilled && total ? { estimate: { status: total.status, min_usd: total.estimate.min_usd, max_usd: total.estimate.max_usd, total_known: false } } : {}),
689
+ ...(budgetRoom && args.max_cost_usd !== undefined ? { budget_check: { factor: REFERENCE_BUDGET_FACTOR, amounts: budgetRoom, max_cost_usd: args.max_cost_usd } } : {}),
690
+ ...(warnings.length ? { warnings } : {}),
691
+ ...(counts.outcome_unknown ? dashboardCheck() : {}),
692
+ };
693
+ if (accepted.length > 0)
694
+ return ok(lines.join('\n'), structured);
695
+ const first = reports.find(report => report.error)?.error;
696
+ return failure(lines.join('\n'), { ...structured, error: { category: first?.category ?? 'not_submitted', ...(first?.code ? { code: first.code } : {}) },
697
+ charged: counts.outcome_unknown ? 'unknown' : 'no' });
698
+ }
699
+ catch (error) {
700
+ if (error instanceof PricingRulesError)
701
+ return failure(error.code === 'rate_limit_exceeded'
702
+ ? `The platform is limiting pricing requests right now, so the prices of these inputs could not be checked and nothing was submitted or charged. Try again in ${retryText(error.retryAfter)}.`
703
+ : 'The pricing rules could not be verified for these inputs. Nothing was submitted or charged.', {
704
+ error: { category: 'estimate_unavailable', code: error.code, ...(error.retryAfter !== undefined ? { retry_after_seconds: error.retryAfter } : {}) },
705
+ charged: 'no', submission_state: 'not_submitted', batch
706
+ });
707
+ if (error instanceof QuoteError)
708
+ return failure(`${error.message} Nothing was submitted or charged.`, {
709
+ error: { category: 'estimate_unavailable', code: error.code }, charged: 'no', submission_state: 'not_submitted', batch
710
+ });
711
+ // Each submission reports its own outcome, so an error here came before any item was submitted.
712
+ return errorResult(error, { paid: false, clientRequestId: batchId, phase: 'before_submit' });
713
+ }
714
+ }