@evolinkai/cli 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +20 -6
  2. package/package.json +2 -2
  3. package/skills/evolink-cli/SKILL.md +21 -7
  4. package/skills/evolink-cli/references/capabilities.md +1 -1
  5. package/skills/evolink-cli/references/media-workflows.md +1 -1
  6. package/skills/evolink-cli/references/usage-and-budget.md +5 -3
  7. package/src/cli.mjs +76 -21
  8. package/src/help.mjs +12 -5
  9. package/src/media.mjs +148 -37
  10. package/src/platform/core/src/data/model-constraints.js +13 -1
  11. package/src/platform/core/src/data/model-params.overrides.generated.js +1 -1
  12. package/src/platform/core/src/platform-operations.js +1 -1
  13. package/src/platform/core/src/services/api-client.js +1 -1
  14. package/src/platform/core/src/services/batch-generation.js +117 -0
  15. package/src/platform/core/src/services/catalog-client.js +28 -2
  16. package/src/platform/core/src/services/gpt-image-tokens.js +264 -0
  17. package/src/platform/core/src/services/mj-prompt.js +18 -0
  18. package/src/platform/core/src/services/model-capabilities.js +2 -1
  19. package/src/platform/core/src/services/omni-tokens.js +245 -0
  20. package/src/platform/core/src/services/param-validator.js +48 -1
  21. package/src/platform/core/src/services/pricing-call-limit.js +40 -0
  22. package/src/platform/core/src/services/pricing-derived.js +59 -0
  23. package/src/platform/core/src/services/pricing-quote-client.js +30 -7
  24. package/src/platform/core/src/services/pricing-rules-client.js +56 -3
  25. package/src/platform/core/src/services/pricing-rules-estimate.js +376 -59
  26. package/src/platform/core/src/tool-guidance.js +25 -2
  27. package/src/platform/core/src/tools/estimate-cost.js +220 -63
  28. package/src/platform/core/src/tools/generate.js +505 -71
  29. package/src/platform/core/src/tools/get-model.js +28 -0
  30. package/src/platform/core/src/tools/get-pricing-rules.js +15 -5
  31. package/src/platform/core/src/tools/search-models.js +4 -1
  32. package/src/platform/core/src/tools/shared.js +5 -1
  33. package/src/platform/core/src/version.js +1 -1
  34. package/src/platform/source.json +54 -42
  35. package/src/state.mjs +12 -1
@@ -2,17 +2,19 @@
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 { getCredits } from '../services/api-client.js';
5
+ import { MAX_BATCH_ITEMS, batchTotal } 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
- import { PricingRulesError } from '../services/pricing-rules-client.js';
9
+ import { PricingRulesError, reusablePricingRules } from '../services/pricing-rules-client.js';
9
10
  import { QuoteError, QuoteParameters } from '../services/pricing-quote-client.js';
10
- import { createRulesEstimate } from '../services/pricing-rules-estimate.js';
11
+ import { calculateRulesEstimate, createRulesEstimate, readPricingRulesFor, recentRulesNote } from '../services/pricing-rules-estimate.js';
11
12
  import { prepareSeedanceInput } from '../services/seedance-input.js';
12
13
  import { API_KEYS_URL, MCP_CONSOLE_URL, MCP_KEY_NAME, TOP_UP_URL } from '../services/http-policy.js';
13
14
  import { trackedLink } from '../services/utm.js';
14
15
  import { currentCredentialMode } from '../request-context.js';
