@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
@@ -1,17 +1,21 @@
1
1
  // Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
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
- import { getPricingRules } from './pricing-rules-client.js';
5
- import { QuoteError, prepareQuoteParameters, quoteRequestHash } from './pricing-quote-client.js';
4
+ import { PricingRulesError, getPricingRules, recentModelRules } from './pricing-rules-client.js';
5
+ import { QuoteError, compareDecimal, isUsageParameter, prepareQuoteParameters, quoteRequestHash } from './pricing-quote-client.js';
6
6
  import { prepareSeedanceInput } from './seedance-input.js';
7
7
  import { searchUsage } from './search-usage.js';
8
+ import { CONSERVATIVE_QUOTE_PARAMETERS } from './pricing-derived.js';
9
+ import { INPUT_IMAGE_TOKENS, isTokenImageModel, tokenImageReservation } from './gpt-image-tokens.js';
10
+ import { OMNI_IMAGE_TOKENS, OMNI_UNREAD_TIER, isOmniTokenModel, omniLowerInputTier, omniReservation } from './omni-tokens.js';
8
11
  /**
9
- * How long an approval from estimate_cost may be passed to generate_*. The rules' own
10
- * `fresh_until` is a short refresh window (minutes); people confirming a price in a chat
11
- * need longer. generate_* re-evaluates the current rules and refuses with `price_changed`
12
- * when the price moved, so a longer approval cannot submit at a stale price.
12
+ * How long an approval from estimate_cost is shown as current. The rules' own `fresh_until`
13
+ * is a short refresh window (minutes); people confirming a price in a chat may come back much
14
+ * later. generate_* re-evaluates the current rules and refuses with `price_changed` when the
15
+ * price moved, so an approval never submits at a stale price; one past this time still holds
16
+ * for the same input and price (checkRulesApproval).
13
17
  */
14
- export const APPROVAL_TTL_MS = 30 * 60_000;
18
+ export const APPROVAL_TTL_MS = 24 * 60 * 60_000;
15
19
  function fail(code, message) { throw new QuoteError(code, message); }
16
20
  function gcd(a, b) { while (b)
17
21
  [a, b] = [b, a % b]; return a < 0n ? -a : a; }
@@ -70,12 +74,25 @@ export function amountsForUC(uc) {
70
74
  const a = decimal(uc);
71
75
  return { uc, credits: display(div(a, rat(10000n)), 4), cny: display(div(a, rat(100000n)), 5), usd: display(div(a, rat(680000n)), 8) };
72
76
  }
