Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

extract-fal-pricing.test.ts

774 lines24.3 KB

1import { describe, expect, it, vi } from 'vitest'
2import type { Mock } from 'vitest'
3​
4import { verifyExamples } from '@modelschemas/rate-card'
5​
6import { NANO_BANANA_2 } from '../../../packages/rate-card/src/fixtures/nano-banana-2.ts'
7​
8import {
9 FAL_PRICING_EXTRACT_CRONS,
10 FAL_PRICING_EXTRACT_CAP,
11 FAL_PRICING_EXTRACT_MODEL,
12 FAL_PRICING_FETCH_CAP,
13 FAL_PRICING_FETCH_FAIL_ABORT,
14 EXTRACT_SYSTEM,
15 checkExtractedCard,
16 isRetryableLlmsStatus,
17 extractRateCard,
18 gatewayChat,
19 isStubPricingSection,
20 pricingSection,
21 pricingSectionHash,
22 resumeIndex,
23 shouldSkipExtract,
24} from './extract-fal-pricing.ts'
25import { parseFalUnitRate } from './fal-unit-rate.ts'
26import { SPEC_SYNC_SHARD_CRONS } from './sync.ts'
27​
28type RunMock = Mock<
29 (
30 model: string,
31 inputs: Record<string, unknown>,
32 options: Record<string, unknown>,
33 ) => Promise<Response>
35​
36/** Gateway `run` answering successive chat calls with these contents. */
37function gatewayReplies(...replies: Array<unknown>): RunMock {
38 const mock: RunMock = vi.fn()
39 for (const reply of replies) {
40 const content = typeof reply === 'string' ? reply : JSON.stringify(reply)
41 mock.mockResolvedValueOnce(sseReply(content))
42 }
43 return mock
45​
46/** A streamed Anthropic Messages reply, as the gateway returns it. */
47function sseReply(text: string): Response {
48 const events: Array<[string, unknown]> = [
49 [
50 'message_start',
51 {
52 type: 'message_start',
53 message: {
54 id: 'msg_test',
55 type: 'message',
56 role: 'assistant',
57 model: FAL_PRICING_EXTRACT_MODEL,
58 content: [],
59 stop_reason: null,
60 usage: { input_tokens: 1, output_tokens: 0 },
61 },
62 },
63 ],
64 [
65 'content_block_start',
66 {
67 type: 'content_block_start',
68 index: 0,
69 content_block: { type: 'text', text: '' },
70 },
71 ],
72 [
73 'content_block_delta',
74 {
75 type: 'content_block_delta',
76 index: 0,
77 delta: { type: 'text_delta', text },
78 },
79 ],
80 ['content_block_stop', { type: 'content_block_stop', index: 0 }],
81 [
82 'message_delta',
83 {
84 type: 'message_delta',
85 delta: { stop_reason: 'end_turn' },
86 usage: { output_tokens: 1 },
87 },
88 ],
89 ['message_stop', { type: 'message_stop' }],
90 ]
91 const body = events
92 .map(
93 ([event, data]) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`,
94 )
95 .join('')
96 return new Response(body, {
97 headers: { 'content-type': 'text/event-stream' },
98 })
100​
101/** `env.AI` with only `run` doing anything. */
102function fakeAi(run: RunMock): Ai {
103 return { run } as unknown as Ai
105​
106/** The Anthropic Messages body of call `n`. */
107function runInput(
108 run: RunMock,
109 n: number,
110): {
111 system?: unknown
112 messages: Array<{ role: string; content: unknown }>
113} {
114 return run.mock.calls[n]?.[1] as {
115 messages: Array<{ role: string; content: unknown }>
116 }
118​
119/** A message's text, whether sent as a string or as content blocks. */
120function textOf(content: unknown): string {
121 return typeof content === 'string' ? content : JSON.stringify(content)
123​
124const NANO_LLMS = `# Nano Banana 2
125​
126## Overview
127​
128- **Endpoint**: \`https://fal.run/fal-ai/nano-banana-2\`
129​
130## Pricing
131​
132Your request will cost **$0.08** per image. For **$1.00**, you can run this model **12** times. 2K and 4K outputs will be charged at **1.5** times and **2** times the standard rate, respectively. 0.5K (512px) resolution outputs will be charged at **0.75** times the standard rate. If web search is used, an additional $0.015 will be charged. If high thinking is used, an additional $0.002 will be charged. **Note: Pricing is subject to change.**
133​
134For more details, see [fal.ai pricing](https://fal.ai/pricing).
135​
136## API Information
137​
138This model can be used via our HTTP API.
140​
141describe('pricingSection', () => {
142 it('cuts the Pricing heading from llms.txt and ignores sibling sections', () => {
143 const section = pricingSection(NANO_LLMS)
144 expect(section.startsWith('## Pricing')).toBe(true)
145 expect(section).toContain('$0.08')
146 expect(section).not.toContain('API Information')
147 expect(section).not.toContain('Nano Banana 2 is')
148 })
149​
150 it('is empty when the heading is absent', () => {
151 expect(pricingSection('# Title\n\n## Overview\n\nNope.\n')).toBe('')
152 })
153})
154​
155describe('isStubPricingSection', () => {
156 it('treats empty, boilerplate, and zero-dollar sections as stubs', () => {
157 expect(isStubPricingSection('')).toBe(true)
158 expect(
159 isStubPricingSection(
160 '## Pricing\n\nFor more details, see [fal.ai pricing](https://fal.ai/pricing).',
161 ),
162 ).toBe(true)
163 expect(
164 isStubPricingSection(
165 '## Pricing\n\nYour request will cost **$0.00** per image.',
166 ),
167 ).toBe(true)
168 })
169​
170 it('keeps a section that names a positive price', () => {
171 expect(isStubPricingSection(pricingSection(NANO_LLMS))).toBe(false)
172 })
173​
174 it('keeps bold and suffix-$ prices the old regex missed (#70)', () => {
175 expect(isStubPricingSection('- **Price**: $**0.04** per images')).toBe(
176 false,
177 )
178 expect(isStubPricingSection('- **Price**: **0.17** $ per second')).toBe(
179 false,
180 )
181 })
182})
183​
184describe('pricingSectionHash', () => {
185 it('hashes the Pricing section, not the rest of the file', async () => {
186 const a = await pricingSectionHash(pricingSection(NANO_LLMS))
187 const b = await pricingSectionHash(
188 pricingSection(NANO_LLMS.replace('Nano Banana 2', 'Renamed')),
189 )
190 const c = await pricingSectionHash(
191 pricingSection(NANO_LLMS.replace('$0.08', '$0.09')),
192 )
193 expect(a).toMatch(/^[0-9a-f]{64}$/)
194 expect(a).toBe(b)
195 expect(c).not.toBe(a)
196 })
197})
198​
199describe('resumeIndex', () => {
200 const ids = ['a/one', 'b/two', 'c/three']
201​
202 it('starts at 0 with no cursor and wraps past the tail', () => {
203 expect(resumeIndex(ids, null)).toBe(0)
204 expect(resumeIndex(ids, 'c/three')).toBe(0)
205 expect(resumeIndex(ids, 'b/two')).toBe(2)
206 })
207​
208 it('resumes after a cursor that left the roster', () => {
209 expect(resumeIndex(ids, 'a/two')).toBe(1)
210 expect(resumeIndex(ids, 'z/gone')).toBe(0)
211 })
212})
213​
214describe('shouldSkipExtract', () => {
215 const hash = 'a'.repeat(64)
216 const now = 1_781_150_000
217​
218 it('skips an unchanged hash and re-extracts after expiresAt', () => {
219 expect(
220 shouldSkipExtract({
221 storedHash: hash,
222 sectionHash: hash,
223 hasCard: true,
224 stub: false,
225 expiresAt: undefined,
226 now,
227 }),
228 ).toBe(true)
229 expect(
230 shouldSkipExtract({
231 storedHash: hash,
232 sectionHash: 'b'.repeat(64),
233 hasCard: true,
234 stub: false,
235 expiresAt: undefined,
236 now,
237 }),
238 ).toBe(false)
239 expect(
240 shouldSkipExtract({
241 storedHash: hash,
242 sectionHash: hash,
243 hasCard: true,
244 stub: false,
245 expiresAt: '2020-01-01T00:00:00.000Z',
246 now,
247 }),
248 ).toBe(false)
249 expect(
250 shouldSkipExtract({
251 storedHash: hash,
252 sectionHash: hash,
253 hasCard: true,
254 stub: false,
255 expiresAt: '2099-01-01T00:00:00.000Z',
256 now,
257 }),
258 ).toBe(true)
259 })
260​
261 it('retries an unchanged hash whose card is still null unless it is a stub (#84)', () => {
262 const base = { storedHash: hash, sectionHash: hash, expiresAt: undefined }
263 expect(
264 shouldSkipExtract({ ...base, hasCard: false, stub: false, now }),
265 ).toBe(false)
266 expect(
267 shouldSkipExtract({ ...base, hasCard: false, stub: true, now }),
268 ).toBe(true)
269 })
270})
271​
272describe('FAL_PRICING_EXTRACT_CRONS', () => {
273 it('is six hourly daytime shards, none of them a spec-sync shard', () => {
274 expect([...FAL_PRICING_EXTRACT_CRONS]).toEqual([
275 '0 6 * * *',
276 '0 7 * * *',
277 '0 8 * * *',
278 '0 9 * * *',
279 '0 10 * * *',
280 '0 11 * * *',
281 ])
282 expect(FAL_PRICING_FETCH_CAP).toBe(250)
283 expect(FAL_PRICING_EXTRACT_CAP).toBe(40)
284 expect(FAL_PRICING_FETCH_FAIL_ABORT).toBe(8)
285 expect(FAL_PRICING_EXTRACT_MODEL).toBe('claude-sonnet-5-5')
286 for (const cron of FAL_PRICING_EXTRACT_CRONS) {
287 expect(
288 (SPEC_SYNC_SHARD_CRONS as ReadonlyArray<string>).includes(cron),
289 ).toBe(false)
290 expect(cron).not.toBe('*/15 * * * *')
291 }
292 // Six shards x 250 fetches covers the FAL roster in one calendar day.
293 expect(
294 FAL_PRICING_EXTRACT_CRONS.length * FAL_PRICING_FETCH_CAP,
295 ).toBeGreaterThanOrEqual(1500)
296 })
297​
298 it('keeps wrangler.jsonc in lockstep', async () => {
299 const fs = await import('node:fs/promises')
300 const raw = await fs.readFile('wrangler.jsonc', 'utf8')
301 for (const cron of FAL_PRICING_EXTRACT_CRONS) {
302 expect(raw).toContain(`"${cron}"`)
303 }
304 expect(raw).toContain('"*/15 * * * *"')
305 for (const cron of SPEC_SYNC_SHARD_CRONS) {
306 expect(raw).toContain(`"${cron}"`)
307 }
308 })
309})
310​
311describe('isRetryableLlmsStatus', () => {
312 it('retries network, 408, 429, and 5xx; 404 is done', () => {
313 expect(isRetryableLlmsStatus(0)).toBe(true)
314 expect(isRetryableLlmsStatus(408)).toBe(true)
315 expect(isRetryableLlmsStatus(429)).toBe(true)
316 expect(isRetryableLlmsStatus(500)).toBe(true)
317 expect(isRetryableLlmsStatus(503)).toBe(true)
318 expect(isRetryableLlmsStatus(404)).toBe(false)
319 expect(isRetryableLlmsStatus(400)).toBe(false)
320 })
321})
322​
323type ExtractArgs = Omit<Parameters<typeof extractRateCard>[0], 'chat'>
324​
325function extract(args: ExtractArgs, run: RunMock) {
326 return extractRateCard({ ...args, chat: gatewayChat(fakeAi(run), 'gw-test') })
328​
329async function extractError(
330 args: ExtractArgs,
331 run: RunMock,
332): Promise<string | null> {
333 const result = await extract(args, run)
334 return typeof result === 'object' && 'error' in result ? result.error : null
336​
337describe('extractRateCard through the gateway', () => {
338 const args = {
339 pricingText: pricingSection(NANO_LLMS),
340 requestProperties: new Set([
341 'num_images',
342 'resolution',
343 'enable_web_search',
344 'thinking_level',
345 ]),
346 sourceUrl: NANO_BANANA_2.source.url,
347 sourceHash: 'c'.repeat(64),
348 now: 1_781_150_000,
349 }
350 const { source: _source, ...body } = NANO_BANANA_2
351​
352 it('stamps source and accepts a verified card', async () => {
353 const run = gatewayReplies(body)
354 const card = await extract(args, run)
355 expect(card).not.toBe('unverified')
356 expect(card).not.toHaveProperty('error')
357 if (card === 'unverified' || 'error' in card) return
358 expect(card.source.hash).toBe(args.sourceHash)
359 expect(card.source.url).toBe(args.sourceUrl)
360 const [model, input, options] = run.mock.calls[0] ?? []
361 // Cloudflare's catalog id, not Anthropic's (#556).
362 expect(model).toBe('anthropic/claude-sonnet-5.5')
363 expect(options).toMatchObject({ gateway: { id: 'gw-test' } })
364 // Claude 5 400s on temperature (#550).
365 expect(input).not.toHaveProperty('temperature')
366 expect(textOf(runInput(run, 0).system)).toContain(
367 'You write a modelschemas RateCard',
368 )
369 })
370​
371 it('returns unverified only for a section that names no price', async () => {
372 const run = gatewayReplies({ unverified: true })
373 await expect(
374 extract(
375 {
376 ...args,
377 pricingText:
378 '## Pricing\n\nSee [fal.ai pricing](https://fal.ai/pricing).',
379 },
380 run,
381 ),
382 ).resolves.toBe('unverified')
383 expect(run).toHaveBeenCalledTimes(1)
384 })
385​
386 it('sends a priced section back once when the model says unverified (#88)', async () => {
387 const run = gatewayReplies({ unverified: true }, body)
388 const card = await extract(args, run)
389 expect(card).toMatchObject({ price: NANO_BANANA_2.price })
390 expect(run).toHaveBeenCalledTimes(2)
391 const retry = runInput(run, 1)
392 expect(retry.messages.map((m) => m.role)).toEqual([
393 'user',
394 'assistant',
395 'user',
396 ])
397 expect(textOf(retry.messages[2]?.content)).toContain('$0.08')
398 })
399​
400 const promoSection = `## Pricing
401​
402Limited-time promo (50% off) until **October 31, 2026**: speech costs **$0.015** per **1,000 characters** of input text (regular price: $0.03).`
403 const promoCard = {
404 inputs: {
405 characters: { param: 'characters', kind: 'number', bound: 'usage' },
406 },
407 tables: {},
408 price: { '*': [{ '/': [{ var: 'characters' }, 1000] }, 0.015] },
409 examples: [
410 {
411 params: { characters: 1000 },
412 usd: 0.015,
413 quote: 'speech costs **$0.015** per **1,000 characters**',
414 },
415 ],
416 expiresAt: '2026-10-31T23:59:59Z',
417 }
418 const { expiresAt: _promoEnd, ...regularCard } = {
419 ...promoCard,
420 price: { '*': [{ '/': [{ var: 'characters' }, 1000] }, 0.03] },
421 examples: [
422 {
423 params: { characters: 1000 },
424 usd: 0.03,
425 quote: 'regular price: $0.03',
426 },
427 ],
428 }
429​
430 it('keeps a promo card whose end is still ahead', async () => {
431 const run = gatewayReplies(promoCard)
432 const card = await extract({ ...args, pricingText: promoSection }, run)
433 expect(card).toMatchObject({ source: { expiresAt: promoCard.expiresAt } })
434 expect(textOf(runInput(run, 0).messages[0]?.content)).toContain(
435 'Today: 2026-06-11',
436 )
437 })
438​
439 it('sends an ended promo back once and takes the regular rate (#552)', async () => {
440 const run = gatewayReplies(promoCard, regularCard)
441 const card = await extract(
442 { ...args, pricingText: promoSection, now: Date.UTC(2026, 10, 4) / 1000 },
443 run,
444 )
445 expect(card).toMatchObject({ price: regularCard.price })
446 if (card === 'unverified' || 'error' in card) return
447 expect(card.source.expiresAt).toBeUndefined()
448 expect(run).toHaveBeenCalledTimes(2)
449 expect(textOf(runInput(run, 1).messages[2]?.content)).toContain(
450 'the promo ended 2026-10-31T23:59:59Z',
451 )
452 })
453​
454 it('takes unverified for an ended promo that states no regular rate (#552)', async () => {
455 const promoOnly = promoSection.replace(' (regular price: $0.03)', '')
456 const ended = { unverified: true, expiresAt: promoCard.expiresAt }
457 // Over: the section states no current price.
458 const over = gatewayReplies(ended)
459 await expect(
460 extract(
461 { ...args, pricingText: promoOnly, now: Date.UTC(2026, 10, 4) / 1000 },
462 over,
463 ),
464 ).resolves.toBe('unverified')
465 expect(over).toHaveBeenCalledTimes(1)
466 // Still running: the promo card is the price, so unverified is refused.
467 const live = gatewayReplies(ended, promoCard)
468 const card = await extract({ ...args, pricingText: promoOnly }, live)
469 expect(card).toMatchObject({ source: { expiresAt: promoCard.expiresAt } })
470 expect(textOf(runInput(live, 1).messages[2]?.content)).toContain(
471 'the section names $0.015',
472 )
473 // No promo in the section: a past end is a lazy refusal, not a fact.
474 const lazy = gatewayReplies(
475 { unverified: true, expiresAt: '2020-01-01T00:00:00Z' },
476 body,
477 )
478 await extract(args, lazy)
479 expect(textOf(runInput(lazy, 1).messages[2]?.content)).toContain(
480 'the section names $0.08',
481 )
482 })
483​
484 it('reads the card after the model explains itself, fenced or not, in one turn (#552)', async () => {
485 // Live Sonnet 5.5 reply shapes: a sentence, then the card.
486 const prose =
487 'The promo ended on October 31, 2026, so I price at the regular rate.'
488 const json = JSON.stringify(regularCard)
489 for (const reply of [
490 `${prose}\n\n\`\`\`json\n${json}\n\`\`\``,
491 `${prose}\n\n${json}`,
492 ]) {
493 const run = gatewayReplies(reply)
494 const card = await extract(
495 {
496 ...args,
497 pricingText: promoSection,
498 now: Date.UTC(2026, 10, 4) / 1000,
499 },
500 run,
501 )
502 expect(card).toMatchObject({ price: regularCard.price })
503 expect(run).toHaveBeenCalledTimes(1)
504 }
505 })
506​
507 it('returns the rejection when a priced section is refused twice', async () => {
508 for (const reply of [{ unverified: true }, { ...body, examples: [] }]) {
509 const run = gatewayReplies(reply, reply)
510 expect(await extractError(args, run)).toMatch(
511 /^rejected twice: the section names/,
512 )
513 expect(run).toHaveBeenCalledTimes(2)
514 }
515 })
516​
517 it('returns the rejection when verifyExamples fails on both turns', async () => {
518 const { examples, ...rest } = body
519 const first = examples[0]
520 const bad = {
521 ...rest,
522 examples: first
523 ? [{ ...first, usd: 999 }]
524 : [{ params: {}, usd: 999, quote: 'nope' }],
525 }
526 const run = gatewayReplies(bad, bad)
527 expect(await extractError(args, run)).toMatch(
528 /^rejected twice: verifyExamples failed/,
529 )
530 expect(textOf(runInput(run, 1).messages[2]?.content)).toContain(
531 'verifyExamples failed',
532 )
533 })
534​
535 it('rejects a request-bound param the input schema does not have', async () => {
536 const invented = {
537 ...body,
538 inputs: {
539 ...body.inputs,
540 num_images: { param: 'image_count', kind: 'number', default: 1 },
541 },
542 }
543 expect(
544 await extractError(args, gatewayReplies(invented, invented)),
545 ).toMatch(/^rejected twice: a request-bound/)
546 })
547​
548 it('fails closed on a non-card payload', async () => {
549 await expect(
550 extract(args, gatewayReplies({ nope: true }, 'not json')),
551 ).resolves.toEqual({ error: 'rejected twice: reply is not JSON' })
552 })
553​
554 it('fails closed when the binding call throws', async () => {
555 // The Anthropic SDK reports a thrown fetch as "Connection error.";
556 // gatewayChat keeps the binding's own error as the cause.
557 const run: RunMock = vi
558 .fn()
559 .mockRejectedValue(new Error('3040: Capacity temporarily exceeded'))
560 expect(await extractError(args, run)).toMatch(
561 /Connection error\..*caused by: 3040: Capacity temporarily exceeded/,
562 )
563 })
564​
565 it('does not blame an earlier retried throw for a later HTTP error', async () => {
566 const run: RunMock = vi
567 .fn()
568 .mockRejectedValueOnce(new Error('3040: Capacity temporarily exceeded'))
569 .mockImplementation(() =>
570 Promise.resolve(
571 Response.json(
572 { error: { message: 'rate limited' } },
573 { status: 429 },
574 ),
575 ),
576 )
577 const error = await extractError(args, run)
578 expect(error).toMatch(/429.*rate limited/)
579 expect(error).not.toContain('3040')
580 })
581​
582 it('returns the provider status and body when the gateway answers non-ok (#394)', async () => {
583 const run: RunMock = vi.fn(() =>
584 Promise.resolve(
585 Response.json({ error: { message: 'rate limited' } }, { status: 429 }),
586 ),
587 )
588 expect(await extractError(args, run)).toMatch(/429.*rate limited/)
589 })
590​
591 it('treats an empty reply as a rejection', async () => {
592 const run: RunMock = vi.fn(() => Promise.resolve(sseReply('')))
593 await expect(extract(args, run)).resolves.toEqual({
594 error: 'rejected twice: reply is not JSON',
595 })
596 })
597})
598​
599describe('EXTRACT_SYSTEM', () => {
600 // The model copies these, so each must pass the checks its reply does.
601 // A count input binds a list param; without a worked one the model wrote
602 // `{"reference_image_urls": 1}` and `x.length` (#489).
603 const workedExamples = [
604 ...EXTRACT_SYSTEM.matchAll(
605 /Section: "(.+)" Allowed: (.+)\.\n(\{"inputs".+\})$/gm,
606 ),
607 ].map(([, section = '', allowed = '', reply = '']) => ({
608 section,
609 allowed: new Set(allowed.split(', ')),
610 reply,
611 }))
612​
613 it('includes a worked count input', () => {
614 // Every "Example." in the prompt is parsed, none skipped by the regex.
615 expect(workedExamples).toHaveLength(
616 EXTRACT_SYSTEM.match(/^Example\. /gm)?.length ?? 0,
617 )
618 expect(workedExamples.length).toBeGreaterThan(1)
619 expect(workedExamples.some(({ reply }) => reply.includes('"count"'))).toBe(
620 true,
621 )
622 })
623​
624 it('has worked examples that pass checkExtractedCard', () => {
625 expect(workedExamples.length).toBeGreaterThan(0)
626 for (const { section, allowed, reply } of workedExamples) {
627 const card = checkExtractedCard(reply, {
628 pricingText: section,
629 requestProperties: allowed,
630 sourceUrl: 'https://fal.ai/models/fal-ai/example/llms.txt',
631 sourceHash: 'e'.repeat(64),
632 now: 1_781_150_000,
633 })
634 if (card === 'unverified' || 'error' in card) {
635 throw new Error(`${section}: ${JSON.stringify(card)}`)
636 }
637 expect(verifyExamples(card).every((r) => r.ok)).toBe(true)
638 }
639 })
640})
641​
642describe('checkExtractedCard', () => {
643 const base = {
644 requestProperties: new Set(['resolution', 'duration']),
645 sourceUrl:
646 'https://fal.ai/models/fal-ai/wan-25-preview/text-to-video/llms.txt',
647 sourceHash: 'd'.repeat(64),
648 now: 1_781_150_000,
649 }
650​
651 /** Live fal-ai/wan-25-preview/text-to-video, read 2026-09-30. */
652 const WAN_TABLE = `## Pricing
653​
654Your request will cost **$0.05** per second for **480p**, **$0.10** per second for **720p**, **$0.15** per second for **1080p**.
655​
656For more details, see [fal.ai pricing](https://fal.ai/pricing).`
657​
658 it('accepts a lookup calculator for a per-second resolution table', () => {
659 // The fast path refuses several rates by design — this is leftover work.
660 expect(parseFalUnitRate(WAN_TABLE)).toBeNull()
661 const reply = {
662 inputs: {
663 resolution: {
664 param: 'resolution',
665 kind: 'enum',
666 bound: 'request',
667 values: ['480p', '720p', '1080p'],
668 default: '1080p',
669 },
670 seconds: { param: 'seconds', kind: 'number', bound: 'usage' },
671 },
672 tables: { rate: { '480p': 0.05, '720p': 0.1, '1080p': 0.15 } },
673 price: {
674 '*': [
675 { var: 'seconds' },
676 { lookup: { table: 'rate', keys: [{ var: 'resolution' }] } },
677 ],
678 },
679 examples: [
680 {
681 params: { resolution: '480p', seconds: 1 },
682 usd: 0.05,
683 quote: 'Your request will cost **$0.05** per second for **480p**',
684 },
685 {
686 params: { resolution: '720p', seconds: 1 },
687 usd: 0.1,
688 quote: '**$0.10** per second for **720p**',
689 },
690 {
691 params: { seconds: 1 },
692 usd: 0.15,
693 quote: '**$0.15** per second for **1080p**',
694 },
695 ],
696 }
697 const card = checkExtractedCard(JSON.stringify(reply), {
698 ...base,
699 pricingText: WAN_TABLE,
700 })
701 if (card === 'unverified' || 'error' in card) {
702 throw new Error(JSON.stringify(card))
703 }
704 expect(card.source.hash).toBe(base.sourceHash)
705 expect(verifyExamples(card).every((r) => r.ok)).toBe(true)
706 expect(card.price).toMatchObject({
707 '*': [{ var: 'seconds' }, { lookup: {} }],
708 })
709 })
710​
711 // #304: live grok-4-fast reply for xai/grok-imagine-video/extend-video,
712 // whose request has no resolution field.
713 it('refuses a usage-bound input with a default', () => {
714 const reply = {
715 inputs: {
716 resolution: {
717 param: 'resolution',
718 bound: 'usage',
719 kind: 'enum',
720 values: ['480p', '720p'],
721 default: '480p',
722 },
723 seconds: { param: 'seconds', bound: 'usage', kind: 'number' },
724 },
725 tables: { rate: { '480p': 0.05, '720p': 0.07 } },
726 price: {
727 '*': [
728 { var: 'seconds' },
729 { lookup: { table: 'rate', keys: [{ var: 'resolution' }] } },
730 ],
731 },
732 examples: [
733 {
734 params: { resolution: '480p', seconds: 1 },
735 usd: 0.05,
736 quote: 'Cost is **$0.05** per second of 480p output video',
737 },
738 ],
739 }
740 const pricingText =
741 '## Pricing\n\nCost is **$0.05** per second of 480p output video (**$0.07** at 720p).'
742 const refused = checkExtractedCard(JSON.stringify(reply), {
743 ...base,
744 requestProperties: new Set(['prompt']),
745 pricingText,
746 })
747 expect(
748 typeof refused === 'object' && 'error' in refused && refused.error,
749 ).toContain('usage-bound enums have a default (resolution)')
750 const { default: _default, ...resolution } = reply.inputs.resolution
751 const card = checkExtractedCard(
752 JSON.stringify({ ...reply, inputs: { ...reply.inputs, resolution } }),
753 { ...base, requestProperties: new Set(['prompt']), pricingText },
754 )
755 expect(typeof card === 'object' && 'inputs' in card).toBe(true)
756 })
757​
758 it('refuses unverified for the table but allows it for a zero-price stub', () => {
759 const refused = checkExtractedCard('{"unverified":true}', {
760 ...base,
761 pricingText: WAN_TABLE,
762 })
763 expect(
764 typeof refused === 'object' && 'error' in refused && refused.error,
765 ).toContain('$0.05')
766 expect(
767 checkExtractedCard('{"unverified":true}', {
768 ...base,
769 pricingText:
770 '## Pricing\n\nYour request will cost **$0.00** per image.',
771 }),
772 ).toBe('unverified')
773 })
774})