15
- import { MEDIA_SECONDS_DESCRIPTION, MEDIA_SECONDS_MAX, READ_ONLY, dailyLimitOf, errorResult, failure, money, ok } from './shared.js';
16
+ import { MEDIA_SECONDS_DESCRIPTION, MEDIA_SECONDS_MAX, READ_ONLY, dailyLimitOf, errorResult, failure, money, ok, retryText } from './shared.js';
17
+ import { pricingCallLimitReached } from '../services/pricing-call-limit.js';
16
18
  export function registerEstimateCost(server, config) {
17
19
  server.registerTool('estimate_cost', {
18
20
  title: 'Estimate cost',
@@ -20,23 +22,33 @@ export function registerEstimateCost(server, config) {
20
22
  'Check a generation input and estimate what it will cost, without submitting anything. Free.',
21
23
  'Returns whether the input is valid, the expected price range in USD and credits, what it is based on, and whether the account balance and any spending limit (the EvoLink MCP limit, or this API key\'s) cover it.',
22
24
  'Call it before a paid generate_* call, then use the generation confirmation template in the server instructions.',
25
+ `For several tasks of one model, pass inputs (up to ${MAX_BATCH_ITEMS}): one total and one pricing_quote approve the whole batch.`,
23
26
  ].join(' '),
24
27
  inputSchema: {
25
28
  model: z.string().min(1).max(128).describe('Model ID, e.g. "seedance-2.0-text-to-video".'),
26
- input: z.record(z.unknown()).optional()
29
+ input: z.record(z.string(), z.unknown()).optional()
27
30
  .describe('The input you plan to pass to the generate tool, e.g. {"prompt":"…","duration":5,"quality":"1080p"}.'),
31
+ // The leading max() lets zod stop at an oversized array instead of checking every element.
32
+ inputs: z.array(z.record(z.string(), z.unknown())).max(MAX_BATCH_ITEMS).min(1).optional()
33
+ .describe(`Several inputs for this model (1–${MAX_BATCH_ITEMS}), each as you will pass it in the generate tool's inputs, in the same order. Returns each input's estimate, the total and one pricing_quote that approves the whole batch. media_seconds and pricing_parameters apply to every input. Pass input or inputs, not both.`),
28
34
  pricing_source: z.enum(['pricing_rules', 'account', 'public_reference']).default('pricing_rules').describe('Use published full pricing rules for public default estimates. The old account/public_reference values are compatibility aliases; neither requests a backend account quote.'),
29
- pricing_parameters: QuoteParameters.optional().describe('Measured or explicitly expected usage declared by the pricing policy, such as input_seconds or search_count. Missing enabled-search counts produce a zero-search partial subtotal and per-search rates. Do not invent counts, include user_group/prices/prompts, or treat expected counts as execution limits.'),
35
+ pricing_parameters: QuoteParameters.optional().describe('Measured or explicitly expected usage declared by the pricing policy, such as input_seconds or search_count. Missing enabled-search counts produce a zero-search partial subtotal and per-search rates. GPT Image token models do not use token counts here: their reference price comes from the input. Do not invent counts, include user_group/prices/prompts, or treat expected counts as execution limits.'),
30
36
  media_seconds: z.number().positive().max(MEDIA_SECONDS_MAX).optional().describe(MEDIA_SECONDS_DESCRIPTION),
31
37
  },
32
38
  annotations: { title: 'Estimate cost', ...READ_ONLY },
33
- }, async ({ model, input, media_seconds: mediaSeconds, pricing_source: pricingSource, pricing_parameters: pricingParameters }) => {
39
+ }, async ({ model, input, inputs, media_seconds: mediaSeconds, pricing_source: pricingSource, pricing_parameters: pricingParameters }) => {
34
40
  try {
41
+ if (inputs !== undefined && input !== undefined)
42
+ return failure('Pass input for one generation or inputs for a batch, not both. No estimate was created.', {
43
+ error: { category: 'invalid_request', param: 'inputs' }, charged: 'no', batch: { items: inputs.length }
44
+ });
35
45
  const { catalog, entry } = await resolveModel(model, config, { fresh: true, allowStale: false, skipPricing: true });
36
46
  if (!entry) {
37
47
  const suggestions = suggestModels(catalog, model);
38
48
  return failure(`Unknown model "${model}".${suggestions.length ? ` Did you mean: ${suggestions.join(', ')}?` : ''} Use search_models to find model IDs.`, { error: { category: 'not_found', param: 'model' }, suggestions });
39
49
  }
50
+ if (inputs !== undefined)
51
+ return await estimateBatch(config, entry, inputs, { mediaSeconds, pricingParameters, pricingSource });
40
52
  const prepared = prepareSeedanceInput(entry, input ?? {});
41
53
  const values = prepared.input;
42
54
  const validation = entry.spec ? validateInput(entry.spec, values) : undefined;
@@ -44,7 +56,10 @@ export function registerEstimateCost(server, config) {
44
56
  validation?.warnings.push(...prepared.warnings);
45
57
  if (validation?.errors.length)
46
58
  return failure('The generation input is invalid; no estimate was created.', { input_valid: false, problems: validation.errors, error: { category: 'invalid_request' }, charged: 'no' });
47
- const rulesEstimate = await createRulesEstimate(entry, values, { mediaSeconds, pricingParameters });
59
+ const over = estimateLimitReached(config, entry);
60
+ if (over)
61
+ return limitFailure(over, pricingSource);
62
+ const rulesEstimate = await createRulesEstimate(entry, values, { mediaSeconds, pricingParameters, reuseRules: config.reusePricingRules === true });
48
63
  const estimate = rulesEstimate.estimate;
49
64
  const lines = [`Estimate for ${entry.id} (${entry.kind}); nothing was submitted or charged.`];
50
65
  if (!validation) {
@@ -65,10 +80,12 @@ export function registerEstimateCost(server, config) {
65
80
  lines.push(`Estimated cost: ${range}`);
66
81
  else if (estimate.status === 'partial' && range)
67
82
  lines.push(`Partial estimate at published rates: ${range} (not a total or an upper bound).`);
83
+ else if (estimate.status === 'token_billed' && range)
84
+ lines.push(`Reference price: ${range}. Billed by actual token usage and settled when the task finishes, so the final charge may be lower or slightly higher.`);
68
85
  else if (estimate.status === 'token_billed')
69
86
  lines.push('Cost: billed by tokens used; it is only known after the task runs.');
70
87
  else if (estimate.status === 'needs_input')
71
- lines.push('Cost: cannot estimate yet; see the note below.');
88
+ lines.push('Cost: cannot estimate yet. The total depends on usage this request does not give:', ...(estimate.usage_help ?? []).map(line => `- ${line}`));
72
89
  else if (estimate.uncheckable_reason === 'output_duration')
73
90
  lines.push('Cost: the output duration is unknown, so there is no total or upper bound to quote.');
74
91
  else
@@ -79,19 +96,23 @@ export function registerEstimateCost(server, config) {
79
96
  lines.push('May also charge:', ...estimate.possible_extras.map(line => `- ${line}`));
80
97
  for (const note of estimate.notes)
81
98
  lines.push(`Note: ${note}`);
99
+ // Without any priced component there is no total to show or approve: no amounts and no approval record.
100
+ const priced = estimate.status !== 'needs_input';
82
101
  const structured = {
83
102
  model: entry.id,
84
103
  type: entry.kind,
85
104
  pricing_scope: 'public_default',
86
105
  pricing_source: 'pricing_rules',
87
- pricing_quote: rulesEstimate.approval,
88
- amounts: rulesEstimate.amounts,
106
+ ...(priced ? { pricing_quote: rulesEstimate.approval, amounts: rulesEstimate.amounts } : { submission_allowed: false }),
107
+ total_known: estimate.total_known === true,
108
+ ...(estimate.missing_usage ? { missing_usage: estimate.missing_usage } : {}),
89
109
  components: rulesEstimate.components,
90
110
  pricing_parameters: rulesEstimate.parameters,
91
111
  policy_version: rulesEstimate.rule.policy_version,
92
112
  policy_checksum: rulesEstimate.rule.policy_checksum,
93
113
  settlement_basis: rulesEstimate.rule.settlement_basis,
94
- expires_at: rulesEstimate.approval.expires_at,
114
+ ...(priced ? { expires_at: rulesEstimate.approval.expires_at } : {}),
115
+ ...('rules_read_at' in rulesEstimate ? { rules_read_at: rulesEstimate.rules_read_at } : {}),
95
116
  final_budget_enforced: false,
96
117
  input_valid: validation ? validation.errors.length === 0 : null,
97
118
  problems: validation?.errors ?? [],
@@ -102,66 +123,27 @@ export function registerEstimateCost(server, config) {
102
123
  ...(prepared.applies ? { effective_input: values, defaults_applied: prepared.defaults,
103
124
  amount_scope: estimate.status === 'partial' ? 'known_components_subtotal' : estimate.status === 'estimated' ? 'expected_usage_estimate' : 'not_established' } : {}),
104
125
  };
105
- try {
106
- const credits = await getCredits(config, 'estimate_cost');
107
- const balance = Math.max(0, credits.user.remaining_credits);
108
- lines.push(`Account balance: ${money(balance)}`);
109
- structured.balance_credits = balance;
110
- if (estimate.status === 'estimated' && estimate.max_credits !== undefined) {
111
- const enough = balance >= estimate.max_credits;
112
- structured.enough_balance = enough;
113
- if (!enough)
114
- lines.push(`The account balance may not cover this; top up at ${trackedLink(TOP_UP_URL, 'top_up')}.`);
115
- }
116
- // The key's own limit is checked before the balance: warn now instead of failing on submit.
117
- if (!credits.token.unlimited_credits) {
118
- const signedIn = currentCredentialMode() === 'signed_in';
119
- const left = Math.max(0, credits.token.remaining_credits);
120
- lines.push(signedIn
121
- ? `EvoLink MCP limit left: ${money(left)} (shared by all connected assistants).`
122
- : `This API key's limit left: ${money(left)}.`);
123
- structured.limit_scope = signedIn ? 'mcp' : 'api_key';
124
- structured.limit_remaining_credits = left;
125
- if (estimate.status === 'estimated' && estimate.max_credits !== undefined) {
126
- const enoughLimit = left >= estimate.max_credits;
127
- structured.enough_limit = enoughLimit;
128
- if (!enoughLimit) {
129
- lines.push(signedIn
130
- ? `The EvoLink MCP limit may not cover this. It is a limit the user set, not the account balance; they can raise it at ${trackedLink(MCP_CONSOLE_URL, 'api_keys')} (the key named "${MCP_KEY_NAME}").`
131
- : `This API key's limit may not cover this; raise it at ${trackedLink(API_KEYS_URL, 'api_keys')} or use another key.`);
132
- }
133
- }
134
- }
135
- const daily = dailyLimitOf(credits.token);
136
- if (daily && estimate.status === 'estimated' && estimate.max_credits !== undefined) {
137
- const signedIn = currentCredentialMode() === 'signed_in';
138
- const enoughToday = daily.left >= estimate.max_credits;
139
- structured.daily_left_credits = daily.left;
140
- structured.enough_daily_limit = enoughToday;
141
- if (!enoughToday) {
142
- const resets = `it resets at midnight${daily.zone ? ` (${daily.zone})` : ''}`;
143
- lines.push(signedIn
144
- ? `Today's EvoLink MCP limit may not cover this (${money(daily.left)} left today; ${resets}). It is a limit the user set, not the account balance.`
145
- : `Today's limit of this API key may not cover this (${money(daily.left)} left today; ${resets}).`);
146
- }
147
- }
148
- }
149
- catch {
150
- lines.push('Balance: could not be read right now.');
151
- }
152
- lines.push(`Estimate valid until ${rulesEstimate.approval.expires_at}.`, 'Public default estimate; account discounts are not included. Confirm this estimated cost before generation. Final charges depend on actual usage.');
126
+ await addBalance(config, estimate, lines, structured);
127
+ if (priced)
128
+ lines.push(`Estimate valid until ${rulesEstimate.approval.expires_at}.`, estimate.status === 'token_billed'
129
+ ? 'Public default reference price; account discounts are not included. Confirm it before generation. The final charge follows actual token usage.'
130
+ : 'Public default estimate; account discounts are not included. Confirm this estimated cost before generation. Final charges depend on actual usage.');
131
+ else
132
+ lines.push('No total or approval record was issued. Estimate again with the missing usage before asking the user to approve a generation.');
153
133
  return ok(lines.join('\n'), structured);
154
134
  }
155
135
  catch (error) {
156
136
  if (error instanceof PricingRulesError)
157
- return failure('The model pricing rules could not be verified. No estimate or generation was created.', {
158
- error: { category: 'estimate_unavailable', code: error.code, status: error.status }, pricing_source: pricingSource,
159
- submission_allowed: false, final_budget_enforced: false, charged: 'no'
137
+ return failure(error.code === 'rate_limit_exceeded'
138
+ ? `The platform is limiting pricing requests right now, so no estimate was created. Try again in ${retryText(error.retryAfter)}. Nothing was submitted or charged.`
139
+ : 'The model pricing rules could not be verified. No estimate or generation was created.', {
140
+ error: { category: 'estimate_unavailable', code: error.code, status: error.status, ...(error.retryAfter !== undefined ? { retry_after_seconds: error.retryAfter } : {}) }, pricing_source: pricingSource,
141
+ submission_allowed: false, final_budget_enforced: false, charged: 'no', ...(inputs ? { batch: { items: inputs.length } } : {})
160
142
  });
161
143
  if (error instanceof QuoteError)
162
144
  return failure(`${error.message} Nothing was submitted or charged.`, {
163
145
  error: { category: 'estimate_unavailable', code: error.code, ...(error.param ? { param: error.param } : {}) },
164
- pricing_source: pricingSource, submission_allowed: false, final_budget_enforced: false, charged: 'no'
146
+ pricing_source: pricingSource, submission_allowed: false, final_budget_enforced: false, charged: 'no', ...(inputs ? { batch: { items: inputs.length } } : {})
165
147
  });
166
148
  const failed = errorResult(error);
167
149
  return { ...failed, structuredContent: { ...failed.structuredContent, pricing_source: pricingSource,
@@ -169,3 +151,178 @@ export function registerEstimateCost(server, config) {
169
151
  }
170
152
  });
171
153
  }
154
+ /** Only an estimate that reads the platform's rules counts; one answered from rules read moments ago does not. */
155
+ function estimateLimitReached(config, entry) {
156
+ const reused = config.reusePricingRules === true && reusablePricingRules({ model: entry.id.toLowerCase(), view: 'full' });
157
+ const over = reused ? undefined : pricingCallLimitReached('estimate_cost');
158
+ return over;
159
+ }
160
+ function limitFailure(over, pricingSource) {
161
+ return failure(`This account already made ${over.limit} estimate_cost calls that read the pricing rules in the last minute, the most allowed. Wait ${retryText(over.retryAfterSeconds)}, then estimate again. Nothing was submitted or charged.`, {
162
+ error: { category: 'rate_limited', code: 'pricing_calls_per_minute', retry_after_seconds: over.retryAfterSeconds },
163
+ pricing_source: pricingSource, submission_allowed: false, final_budget_enforced: false, charged: 'no'
164
+ });
165
+ }
166
+ /** Whether the balance and the spending limits cover the estimate; a reference price is what the gateway reserves at submission. */
167
+ async function addBalance(config, estimate, lines, structured) {
168
+ const checkable = (estimate.status === 'estimated' || estimate.status === 'token_billed') && estimate.max_credits !== undefined;
169
+ try {
170
+ const credits = await getCredits(config, 'estimate_cost');
171
+ const balance = Math.max(0, credits.user.remaining_credits);
172
+ lines.push(`Account balance: ${money(balance)}`);
173
+ structured.balance_credits = balance;
174
+ if (checkable && estimate.max_credits !== undefined) {
175
+ const enough = balance >= estimate.max_credits;
176
+ structured.enough_balance = enough;
177
+ if (!enough)
178
+ lines.push(`The account balance may not cover this; top up at ${trackedLink(TOP_UP_URL, 'top_up')}.`);
179
+ }
180
+ // The key's own limit is checked before the balance: warn now instead of failing on submit.
181
+ if (!credits.token.unlimited_credits) {
182
+ const signedIn = currentCredentialMode() === 'signed_in';
183
+ const left = Math.max(0, credits.token.remaining_credits);
184
+ lines.push(signedIn
185
+ ? `EvoLink MCP limit left: ${money(left)} (shared by all connected assistants).`
186
+ : `This API key's limit left: ${money(left)}.`);
187
+ structured.limit_scope = signedIn ? 'mcp' : 'api_key';
188
+ structured.limit_remaining_credits = left;
189
+ if (checkable && estimate.max_credits !== undefined) {
190
+ const enoughLimit = left >= estimate.max_credits;
191
+ structured.enough_limit = enoughLimit;
192
+ if (!enoughLimit) {
193
+ lines.push(signedIn
194
+ ? `The EvoLink MCP limit may not cover this. It is a limit the user set, not the account balance; they can raise it at ${trackedLink(MCP_CONSOLE_URL, 'api_keys')} (the key named "${MCP_KEY_NAME}").`
195
+ : `This API key's limit may not cover this; raise it at ${trackedLink(API_KEYS_URL, 'api_keys')} or use another key.`);
196
+ }
197
+ }
198
+ }
199
+ const daily = dailyLimitOf(credits.token);
200
+ if (daily && checkable && estimate.max_credits !== undefined) {
201
+ const signedIn = currentCredentialMode() === 'signed_in';
202
+ const enoughToday = daily.left >= estimate.max_credits;
203
+ structured.daily_left_credits = daily.left;
204
+ structured.enough_daily_limit = enoughToday;
205
+ if (!enoughToday) {
206
+ const resets = `it resets at midnight${daily.zone ? ` (${daily.zone})` : ''}`;
207
+ lines.push(signedIn
208
+ ? `Today's EvoLink MCP limit may not cover this (${money(daily.left)} left today; ${resets}). It is a limit the user set, not the account balance.`
209
+ : `Today's limit of this API key may not cover this (${money(daily.left)} left today; ${resets}).`);
210
+ }
211
+ }
212
+ }
213
+ catch {
214
+ lines.push('Balance: could not be read right now.');
215
+ }
216
+ }
217
+ const itemsText = (indexes) => indexes.map(index => `inputs[${index}]`).join(', ');
218
+ /** One input's price, for the per-input list of a batch. */
219
+ function itemPrice(estimate) {
220
+ const range = formatEstimateRange(estimate);
221
+ if (estimate.status === 'needs_input' || !range)
222
+ return `no total yet (depends on ${(estimate.missing_usage ?? []).join(', ') || 'usage measured when it runs'})`;
223
+ return estimate.status === 'partial' ? `${range} partial` : estimate.status === 'token_billed' ? `${range} reference price` : range;
224
+ }
225
+ /**
226
+ * Several inputs for one model, estimated from one read of its rules and counted once against the account: each
227
+ * input's price, the total, and one approval record for the whole batch, in input order.
228
+ */
229
+ async function estimateBatch(config, entry, inputs, options) {
230
+ const batch = { items: inputs.length };
231
+ const prepared = inputs.map(item => prepareSeedanceInput(entry, item));
232
+ const checks = prepared.map(item => {
233
+ if (!entry.spec)
234
+ return undefined;
235
+ const check = validateInput(entry.spec, item.input);
236
+ check.errors.push(...item.errors);
237
+ check.warnings.push(...item.warnings);
238
+ return check;
239
+ });
240
+ const located = (index, issues) => issues.map(issue => ({ ...issue, param: `inputs[${index}].${issue.param}` }));
241
+ const problems = checks.flatMap((check, index) => located(index, check?.errors ?? []));
242
+ if (problems.length)
243
+ return failure(['Some inputs are invalid; no estimate was created:', ...formatIssues(problems)].join('\n'), {
244
+ input_valid: false, problems, error: { category: 'invalid_request' }, charged: 'no', batch
245
+ });
246
+ const over = estimateLimitReached(config, entry);
247
+ if (over)
248
+ return limitFailure(over, options.pricingSource);
249
+ const reuse = config.reusePricingRules === true;
250
+ const { body, readAt } = await readPricingRulesFor(entry, { reuseRules: reuse });
251
+ const results = prepared.map((item, index) => {
252
+ try {
253
+ return calculateRulesEstimate(body, entry, item.input, { mediaSeconds: options.mediaSeconds, pricingParameters: options.pricingParameters });
254
+ }
255
+ catch (error) {
256
+ throw error instanceof QuoteError ? new QuoteError(error.code, `inputs[${index}]: ${error.message}`, error.param) : error;
257
+ }
258
+ });
259
+ const total = batchTotal(entry.id, results), combined = total.estimate, status = total.status;
260
+ if (readAt)
261
+ combined.notes.push(recentRulesNote(readAt));
262
+ const count = inputs.length;
263
+ const lines = [`Estimate for ${count} input${count === 1 ? '' : 's'} of ${entry.id} (${entry.kind}); nothing was submitted or charged.`];
264
+ lines.push(entry.spec ? 'Inputs look valid.' : 'Inputs not checked: this model\'s parameters are not documented here.');
265
+ const warnings = checks.flatMap((check, index) => located(index, check?.warnings ?? []));
266
+ if (warnings.length)
267
+ lines.push('Warnings:', ...formatIssues(warnings));
268
+ prepared.forEach((item, index) => {
269
+ for (const applied of item.defaults)
270
+ lines.push(`Applied default: inputs[${index}].${applied.param}=${applied.value} (${applied.reason}); this effective value is used for pricing and submission.`);
271
+ });
272
+ const prices = results.map(result => itemPrice(result.estimate));
273
+ const same = prices.every(price => price === prices[0]);
274
+ const each = same && count > 1 ? `; ${prices[0]} each` : '';
275
+ const range = formatEstimateRange(combined);
276
+ if (status === 'estimated' && range)
277
+ lines.push(`Estimated cost: ${range} in total for ${count} input${count === 1 ? '' : 's'}${each}.`);
278
+ else if (status === 'partial' && range)
279
+ lines.push(`Partial estimate at published rates: ${range} in total (not a total or an upper bound; partial for ${itemsText(total.partial)}).`);
280
+ else if (status === 'token_billed' && range)
281
+ lines.push(`Reference price: ${range} in total for ${count} input${count === 1 ? '' : 's'}${each}. Billed by actual token usage and settled when each task finishes, so the final charge may be lower or slightly higher.`);
282
+ else if (status === 'needs_input')
283
+ lines.push(`Cost: cannot estimate yet. ${itemsText(total.needsInput)} depend${total.needsInput.length === 1 ? 's' : ''} on usage this request does not give:`, ...(combined.usage_help ?? []).map(line => `- ${line}`));
284
+ if (!same)
285
+ lines.push('Per input:', ...prices.map((price, index) => `- inputs[${index}]: ${price}`));
286
+ if (combined.basis.length)
287
+ lines.push('Based on:', ...combined.basis.map(line => `- ${line}`));
288
+ if (combined.possible_extras.length)
289
+ lines.push('May also charge:', ...combined.possible_extras.map(line => `- ${line}`));
290
+ for (const note of combined.notes)
291
+ lines.push(`Note: ${note}`);
292
+ // Without a total for every input there is nothing to approve: no amounts and no approval record.
293
+ const quoted = status !== 'needs_input';
294
+ const rule = results[0].rule;
295
+ const structured = {
296
+ model: entry.id,
297
+ type: entry.kind,
298
+ batch,
299
+ pricing_scope: 'public_default',
300
+ pricing_source: 'pricing_rules',
301
+ ...(quoted ? { pricing_quote: total.approval, amounts: total.amounts } : { submission_allowed: false }),
302
+ total_known: status === 'estimated',
303
+ ...(combined.missing_usage ? { missing_usage: combined.missing_usage } : {}),
304
+ items: results.map((result, index) => ({ index, status: result.estimate.status, total_known: result.estimate.total_known === true,
305
+ ...(result.estimate.status === 'needs_input' ? {} : { amounts: result.amounts }),
306
+ ...(result.estimate.missing_usage ? { missing_usage: result.estimate.missing_usage } : {}),
307
+ ...(result.estimate.search_charges?.length ? { search_charges: result.estimate.search_charges } : {}),
308
+ ...(prepared[index].applies ? { effective_input: prepared[index].input, defaults_applied: prepared[index].defaults } : {}) })),
309
+ policy_version: rule.policy_version,
310
+ policy_checksum: rule.policy_checksum,
311
+ settlement_basis: rule.settlement_basis,
312
+ ...(quoted ? { expires_at: total.approval.expires_at } : {}),
313
+ ...(readAt ? { rules_read_at: readAt } : {}),
314
+ final_budget_enforced: false,
315
+ input_valid: entry.spec ? true : null,
316
+ problems: [],
317
+ warnings,
318
+ estimate: combined,
319
+ };
320
+ await addBalance(config, combined, lines, structured);
321
+ if (quoted)
322
+ lines.push(`Estimate valid until ${total.approval.expires_at}.`, status === 'token_billed'
323
+ ? `Public default reference price; account discounts are not included. Confirm it for the whole batch before generation. The final charge follows actual token usage.`
324
+ : `Public default estimate; account discounts are not included. Confirm this estimated cost for the whole batch before generation. Final charges depend on actual usage.`, `One approval covers all ${count} input${count === 1 ? '' : 's'}: pass this pricing_quote with the same inputs, in the same order, to generate_${entry.kind}.`);
325
+ else
326
+ lines.push('No total or approval record was issued. Estimate again with the missing usage before asking the user to approve a generation.');
327
+ return ok(lines.join('\n'), structured);
328
+ }