73
- export function rulesBudgetExceeded(uc, budget) {
77
+ function budgetUC(budget) {
74
78
  // String(number) may use scientific notation for a small, explicit budget.
75
79
  const [mantissa, exp = '0'] = String(budget).split('e');
76
80
  const power = Number(exp), b = decimal(mantissa);
77
81
  const value = power < 0 ? div(b, rat(10n ** BigInt(-power))) : mul(b, rat(10n ** BigInt(power)));
78
- return cmp(decimal(uc), mul(value, rat(680000n))) > 0;
82
+ return mul(value, rat(680000n));
83
+ }
84
+ export function rulesBudgetExceeded(uc, budget) {
85
+ return cmp(decimal(uc), budgetUC(budget)) > 0;
86
+ }
87
+ /**
88
+ * A token-billed reference price fits a budget only with room for the tokens a task actually uses: 1.5 times the
89
+ * reference must fit. The largest overrun on record is 20% (gpt-image-2, 4K high); large reference images are unmeasured.
90
+ */
91
+ export const REFERENCE_BUDGET_FACTOR = '1.5';
92
+ /** The amount a budget has to cover for a reference price, for messages. */
93
+ export function referenceAllowance(uc) { return amountsForUC(display(mul(decimal(uc), decimal(REFERENCE_BUDGET_FACTOR)), 4)); }
94
+ export function referenceBudgetExceeded(uc, budget) {
95
+ return cmp(mul(decimal(uc), decimal(REFERENCE_BUDGET_FACTOR)), budgetUC(budget)) > 0;
79
96
  }
80
97
  const arity = { constant: [0, 0], variable: [0, 0], lookup: [0, 0],
81
98
  add: [2, 32], multiply: [2, 32], subtract: [2, 2], divide: [2, 2], min: [2, 32], max: [2, 32], clamp: [3, 3],
@@ -97,6 +114,163 @@ function checkExpression(node, declared, depth = 0, budget = { nodes: 0 }) {
97
114
  for (const child of node.args ?? [])
98
115
  checkExpression(child, declared, depth + 1, budget);
99
116
  }
117
+ /** Every value an expression reads, so a component short of several usages can name all of them. */
118
+ function variables(node, found) {
119
+ if (!node)
120
+ return;
121
+ if (node.op === 'variable' && node.name)
122
+ found.add(node.name);
123
+ if (node.op === 'lookup')
124
+ variables(node.key, found);
125
+ for (const child of node.args ?? [])
126
+ variables(child, found);
127
+ }
128
+ function componentReads(c) {
129
+ const read = new Set();
130
+ for (const expr of [c.condition, c.quantity_rule, ...c.tiers.map(t => t.when)])
131
+ variables(expr, read);
132
+ return read;
133
+ }
134
+ /** How to give a usage value an estimate lacks, or why only the finished task knows it. */
135
+ function usageHint(name, entry, declared) {
136
+ if (name === 'media_seconds')
137
+ return 'pass the length of the input video in seconds as media_seconds (for several reference videos, the longest one\'s): EvoLink measures it at submission and reserves its tokens with the output\'s.';
138
+ if (name === 'input_seconds' || name === 'first_input_video_seconds')
139
+ return 'pass the length of the input video or audio, in seconds, as media_seconds.';
140
+ if (name === 'source_output_seconds')
141
+ return `pass the length of the source task's output, in seconds, in pricing_parameters.${name}.`;
142
+ if (name === 'output_seconds' || name === 'duration_seconds') {
143
+ // As prepareQuoteParameters reads it: media_seconds stands for the billed length only where the model takes no duration.
144
+ return entry.spec && !entry.spec.params.duration && !declared.has('duration') && entry.spec.constraints?.outputDuration !== 'unknown'
145
+ ? 'pass the billed length, usually that of the input video or audio, in seconds, as media_seconds.'
146
+ : `the generated length is known only after the task runs; pass an expected length in pricing_parameters.${name} only when the user gives one.`;
147
+ }
148
+ if (name === 'output_fps')
149
+ return `pass the source video's frame rate in pricing_parameters.${name}, or, if a 30 fps output is acceptable, set model_params.max_fps to "30".`;
150
+ if (/search_count$/.test(name))
151
+ return `the number of searches is known only after the task runs; pass an expected count in pricing_parameters.${name} only when the user gives one.`;
152
+ return `pass measured or expected usage in pricing_parameters.${name}.`;
153
+ }
154
+ /** Token usage is known only once the task has run; name the published rates instead. */
155
+ function tokenHelp(names, rule) {
156
+ const unit = (text) => text === '1k_tokens' ? '1K tokens' : text.replace(/_/g, ' ');
157
+ const rates = rule.components.filter(c => names.some(name => componentReads(c).has(name)))
158
+ .map(c => `${c.id} ${c.tiers.length ? 'from ' : ''}$${c.rate.usd} per ${unit(c.unit)}`);
159
+ return `${names.join(', ')}: billed by the tokens the task actually uses, known only after it runs${rates.length ? ` (public default rates: ${rates.join('; ')})` : ''}.`;
160
+ }
161
+ function helpLines(names, entry, rule, declared) {
162
+ const tokens = names.filter(name => /tokens$/.test(name));
163
+ return [...names.filter(name => !tokens.includes(name)).map(name => `${name}: ${usageHint(name, entry, declared)}`),
164
+ ...(tokens.length ? [tokenHelp(tokens, rule)] : [])];
165
+ }
166
+ /** Every usage value a rule can bill by, with how to give it; get_model lists them before any estimate. */
167
+ export function billingUsageHelp(rule, entry) {
168
+ if (reservesTokens(rule, entry))
169
+ return [];
170
+ const declared = new Set((rule.parameters ?? []).map(p => p.name));
171
+ return helpLines([...declared].filter(name => isUsageParameter(entry.id, name)).sort(), entry, rule, declared);
172
+ }
173
+ // GPT Image and Gemini Omni token models: the reference price counts the tokens the gateway reserves at submission for the input.
174
+ const RESERVED_TOKENS = new Set(['image_input_tokens', 'image_cached_input_tokens', 'image_output_tokens',
175
+ 'text_input_tokens', 'text_cached_input_tokens', 'text_output_tokens']);
176
+ const OMNI_TOKENS = new Set(['input_tokens', 'video_output_tokens', 'other_output_tokens']);
177
+ /** GPT Image 2.6 rules also bill an SVG's author model. SVG output is not quoted, so a reference price uses none. */
178
+ const NO_SVG_AUTHOR = { svg_model: 'none', svg_input_tokens: 0, svg_output_tokens: 0 };
179
+ const svgAuthor = (name) => Object.hasOwn(NO_SVG_AUTHOR, name);
180
+ /** Only a rule billed by these token counts alone, with an output component, can price the reservation. */
181
+ function reservesTokens(rule, entry) {
182
+ const id = entry.id.toLowerCase();
183
+ if (rule.settlement_basis !== 'actual_usage')
184
+ return false;
185
+ if (isOmniTokenModel(id)) {
186
+ return (rule.parameters ?? []).every(p => OMNI_TOKENS.has(p.name))
187
+ && rule.components.some(c => c.role === 'video_output' && c.pricing_status === 'available' && componentReads(c).has('video_output_tokens'));
188
+ }
189
+ return isTokenImageModel(id)
190
+ && (rule.parameters ?? []).every(p => RESERVED_TOKENS.has(p.name)
191
+ || svgAuthor(p.name) && (p.name !== 'svg_model' || (p.values ?? p.enum ?? []).includes(NO_SVG_AUTHOR.svg_model)))
192
+ && rule.components.some(c => c.role === 'image_output' && c.pricing_status === 'available' && componentReads(c).has('image_output_tokens'));
193
+ }
194
+ /** How estimate_cost prices a token model, for get_model. */
195
+ export function tokenReferenceHelp(rule, entry) {
196
+ if (!reservesTokens(rule, entry))
197
+ return undefined;
198
+ const rates = rule.components.filter(c => ![...componentReads(c)].some(svgAuthor))
199
+ .map(c => `${c.id} $${c.rate.usd} per ${c.unit === '1k_tokens' ? '1K tokens' : c.unit.replace(/_/g, ' ')}`);
200
+ if (isOmniTokenModel(entry.id.toLowerCase())) {
201
+ return `Billed by actual token usage. estimate_cost gives a reference price for the exact input: the tokens EvoLink reserves at submission for its resolution, duration, prompt, images and input videos, at the published rates (public default rates: ${rates.join('; ')}). Give an input or reference video's length as media_seconds; its resolution is read at submission, so the reference counts the highest (${OMNI_UNREAD_TIER}). The task settles at the tokens it actually uses.`;
202
+ }
203
+ return `Billed by actual token usage. estimate_cost gives a reference price for the exact input: the tokens EvoLink reserves at submission for its size, quality, n, prompt and reference images, at the published rates (public default rates: ${rates.join('; ')}). The task settles at the tokens it actually uses.`;
204
+ }
205
+ /** An Omni reservation's tokens as the rule's parameters. */
206
+ const omniParameters = (rule, usage) => Object.fromEntries((rule.parameters ?? []).map(p => [p.name, usage.tokens[p.name] ?? 0]));
207
+ function reservation(rule, entry, input, countPromptTokens, mediaSeconds) {
208
+ if (!reservesTokens(rule, entry))
209
+ return undefined;
210
+ const id = entry.id.toLowerCase();
211
+ if (isOmniTokenModel(id)) {
212
+ const usage = omniReservation(id, input, mediaSeconds, { countPromptTokens });
213
+ return 'needs' in usage ? usage : { omni: usage, parameters: omniParameters(rule, usage) };
214
+ }
215
+ const usage = tokenImageReservation(id, input, countPromptTokens);
216
+ const parameters = {};
217
+ for (const p of rule.parameters ?? []) {
218
+ parameters[p.name] = svgAuthor(p.name) ? NO_SVG_AUTHOR[p.name] : usage.per_image[p.name] ?? 0;
219
+ }
220
+ return { gpt: usage, parameters };
221
+ }
222
+ const CONFIRM_REFERENCE = 'Confirm this reference price before generation. It is billed by actual token usage: EvoLink reserves this amount at submission and settles the task at the tokens it actually uses, refunding or charging the difference when it finishes, so the final charge may be lower or slightly higher.';
223
+ const ignoredNote = (ignored) => `pricing_parameters ${ignored.join(', ')} ${ignored.length > 1 ? 'are' : 'is'} not used for this model: the reference price comes from the generation input.`;
224
+ function reservationNotes(usage, ignored) {
225
+ const notes = [CONFIRM_REFERENCE];
226
+ const gif = usage.output.gif;
227
+ if (gif)
228
+ notes.push(`output_format is gif: the ${gif.frames} frames of ${gif.frame_width}×${gif.frame_height}${usage.output.size === 'auto' ? ' (size auto)' : ''} are drawn ${gif.columns}×${gif.rows} on one ${usage.output.width}×${usage.output.height} image, and the reference counts that image's output tokens.`);
229
+ else if (usage.output.size === 'auto')
230
+ notes.push('size is auto, so the reference counts a 2048×2048 output, as EvoLink reserves for auto; the image is often smaller, so set a size for a closer reference price.');
231
+ if (usage.reference_images)
232
+ notes.push(`Each reference image or mask counts ${INPUT_IMAGE_TOKENS.toLocaleString('en-US')} input tokens; larger reference images can use more.`);
233
+ if (usage.images > 1)
234
+ notes.push(`n=${usage.images}: the reference covers ${usage.images} images; the model often returns fewer, and the task is billed for what it returns.`);
235
+ notes.push('Prompt tokens are approximated; EvoLink counts them exactly at submission.');
236
+ if (ignored.length)
237
+ notes.push(ignoredNote(ignored));
238
+ return notes;
239
+ }
240
+ const tokenText = (tokens) => tokens.toLocaleString('en-US');
241
+ function omniBasis(usage) {
242
+ const t = usage.tokens, videos = usage.input_videos;
243
+ const parts = [`${tokenText(t.video_output_tokens)} video output tokens (${usage.upscale ? `upscale ${usage.upscale.source} to ${usage.upscale.target}` : usage.output.resolution}, ${usage.output.seconds} s)`];
244
+ if (t.input_tokens) {
245
+ const inputs = [`about ${tokenText(usage.prompt_tokens)} prompt tokens`, ...usage.images ? [`${usage.images} image${usage.images > 1 ? 's' : ''}`] : [],
246
+ ...videos ? [`${videos.count > 1 ? `${videos.count} reference videos of` : 'an input video of'} ${videos.seconds} s at ${videos.resolution}`] : []];
247
+ parts.push(`${tokenText(t.input_tokens)} input tokens (${inputs.join(', ')})`);
248
+ }
249
+ if (t.other_output_tokens)
250
+ parts.push(`${tokenText(t.other_output_tokens)} other output tokens`);
251
+ return `Reference price: published token rates applied to what EvoLink reserves at submission for this input: ${parts.join(', ')}, each part rounded up.`;
252
+ }
253
+ function omniNotes(usage, ignored, lower) {
254
+ const notes = [CONFIRM_REFERENCE];
255
+ const videos = usage.input_videos;
256
+ if (videos?.resolution_assumed) {
257
+ notes.push(`EvoLink reads the input video's resolution at submission; the request does not give it, so the reference counts the highest, ${videos.resolution}, as EvoLink reserves when it cannot read it.${lower ? ` A ${lower.tier} input video reserves ${lower.amounts.credits} credits (about $${lower.amounts.usd}) instead.` : ''}`);
258
+ }
259
+ if (usage.upscale?.source_assumed) {
260
+ notes.push(`EvoLink reads the source video's resolution at submission; the reference counts the source that costs most for ${usage.upscale.target}, ${usage.upscale.source}.${lower ? ` A ${lower.tier} source reserves ${lower.amounts.credits} credits (about $${lower.amounts.usd}) instead.` : ''}`);
261
+ }
262
+ if (videos && usage.route !== 'upscale')
263
+ notes.push(`media_seconds counts ${videos.count > 1 ? 'each reference video' : 'the input video'} at ${videos.seconds} s (rounded up); EvoLink measures ${videos.count > 1 ? 'each' : 'it'} at submission.`);
264
+ if (usage.output.follows_input)
265
+ notes.push('quality is auto, so the output follows the input video\'s resolution.');
266
+ if (usage.images)
267
+ notes.push(`Each input image counts ${tokenText(OMNI_IMAGE_TOKENS)} input tokens.`);
268
+ if (usage.prompt_tokens)
269
+ notes.push('Prompt tokens are approximated; EvoLink counts them exactly at submission.');
270
+ if (ignored.length > 0)
271
+ notes.push(ignoredNote(ignored));
272
+ return notes;
273
+ }
100
274
  function evaluate(node, params) {
101
275
  const nodes = node.args ?? [], at = (i) => evaluate(nodes[i], params), number = (i) => numeric(at(i));
102
276
  switch (node.op) {
@@ -148,42 +322,11 @@ function evaluate(node, params) {
148
322
  default: return fail('invalid_pricing_expression', 'The pricing rule uses an unsupported operation.');
149
323
  }
150
324
  }
151
- export const ApprovedRulesEstimate = z.object({ source: z.literal('pricing_rules'), price_scope: z.literal('public_default'),
152
- model_id: z.string().min(1).max(100), request_hash: z.string().regex(/^[a-f0-9]{64}$/),
153
- fingerprint: z.string().regex(/^[a-f0-9]{64}$/), total_uc: z.string().max(32).regex(/^\d+$/),
154
- expires_at: z.string().datetime({ offset: true }) }).strict();
155
- function economicRules(rule) {
156
- // Freshness and configuration timestamps do not change the approved price.
157
- return { ...rule, components: rule.components.map(({ effective_at, official_rate, ...c }) => ({ ...c,
158
- tiers: c.tiers.map(({ effective_at, official_rate, ...t }) => t) })) };
159
- }
160
- export function calculateRulesEstimate(body, entry, input, options = {}) {
161
- const rule = 'model' in body ? body.model : body.models.find(model => model.model_id === entry.id);
162
- if (!rule || rule.model_id !== entry.id.toLowerCase() || rule.modality !== entry.kind || rule.policy_source !== 'published' || rule.pricing_status !== 'available') {
163
- fail('pricing_rules_unavailable', 'This model has no available published media pricing policy.');
164
- }
165
- const prepared = prepareSeedanceInput(entry, input);
166
- if (prepared.errors.length)
167
- throw new QuoteError('invalid_quote_parameter', `${prepared.errors[0].param} ${prepared.errors[0].problem}`, prepared.errors[0].param);
168
- const effectiveInput = prepared.input;
169
- const params = prepareQuoteParameters(rule, entry, effectiveInput, options.pricingParameters, options.mediaSeconds, true);
170
- const declared = new Set((rule.parameters ?? []).map(p => p.name)), ids = new Set();
325
+ /** The rule's components for these parameters: each subtotal rounded and at least its minimum, times count. */
326
+ function chargeComponents(rule, declared, params, images, missing) {
171
327
  const components = [];
328
+ const ids = new Set();
172
329
  let total = 0n;
173
- const missing = new Set();
174
- const searchCharges = searchUsage(entry, effectiveInput).filter(search => search.enabled).map(search => {
175
- const component = rule.components.find(item => item.role === search.role);
176
- if (!declared.has(search.parameter) || !component || component.pricing_status !== 'available' || component.unit !== 'search'
177
- || component.billing_unit_size !== 1 || component.tiers.length) {
178
- fail('search_pricing_unavailable', 'The enabled search unit price could not be verified. Refresh pricing before generation.');
179
- }
180
- const expected = options.pricingParameters?.[search.parameter] !== undefined || effectiveInput[search.parameter] !== undefined;
181
- if (!expected)
182
- missing.add(search.parameter);
183
- return { role: search.role, input_parameter: search.input_parameter, usage_parameter: search.parameter,
184
- assumed_count: String(params[search.parameter]), assumption: expected ? 'expected_usage' : 'zero_searches',
185
- actual_count_known: false, unit: 'search', unit_price_amounts: amountsForUC(component.rate.uc) };
186
- });
187
330
  for (const c of rule.components) {
188
331
  if (ids.has(c.id) || !c.quantity_rule || !c.rounding)
189
332
  fail('invalid_pricing_expression', 'The pricing rule is incomplete or has duplicate components.');
@@ -215,30 +358,136 @@ export function calculateRulesEstimate(body, entry, input, options = {}) {
215
358
  const charge = cmp(subtotal, minimum) < 0 ? minimum : subtotal;
216
359
  if (charge.d !== 1n || charge.n < 0n || charge.n > BigInt(Number.MAX_SAFE_INTEGER))
217
360
  fail('invalid_pricing_expression', 'The pricing rule does not produce a supported integer UC charge.');
218
- total += charge.n;
219
- components.push({ id: c.id, sku_id: selected.sku_id, quantity: exact(q), billed_quantity: exact(billed),
220
- subtotal_uc: String(charge.n), minimum_charge_applied: cmp(subtotal, minimum) < 0 });
361
+ total += charge.n * images;
362
+ components.push({ id: c.id, sku_id: selected.sku_id, quantity: exact(mul(q, rat(images))), billed_quantity: exact(mul(billed, rat(images))),
363
+ subtotal_uc: String(charge.n * images), minimum_charge_applied: cmp(subtotal, minimum) < 0 });
221
364
  }
222
365
  catch (error) {
223
- if (error instanceof QuoteError && error.code === 'quote_usage_required' && error.param)
366
+ if (error instanceof QuoteError && error.code === 'quote_usage_required' && error.param) {
224
367
  missing.add(error.param);
368
+ // The evaluator stops at the first absent usage; name every one this component reads.
369
+ for (const name of componentReads(c))
370
+ if (!Object.hasOwn(params, name))
371
+ missing.add(name);
372
+ }
225
373
  else
226
374
  throw error;
227
375
  }
228
376
  }
377
+ return { components, total };
378
+ }
379
+ /** The most inputs one estimate_cost or generate_* call takes (`inputs`), all for one model. */
380
+ export const MAX_BATCH_ITEMS = 50;
381
+ /** `batch_items` marks an approval of a whole batch (inputs); it never approves a single input, nor the reverse. */
382
+ export const ApprovedRulesEstimate = z.object({ source: z.literal('pricing_rules'), price_scope: z.literal('public_default'),
383
+ model_id: z.string().min(1).max(100), request_hash: z.string().regex(/^[a-f0-9]{64}$/),
384
+ fingerprint: z.string().regex(/^[a-f0-9]{64}$/), total_uc: z.string().max(32).regex(/^\d+$/),
385
+ expires_at: z.string().datetime({ offset: true }), batch_items: z.number().int().min(1).max(MAX_BATCH_ITEMS).optional() }).strict();
386
+ function economicRules(rule) {
387
+ // Freshness and configuration timestamps do not change the approved price.
388
+ return { ...rule, components: rule.components.map(({ effective_at, official_rate, ...c }) => ({ ...c,
389
+ tiers: c.tiers.map(({ effective_at, official_rate, ...t }) => t) })) };
390
+ }
391
+ /** countPromptTokens replaces the approximate prompt token count, for comparing with the gateway's exact count. */
392
+ export function calculateRulesEstimate(body, entry, input, options = {}) {
393
+ const rule = 'model' in body ? body.model : body.models.find(model => model.model_id === entry.id);
394
+ if (!rule || rule.model_id !== entry.id.toLowerCase() || rule.modality !== entry.kind || rule.policy_source !== 'published' || rule.pricing_status !== 'available') {
395
+ fail('pricing_rules_unavailable', 'This model has no available published media pricing policy.');
396
+ }
397
+ const prepared = prepareSeedanceInput(entry, input);
398
+ if (prepared.errors.length)
399
+ throw new QuoteError('invalid_quote_parameter', `${prepared.errors[0].param} ${prepared.errors[0].problem}`, prepared.errors[0].param);
400
+ const effectiveInput = prepared.input;
401
+ const declared = new Set((rule.parameters ?? []).map(p => p.name));
402
+ const id = entry.id.toLowerCase();
403
+ // GPT Image and Gemini Omni token models never use token counts from pricing_parameters: the reference counts what
404
+ // the gateway reserves for this input. Leaving them out of the request hash lets a generation pass them or not.
405
+ const ignored = isTokenImageModel(id) || isOmniTokenModel(id)
406
+ ? Object.keys(options.pricingParameters ?? {}).filter(name => declared.has(name) && (/tokens$/.test(name) || svgAuthor(name))).sort() : [];
407
+ const pricingParameters = ignored.length
408
+ ? Object.fromEntries(Object.entries(options.pricingParameters).filter(([name]) => !ignored.includes(name))) : options.pricingParameters;
409
+ const reserved = reservation(rule, entry, effectiveInput, options.countPromptTokens, options.mediaSeconds);
410
+ const params = { ...prepareQuoteParameters(rule, entry, effectiveInput, pricingParameters, options.mediaSeconds, true), ...reserved?.parameters };
411
+ // The gateway rounds each image's charge up separately, then reserves it once per image.
412
+ const images = BigInt(reserved?.gpt?.images ?? 1);
413
+ const missing = new Set();
414
+ // An Omni input video is billed by its length, which only media_seconds gives before submission.
415
+ if (reserved?.needs)
416
+ missing.add('media_seconds');
417
+ const searchCharges = searchUsage(entry, effectiveInput).filter(search => search.enabled).map(search => {
418
+ const component = rule.components.find(item => item.role === search.role);
419
+ if (!declared.has(search.parameter) || !component || component.pricing_status !== 'available' || component.unit !== 'search'
420
+ || component.billing_unit_size !== 1 || component.tiers.length) {
421
+ fail('search_pricing_unavailable', 'The enabled search unit price could not be verified. Refresh pricing before generation.');
422
+ }
423
+ const expected = options.pricingParameters?.[search.parameter] !== undefined || effectiveInput[search.parameter] !== undefined;
424
+ if (!expected)
425
+ missing.add(search.parameter);
426
+ return { role: search.role, input_parameter: search.input_parameter, usage_parameter: search.parameter,
427
+ assumed_count: String(params[search.parameter]), assumption: expected ? 'expected_usage' : 'zero_searches',
428
+ actual_count_known: false, unit: 'search', unit_price_amounts: amountsForUC(component.rate.uc) };
429
+ });
430
+ const { components, total } = reserved?.needs ? { components: [], total: 0n } : chargeComponents(rule, declared, params, images, missing);
229
431
  if (total > BigInt(Number.MAX_SAFE_INTEGER))
230
432
  fail('invalid_pricing_expression', 'The estimated charge exceeds its supported range.');
231
- const amounts = amountsForUC(String(total)), requestHash = quoteRequestHash(entry.id, effectiveInput, options.mediaSeconds, options.pricingParameters);
433
+ // No media generation is free. A total of 0 comes only from usage given as 0, which then counts as missing, so
434
+ // nothing is quoted; if no usage explains it, the published rules themselves price the input at 0.
435
+ const zeroUsage = total === 0n ? [...declared].filter(name => isUsageParameter(entry.id, name) && pricingParameters?.[name] !== undefined
436
+ && /^\d+(?:\.\d+)?$/.test(String(params[name])) && compareDecimal(String(params[name]), '0') === 0
437
+ && rule.components.some(c => componentReads(c).has(name))) : [];
438
+ if (total === 0n) {
439
+ if (!zeroUsage.length && !missing.size)
440
+ fail('pricing_rules_unavailable', 'The published rules price this input at 0, and no media generation is free, so it cannot be quoted.');
441
+ for (const name of zeroUsage)
442
+ missing.add(name);
443
+ components.length = 0;
444
+ }
445
+ const amounts = amountsForUC(String(total)), requestHash = quoteRequestHash(entry.id, effectiveInput, options.mediaSeconds, pricingParameters);
232
446
  const approval = { source: 'pricing_rules', price_scope: 'public_default', model_id: entry.id,
233
447
  request_hash: requestHash, total_uc: amounts.uc, expires_at: new Date(Date.now() + APPROVAL_TTL_MS).toISOString(),
234
448
  fingerprint: quoteRequestHash(entry.id, { rules: economicRules(rule), parameters: params,
235
- exchange_rate_version: body.meta.exchange_rate_version, components, missing: [...missing].sort(), total_uc: amounts.uc }) };
236
- const estimate = { status: missing.size ? components.length ? 'partial' : 'needs_input' : 'estimated', min_usd: Number(amounts.usd), max_usd: Number(amounts.usd),
237
- min_credits: Number(amounts.credits), max_credits: Number(amounts.credits),
238
- basis: ['Published full pricing rules evaluated for the supplied generation parameters; exact UC rounding and component minimums.'],
239
- ...(missing.size ? { uncheckable_reason: 'usage' } : {}),
240
- possible_extras: [...missing].map(name => `Additional charge depends on ${name}; supply expected or measured usage in pricing_parameters.`), notes: ['Public default prices; account discounts are not included.',
241
- 'Confirm the estimated cost before generation. Actual billed usage and final charges may differ.'] };
449
+ exchange_rate_version: body.meta.exchange_rate_version, components, missing: [...missing].sort(), total_uc: amounts.uc,
450
+ ...(reserved?.gpt || reserved?.omni ? { reservation: reserved.gpt ?? reserved.omni } : {}) }) };
451
+ const status = missing.size ? components.length ? 'partial' : 'needs_input'
452
+ : reserved?.gpt || reserved?.omni ? 'token_billed' : 'estimated';
453
+ const missingUsage = [...missing].sort(), usageHelp = helpLines(missingUsage, entry, rule, declared);
454
+ const usage = reserved?.gpt, omni = reserved?.omni;
455
+ // An Omni input video of unknown resolution counts the highest; the same input at a lower one, for the notes.
456
+ const lowerTier = omni && status === 'token_billed' ? omniLowerInputTier(omni) : undefined;
457
+ let lower;
458
+ if (omni && lowerTier) {
459
+ const alternative = omniReservation(id, effectiveInput, options.mediaSeconds, { countPromptTokens: options.countPromptTokens, inputTier: lowerTier });
460
+ const cost = 'needs' in alternative ? undefined : chargeComponents(rule, declared, { ...params, ...omniParameters(rule, alternative) }, 1n, new Set()).total;
461
+ if (cost !== undefined && cost < total)
462
+ lower = { tier: lowerTier, amounts: amountsForUC(String(cost)) };
463
+ }
464
+ const estimate = { status,
465
+ // Nothing could be priced: a zero amount would read as free.
466
+ ...(status === 'needs_input' ? {} : { min_usd: Number(amounts.usd), max_usd: Number(amounts.usd),
467
+ min_credits: Number(amounts.credits), max_credits: Number(amounts.credits) }),
468
+ total_known: status === 'estimated',
469
+ basis: [status === 'token_billed' && usage
470
+ ? `Reference price: published token rates applied to what EvoLink reserves at submission for this input. Per image: ${usage.per_image.image_output_tokens.toLocaleString('en-US')} output tokens (${usage.output.width}×${usage.output.height}${usage.output.gif ? `, ${usage.output.gif.frames} GIF frames` : ''}, quality ${usage.output.quality}), about ${usage.per_image.text_input_tokens.toLocaleString('en-US')} prompt tokens and ${usage.per_image.image_input_tokens.toLocaleString('en-US')} reference-image tokens, each part rounded up; ${usage.images} image${usage.images > 1 ? 's' : ''}.`
471
+ : status === 'token_billed' && omni ? omniBasis(omni)
472
+ : 'Published full pricing rules evaluated for the supplied generation parameters; exact UC rounding and component minimums.'],
473
+ ...(missing.size ? { uncheckable_reason: 'usage', missing_usage: missingUsage, usage_help: usageHelp } : {}),
474
+ ...(status === 'token_billed' && usage ? { reference_usage: usage } : {}),
475
+ ...(status === 'token_billed' && omni ? { reference_usage: { ...omni, ...(lower ? { lower_input: { resolution: lower.tier, amounts: lower.amounts } } : {}) } } : {}),
476
+ possible_extras: status === 'partial' ? usageHelp.map(line => `Additional charge depends on ${line}`) : [],
477
+ notes: ['Public default prices; account discounts are not included.', ...status === 'needs_input'
478
+ ? ['No total is quoted until the missing usage is known, and generate_* will not submit before then.']
479
+ : status === 'token_billed' && usage ? reservationNotes(usage, ignored)
480
+ : status === 'token_billed' && omni ? omniNotes(omni, ignored, lower)
481
+ : ['Confirm the estimated cost before generation. Actual billed usage and final charges may differ.']] };
482
+ if (zeroUsage.length)
483
+ estimate.notes.push(`pricing_parameters ${zeroUsage.join(', ')} given as 0 would price this generation at 0. No media generation is free, so ${zeroUsage.length > 1 ? 'they count' : 'it counts'} as missing.`);
484
+ if (ignored.length && status !== 'token_billed')
485
+ estimate.notes.push(`pricing_parameters ${ignored.join(', ')} ${ignored.length > 1 ? 'are' : 'is'} not used for this model.`);
486
+ for (const p of rule.parameters ?? []) {
487
+ const assumed = CONSERVATIVE_QUOTE_PARAMETERS[`${entry.id.toLowerCase()} ${p.name}`];
488
+ if (assumed && options.pricingParameters?.[p.name] === undefined)
489
+ estimate.notes.push(assumed.note);
490
+ }
242
491
  if (searchCharges.length) {
243
492
  estimate.search_charges = searchCharges;
244
493
  for (const search of searchCharges) {
@@ -251,17 +500,85 @@ export function calculateRulesEstimate(body, entry, input, options = {}) {
251
500
  }
252
501
  return { approval, estimate, amounts, components, parameters: params, rule };
253
502
  }
503
+ /** While the platform limits pricing requests, an estimate may use rules read this recently; generation never does. */
504
+ export const RECENT_RULES_MAX_AGE_MS = 10 * 60_000;
505
+ /** The longest Retry-After a generation waits, once, before its fresh rules read gives up. */
506
+ export const GENERATION_RULES_RETRY_MAX_SECONDS = 5;
507
+ /** Generation takes a model's rules read this recently (and still fresh), so a batch of submissions reads them once. */
508
+ export const GENERATION_RULES_REUSE_MS = 10_000;
509
+ const limited = (error) => error instanceof PricingRulesError && error.code === 'rate_limit_exceeded';
510
+ function pause(ms, signal) {
511
+ return new Promise(resolve => {
512
+ const timer = setTimeout(done, ms);
513
+ function done() { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); }
514
+ signal?.addEventListener('abort', done, { once: true });
515
+ if (signal?.aborted)
516
+ done();
517
+ });
518
+ }
519
+ async function generationRules(model, signal) {
520
+ try {
521
+ return (await getPricingRules({ model, view: 'full' }, { fresh: true, maxAgeMs: GENERATION_RULES_REUSE_MS })).body;
522
+ }
523
+ catch (error) {
524
+ const wait = limited(error) ? error.retryAfter ?? 1 : undefined;
525
+ if (wait === undefined || wait > GENERATION_RULES_RETRY_MAX_SECONDS || signal?.aborted)
526
+ throw error;
527
+ await pause(wait * 1000, signal);
528
+ if (signal?.aborted)
529
+ throw error;
530
+ return (await getPricingRules({ model, view: 'full' }, { fresh: true, maxAgeMs: GENERATION_RULES_REUSE_MS })).body;
531
+ }
532
+ }
533
+ /**
534
+ * The rules an estimate or a generation evaluates. Generation reads them fresh, or takes them from a read in the last
535
+ * 10 seconds. A hosted estimate (`reuseRules`) reuses them until their fresh_until and, while the platform limits
536
+ * requests, may use rules read in the last 10 minutes (`readAt`); any other estimate reads them fresh. A batch reads
537
+ * them once for all its inputs.
538
+ */
539
+ export async function readPricingRulesFor(entry, options = {}) {
540
+ const model = entry.id.toLowerCase();
541
+ if (options.purpose === 'generation')
542
+ return { body: await generationRules(model, options.signal) };
543
+ if (!options.reuseRules)
544
+ return { body: (await getPricingRules({ model, view: 'full' }, { fresh: true })).body };
545
+ try {
546
+ return { body: (await getPricingRules({ model, view: 'full' }, { reuseUntilFresh: true })).body };
547
+ }
548
+ catch (error) {
549
+ const recent = limited(error) ? recentModelRules(model, RECENT_RULES_MAX_AGE_MS) : undefined;
550
+ if (!recent)
551
+ throw error;
552
+ return { body: recent.body, readAt: new Date(recent.fetchedAt).toISOString() };
553
+ }
554
+ }
555
+ /** Said with an estimate made from rules read earlier, while the platform limits pricing requests. */
556
+ export function recentRulesNote(readAt) {
557
+ return `The platform is limiting pricing requests right now, so this estimate uses the published rules read at ${readAt}. generate_* reads the current rules again before submitting and asks for a new approval if the price changed.`;
558
+ }
559
+ /** An approval from cached or recent rules can never submit at a changed price: checkRulesApproval refuses it. */
254
560
  export async function createRulesEstimate(entry, input, options = {}) {
255
- const { body } = await getPricingRules({ model: entry.id.toLowerCase(), view: 'full' }, { fresh: true });
256
- return calculateRulesEstimate(body, entry, input, options);
561
+ const { body, readAt } = await readPricingRulesFor(entry, options);
562
+ const result = calculateRulesEstimate(body, entry, input, options);
563
+ if (!readAt)
564
+ return result;
565
+ result.estimate.notes.push(recentRulesNote(readAt));
566
+ return { ...result, rules_read_at: readAt };
257
567
  }
568
+ /**
569
+ * An approval holds for the same input at the same price. Past its expires_at it still holds when neither changed
570
+ * (`expired: true`, for the result to say so); a changed input or price needs a new estimate and approval.
571
+ */
258
572
  export function checkRulesApproval(approval, fresh) {
259
- if (Date.parse(approval.expires_at) <= Date.now())
260
- fail('quote_expired', 'The approved estimate expired. Estimate again and obtain approval.');
573
+ const expired = Date.parse(approval.expires_at) <= Date.now();
574
+ if (approval.batch_items !== undefined) {
575
+ fail('quote_input_changed', 'This pricing_quote approves a batch (inputs); pass the same inputs, or estimate this input and obtain approval.');
576
+ }
261
577
  if (approval.request_hash !== fresh.approval.request_hash || approval.model_id !== fresh.approval.model_id) {
262
578
  fail('quote_input_changed', 'The generation input differs from the approved estimate.');
263
579
  }
264
580
  if (approval.fingerprint !== fresh.approval.fingerprint || approval.total_uc !== fresh.approval.total_uc) {
265
581
  fail('price_changed', 'The pricing rules or estimated price changed. Estimate again and obtain approval.');
266
582
  }
583
+ return { expired };
267
584
  }
@@ -4,13 +4,35 @@
4
4
  export const PAID_GENERATION_GUIDANCE = [
5
5
  'Before each new paid generation, call estimate_cost with the exact model and input, then use the generation confirmation template in the server instructions.',
6
6
  'If the estimate is partial or unavailable, explain what is not covered or that the final cost is unknown.',
7
- 'End the reply and wait for the user to explicitly approve that quoted task before calling a generate tool.',
7
+ 'End the reply and wait for the user to explicitly approve that quoted task before calling a generate tool, unless the user opted out (skip_estimate).',
8
8
  'You may proceed under a prior explicit approval only when the user specified the task or batch scope and a spending budget that still covers this request; track the remaining budget.',
9
9
  'Your own suggested budget, a model recommendation, sufficient balance or a general request to generate is not spending approval.',
10
10
  'Show estimated cost and ask for approval. Do not derive max_cost_usd from a quote; compare only an explicit user budget, without promising a final charge.',
11
11
  'A new variation, regeneration or retry after a failed task is a new paid generation and needs approval unless that explicit batch approval covers it.',
12
12
  'Never remove or raise a user spending cap without their explicit approval.',
13
13
  ].join(' ');
14
+ /**
15
+ * When the user opts out of estimates. The server instructions carry it in full; a generate tool's description only
16
+ * points to skip_estimate, since each description must stay short.
17
+ */
18
+ export const ESTIMATE_OPT_OUT_GUIDANCE = [
19
+ 'Exception: when the user explicitly says not to estimate or not to confirm (for example "generate directly", "no need to estimate", "stop asking", "from now on just generate"), skip estimate_cost and the confirmation and pass skip_estimate: true, within the scope the user gave: this task, this batch, or every later generation in this conversation; if the scope is unclear, only this task. Never infer it from silence, the balance or your own suggestion.',
20
+ 'When the user opts out for the rest of the conversation, tell them once, clearly, that later generations in this conversation will be submitted without asking, and that they can start a new conversation or ask you to restore estimates to bring them back.',
21
+ 'If estimate_cost fails for a reason other than invalid input, generate with skip_estimate: true when the user has opted out; otherwise ask once, in one sentence, whether to generate anyway with the cost settled by actual usage, and on yes use skip_estimate: true.',
22
+ 'skip_estimate does not set aside an explicit user budget, does not approve enabling model web or image search, and does not change what is charged; after submitting, tell the user what was reserved or charged.',
23
+ 'A pricing_quote that expired keeps its approval while the input and price are unchanged; a changed price needs a new estimate and approval.',
24
+ ].join(' ');
25
+ /** How to submit several tasks: clients run paid tool calls one at a time, so one call per task and the wait for each result are what to avoid. */
26
+ export const BATCH_GENERATION_GUIDANCE = [
27
+ 'For several images or tasks of one model, pass inputs (up to 50 items, each like input) to estimate_cost and then, with its pricing_quote, to the generate tool: one estimate, one approval for the batch total, and one call that submits every item at once and returns each task_id right away.',
28
+ 'For tasks of different models, submit one task per item with wait_seconds: 0.',
29
+ 'Either way, collect the results with list_tasks (task_ids, up to 50 per call; free and read-only, so these calls can run in parallel), and tell the user the tasks generate at the same time.',
30
+ 'Do not rely on n for the count: some models, such as GPT Image, often return fewer images than n.',
31
+ 'To finish a batch, call the generate tool again with the same client_request_id and exactly the same inputs within 24 hours: the items its 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.',
32
+ 'For an item with an unknown outcome, retry later the same way or check list_tasks.',
33
+ 'Never resubmit accepted, not-submitted or unknown-outcome items under a new client_request_id: that creates and charges new tasks.',
34
+ 'An item refused because it differs from what that client_request_id submitted earlier is a new task: it needs a new estimate, approval and client_request_id.',
35
+ ].join(' ');
14
36
  /** Shared confirmation wording; approval and spending rules above still apply. */
15
37
  export const GENERATION_CONFIRMATION_GUIDANCE = [
16
38
  'When spending approval is needed, use the following layout in English by default unless the user explicitly requests another language. Fill it from the exact model and input checked by `estimate_cost`; summarize the content in one sentence. Render normal text and bullets; the code blocks below only illustrate the layout.',
@@ -43,9 +65,10 @@ export const GENERATION_CONFIRMATION_GUIDANCE = [
43
65
  '- For a complete estimate, show the returned amount or range in credits and approximate USD. Label it as an estimate, not a guaranteed final charge.',
44
66
  '- Do not add a separate estimated cap or max_cost_usd to the default confirmation. If the user specified a budget, state whether the estimate fits it; pause if it exceeds the budget. A budget comparison does not limit the final settlement.',
45
67
  '- For a partial estimate, label it "部分估价" / "Partial estimate", state what is excluded, and say it is neither the total nor an upper bound.',
68
+ '- For a batch (inputs), use one confirmation for the whole batch: in Output give the number of items and what differs between them, and in Cost the total plus the price per item, or the range when items differ. One approval covers exactly that batch.',
46
69
  '- Keep model web and image search off unless the user explicitly requests or approves enabling it. Never enable search on your own or just because a copied example enables it. If you think search is needed, first explain its extra per-search rates and unknown total, end the reply, and wait for explicit user consent before enabling it. Approval of a task without search does not authorize adding search; changed search settings require a fresh estimate and approval.',
47
70
  '- When search_charges is returned, disclose each enabled search type and its per-search rate before generation approval, even when the user requested search. A zero-search subtotal excludes unknown search fees; one task may search multiple times or not at all. Expected counts are assumptions, not execution limits. Actual counts depend on the task and model strategy. Do not add a search-fee warning when search is off.',
48
- '- For token billing, say "按实际 token 用量计费,生成前无法确定总价" / "Billed by actual token usage; the total is unknown before generation." Include the applicable published unit rates when returned. If no price is available, say so rather than assuming token billing.',
71
+ '- For a token_billed estimate, show the reference price in credits and approximate USD and say "参考价 {积分}(约 {美元}),按实际 token 用量结算,完成后多退少补,实际可能更低或略高" / "Reference price {credits} (about {USD}); billed by actual token usage and settled when the task finishes, so the final charge may be lower or slightly higher." When size is auto (except a GIF, whose frames have a fixed size), add that setting a size gives a closer reference price. For a Gemini Omni video with an input or reference video, pass its length as media_seconds; the reference counts that video at the highest resolution (4k), so also show the lower-resolution price the estimate gives. If an estimate still needs token usage, say "按实际 token 用量计费,生成前无法确定总价" / "Billed by actual token usage; the total is unknown before generation." and include the applicable published unit rates when returned. If no price is available, say so rather than assuming token billing.',
49
72
  '- If the user set a fixed cap that cannot be checked, explain that gap and replace the usual closing with an explicit question about proceeding without that cap. Do not treat a generic "Confirm generation" as consent to remove or raise a cap.',
50
73
  '- The suggested confirmation phrase is not a required command; any clear approval of the quoted task is valid. Existing task or batch approval still follows the spending approval rules; do not ask again when it already covers this request.',
51
74
  '- Keep routine explanations about the task and cost, for example "这次生成需要确认费用" / "Please confirm the cost for this generation." Do not add skill paths, filenames or quoted internal rules to routine confirmations unless the user asks or higher-priority host instructions require them.',