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