@aeye/models 0.3.8 → 0.4.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 (63) hide show
  1. package/aeye-models.md +272 -0
  2. package/dist/scripts/codegen.d.ts +4 -0
  3. package/dist/scripts/codegen.d.ts.map +1 -1
  4. package/dist/scripts/codegen.js +16 -1
  5. package/dist/scripts/codegen.js.map +1 -1
  6. package/dist/scripts/scrape.d.ts +2 -1
  7. package/dist/scripts/scrape.d.ts.map +1 -1
  8. package/dist/scripts/scrape.js +8 -4
  9. package/dist/scripts/scrape.js.map +1 -1
  10. package/dist/scripts/scrapers/aws.d.ts +5 -1
  11. package/dist/scripts/scrapers/aws.d.ts.map +1 -1
  12. package/dist/scripts/scrapers/aws.js +211 -57
  13. package/dist/scripts/scrapers/aws.js.map +1 -1
  14. package/dist/scripts/scrapers/docs.d.ts +43 -0
  15. package/dist/scripts/scrapers/docs.d.ts.map +1 -0
  16. package/dist/scripts/scrapers/docs.js +91 -0
  17. package/dist/scripts/scrapers/docs.js.map +1 -0
  18. package/dist/scripts/scrapers/openai.d.ts +4 -1
  19. package/dist/scripts/scrapers/openai.d.ts.map +1 -1
  20. package/dist/scripts/scrapers/openai.js +183 -445
  21. package/dist/scripts/scrapers/openai.js.map +1 -1
  22. package/dist/scripts/scrapers/openrouter.d.ts +1 -1
  23. package/dist/scripts/scrapers/openrouter.d.ts.map +1 -1
  24. package/dist/scripts/scrapers/openrouter.js +20 -79
  25. package/dist/scripts/scrapers/openrouter.js.map +1 -1
  26. package/dist/src/index.d.ts +1 -0
  27. package/dist/src/index.d.ts.map +1 -1
  28. package/dist/src/index.js +1 -0
  29. package/dist/src/index.js.map +1 -1
  30. package/dist/src/models/aws.d.ts.map +1 -1
  31. package/dist/src/models/aws.js +2180 -1033
  32. package/dist/src/models/aws.js.map +1 -1
  33. package/dist/src/models/openai.d.ts.map +1 -1
  34. package/dist/src/models/openai.js +1925 -1370
  35. package/dist/src/models/openai.js.map +1 -1
  36. package/dist/src/models/openrouter.d.ts.map +1 -1
  37. package/dist/src/models/openrouter.js +16017 -6383
  38. package/dist/src/models/openrouter.js.map +1 -1
  39. package/dist/src/strict-support.d.ts +45 -0
  40. package/dist/src/strict-support.d.ts.map +1 -0
  41. package/dist/src/strict-support.js +129 -0
  42. package/dist/src/strict-support.js.map +1 -0
  43. package/dist/src/transformers/replicate/black-forest-labs-flux-1-1-pro.js +1 -1
  44. package/dist/src/transformers/replicate/black-forest-labs-flux-1-1-pro.js.map +1 -1
  45. package/dist/src/transformers/replicate/black-forest-labs-flux-pro.js +1 -1
  46. package/dist/src/transformers/replicate/black-forest-labs-flux-pro.js.map +1 -1
  47. package/dist/src/transformers/replicate/openai-gpt-image-1.js +1 -1
  48. package/dist/src/transformers/replicate/openai-gpt-image-1.js.map +1 -1
  49. package/package.json +78 -79
  50. package/scripts/codegen.ts +17 -2
  51. package/scripts/scrape.ts +13 -5
  52. package/scripts/scrapers/aws.ts +245 -76
  53. package/scripts/scrapers/docs.ts +101 -0
  54. package/scripts/scrapers/openai.ts +185 -552
  55. package/scripts/scrapers/openrouter.ts +20 -106
  56. package/src/index.ts +13 -12
  57. package/src/models/aws.ts +2569 -1422
  58. package/src/models/openai.ts +2764 -2209
  59. package/src/models/openrouter.ts +19708 -10074
  60. package/src/strict-support.ts +134 -0
  61. package/src/transformers/replicate/black-forest-labs-flux-1-1-pro.ts +1 -1
  62. package/src/transformers/replicate/black-forest-labs-flux-pro.ts +1 -1
  63. package/src/transformers/replicate/openai-gpt-image-1.ts +1 -1
@@ -1,96 +1,266 @@
1
1
  /**
2
2
  * AWS Bedrock Model Scraper
3
3
  *
4
- * Fetches model information from AWS Bedrock using the AWS SDK
4
+ * Builds model information without AWS credentials: every model in the
5
+ * Markdown model cards of the Bedrock user guide (ids, modalities, APIs,
6
+ * features, limits, end-of-life dates), priced from AWS's public price list
7
+ * offer files, or from a card's own pricing table where it has one.
5
8
  */
6
9
 
7
- import type { ModelInfo } from '@aeye/ai';
8
- import { convertAWSModel } from '@aeye/aws';
9
- import {
10
- BedrockClient,
11
- ListFoundationModelsCommand,
12
- } from '@aws-sdk/client-bedrock';
13
- import * as fs from 'fs/promises';
14
10
  import * as path from 'path';
15
- import * as url from 'url';
16
- import { writeModelTS } from '../codegen';
11
+ import { fileURLToPath } from 'url';
12
+ import type { ModelCapability, ModelInfo, ModelPricing } from '@aeye/ai';
13
+ import { detectAWSFamily, detectAWSTier } from '@aeye/aws';
14
+ import { writeModelJSON, writeModelTS } from '../codegen';
15
+ import { amount, bullets, fetchMarkdown, isoDate, reasoningEfforts, section, tableRecords } from './docs';
17
16
 
18
- const __filename = url.fileURLToPath(import.meta.url);
19
- const __dirname = path.dirname(__filename);
17
+ const DOCS = 'https://docs.aws.amazon.com/bedrock/latest/userguide';
18
+ const OFFERS = 'https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws';
20
19
 
21
20
  /**
22
- * Main scraper function
21
+ * Price list offers with Bedrock's on-demand prices: Amazon and open-weight
22
+ * models, and the models AWS Marketplace sells (Anthropic, Cohere, ...).
23
23
  */
24
- export async function scrapeAWS(
25
- outputDir: string,
26
- options: { region?: string } = {}
27
- ): Promise<void> {
28
- const { region = process.env.AWS_REGION || 'us-east-2' } = options;
24
+ const OFFER_CODES = ['AmazonBedrock', 'AmazonBedrockFoundationModels'];
29
25
 
30
- console.log('\n=== AWS Bedrock Scraper ===\n');
31
- console.log(`Using region: ${region}`);
26
+ /**
27
+ * Multipliers to tokens per 1M, by price unit, and to tokens, by limit suffix.
28
+ */
29
+ const PER_MILLION: Record<string, number | undefined> = { '1m tokens': 1, '1k tokens': 1000 };
30
+ const SCALE: Record<string, number | undefined> = { K: 1e3, M: 1e6 };
32
31
 
33
- // Create Bedrock client
34
- const client = new BedrockClient({
35
- region,
36
- // Credentials are automatically picked up from environment
37
- });
32
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
38
33
 
39
- try {
40
- // List foundation models
41
- console.log('Fetching models from AWS Bedrock...');
42
- const command = new ListFoundationModelsCommand({});
43
- const response = await client.send(command);
34
+ type TextPricing = NonNullable<ModelPricing['text']>;
44
35
 
45
- if (!response.modelSummaries) {
46
- console.log('✗ No models returned from AWS Bedrock');
47
- return;
48
- }
36
+ /**
37
+ * The parts of a price list offer file read here.
38
+ */
39
+ interface Offer {
40
+ products: Record<string, { attributes: Record<string, string | undefined> }>;
41
+ terms: {
42
+ OnDemand: Record<string, Record<string, {
43
+ priceDimensions: Record<string, { unit: string; pricePerUnit: { USD: string } }>;
44
+ }>>;
45
+ };
46
+ }
49
47
 
50
- console.log(`✓ Fetched ${response.modelSummaries.length} AWS Bedrock models`);
48
+ /**
49
+ * A model name reduced to the words that tell models apart, so a card's
50
+ * "Llama 3.2 1B Instruct" meets the price list's "Llama 3.2 1B".
51
+ */
52
+ function nameKey(name: string): string {
53
+ return name.toLowerCase()
54
+ .replace(/\.0\b/g, '')
55
+ .split(/[^a-z0-9.+]+/)
56
+ .filter(word => word && !['amazon', 'deepseek', 'openai', 'instruct', 'it', 'pt'].includes(word))
57
+ .join('-');
58
+ }
51
59
 
52
- // Create output directory
53
- await fs.mkdir(outputDir, { recursive: true });
60
+ /**
61
+ * A model id without its version suffix, as price list usage types name it.
62
+ */
63
+ function idKey(id: string): string {
64
+ return id.replace(/-v\d+:\d+$/, '');
65
+ }
54
66
 
55
- // Save raw data
56
- await fs.writeFile(
57
- path.join(outputDir, 'aws-models.json'),
58
- JSON.stringify({ data: response.modelSummaries }, (key, value) => {
59
- if (value instanceof Set) {
60
- return Array.from(value);
61
- }
62
- return value;
63
- }, 2)
64
- );
65
- console.log(`✓ Saved raw AWS models to aws-models.json`);
66
-
67
- // Convert to ModelInfo format
68
- const modelInfos = response.modelSummaries
69
- .map(convertAWSModel)
70
- .filter((m): m is ModelInfo => m !== null);
71
-
72
- // Save JSON for reference
73
- await fs.writeFile(
74
- path.join(outputDir, 'aws-modelinfo.json'),
75
- JSON.stringify(modelInfos, (key, value) => {
76
- if (value instanceof Set) {
77
- return Array.from(value);
67
+ /**
68
+ * Lowest standard on-demand token prices per 1M tokens, by model name and by
69
+ * the model id usage types carry. Batch, flex, priority, provisioned, and
70
+ * long-cache prices are skipped, and the lowest of the in-region, geographic,
71
+ * and global prices is kept (global cross-region inference has no premium).
72
+ */
73
+ async function fetchOfferPricing(region: string): Promise<Map<string, TextPricing>> {
74
+ const pricing = new Map<string, TextPricing>();
75
+ for (const code of OFFER_CODES) {
76
+ const offer: Offer = JSON.parse(await (await fetch(`${OFFERS}/${code}/current/${region}/index.json`)).text());
77
+ for (const [sku, { attributes }] of Object.entries(offer.products)) {
78
+ const { model = attributes.titanModel, inferenceType = '', usagetype = '', feature = '', service_tier = '' } = attributes;
79
+ const kind: keyof TextPricing | undefined =
80
+ /batch|flex|priority|reserved|provisioned|customization|1h|audio|image|video|speech/i.test(`${inferenceType} ${usagetype} ${feature} ${service_tier}`) ? undefined
81
+ : /cache read/i.test(inferenceType) ? 'cached'
82
+ : /cache write/i.test(inferenceType) ? 'cacheWrite'
83
+ : /input/i.test(inferenceType) ? 'input'
84
+ : /output/i.test(inferenceType) ? 'output'
85
+ : undefined;
86
+ const id = /^[A-Z0-9]+-([a-z0-9-]+\.[\w.-]+?)-(?:mantle|input|output|cache)/.exec(usagetype)?.[1];
87
+ for (const term of Object.values(offer.terms.OnDemand[sku] ?? {})) {
88
+ for (const { unit, pricePerUnit } of Object.values(term.priceDimensions)) {
89
+ const perMillion = PER_MILLION[unit.toLowerCase()];
90
+ if (!kind || !perMillion) {
91
+ continue;
92
+ }
93
+ // Rounded to drop float noise from per-1K prices
94
+ const price = Math.round(Number(pricePerUnit.USD) * perMillion * 1e6) / 1e6;
95
+ for (const key of [model && nameKey(model), id]) {
96
+ if (key) {
97
+ const entry = pricing.get(key) ?? {};
98
+ entry[kind] = Math.min(entry[kind] ?? Infinity, price);
99
+ pricing.set(key, entry);
100
+ }
101
+ }
78
102
  }
79
- return value;
80
- }, 2)
81
- );
82
- console.log(`✓ Saved ${modelInfos.length} models to JSON`);
83
-
84
- // Generate TypeScript file
85
- const srcDir = path.join(__dirname, '../../src/models');
86
- await writeModelTS(modelInfos, 'awsModels', path.join(srcDir, 'aws.ts'));
87
- console.log(`✓ Generated TypeScript file: src/models/aws.ts`);
88
-
89
- console.log('\n✓ AWS Bedrock scraping complete\n');
90
- } catch (error) {
91
- console.error('✗ AWS Bedrock scraping failed:', error);
92
- throw error;
103
+ }
104
+ }
105
+ }
106
+ return pricing;
107
+ }
108
+
109
+ /**
110
+ * Lowest prices in a card's own pricing table; the cards that have one are
111
+ * for models the offer files don't price.
112
+ */
113
+ function cardPricing(markdown: string): TextPricing | undefined {
114
+ const rows = tableRecords(section(markdown, 'Pricing'), /Inference option/);
115
+ const lowest = (column: RegExp) => {
116
+ const prices = rows.flatMap(row => [...row].flatMap(([name, cell]) => column.test(name) ? [amount(cell) ?? Infinity] : []));
117
+ const price = Math.min(...prices);
118
+ return Number.isFinite(price) ? price : undefined;
119
+ };
120
+ return rows.length
121
+ ? { input: lowest(/^Input$/), output: lowest(/^Output$/), cached: lowest(/cache read/), cacheWrite: lowest(/cache write/) }
122
+ : undefined;
123
+ }
124
+
125
+ /**
126
+ * A `200K tokens` or `128,000` limit as a number.
127
+ */
128
+ function tokens(text: string | undefined): number | undefined {
129
+ const match = /([\d,.]+)\s*([KM])?/.exec(text ?? '');
130
+ const count = amount(match?.[1] ?? '');
131
+ return count === undefined ? undefined : Math.round(count * (SCALE[match?.[2] ?? ''] ?? 1));
132
+ }
133
+
134
+ /**
135
+ * Convert one model card into ModelInfo, or undefined for models the
136
+ * bedrock-runtime endpoint doesn't serve or that have nothing to offer here.
137
+ */
138
+ function parseCard(card: string, offers: Map<string, TextPricing>): ModelInfo | undefined {
139
+ // Check icons become marks and links their text; other images, emphasis, and escapes go
140
+ const markdown = card
141
+ .replace(/!\[[^\]]*\]\([^)]*icon-yes\.png\)/g, '✓')
142
+ .replace(/!\[[^\]]*\]\([^)]*icon-no\.png\)/g, '✗')
143
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
144
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
145
+ .replace(/\*\*|\\(?=[^|])/g, '');
146
+
147
+ const access = tableRecords(markdown, /Model ID/).find(row => row.get('Endpoint') === 'bedrock-runtime');
148
+ const inferenceIds = [access?.get('Geo inference ID'), access?.get('Global inference ID')]
149
+ .flatMap(cell => cell?.match(/\b[a-z-]+\.[a-z0-9-]+\.[\w.:-]+/g) ?? []);
150
+ // Some cards list only inference profiles, which are the id behind a geography prefix
151
+ const id = [access?.get('Model ID'), ...inferenceIds.map(profile => profile.slice(profile.indexOf('.') + 1))]
152
+ .find(candidate => candidate?.includes('.'));
153
+ if (!id) {
154
+ return undefined;
93
155
  }
156
+ const name = /^# (.+)$/m.exec(markdown)?.[1].trim() ?? id;
157
+ const details = bullets(markdown);
158
+ const detail = (key: string) => details.find(d => d.startsWith(`${key}: `))?.slice(key.length + 2);
159
+ // The card from a heading about the bedrock-runtime endpoint, or nothing without one
160
+ const runtime = (heading: string) => {
161
+ const start = markdown.search(new RegExp(`${heading} (using|on) (the )?\`bedrock-runtime\``));
162
+ return start < 0 ? '' : markdown.slice(start);
163
+ };
164
+
165
+ // Checked modality (and, on older cards, API and endpoint) cells, e.g. 'input modalities: image'
166
+ const checked = new Set(tableRecords(markdown, /Input modalities/i).flatMap(row =>
167
+ [...row].flatMap(([column, cell]) => cell.startsWith('✓') ? [`${column}: ${cell.slice(1).trim()}`.toLowerCase()] : [])));
168
+ const runtimeAPIs = tableRecords(runtime('APIs supported'), /Converse/)[0];
169
+ const features = (tableRecords(runtime('Features supported'), /Supported/)[0]?.get('Supported') ?? '')
170
+ .split('<br />')
171
+ .map(feature => feature.replace(/^\+?\s*✓\s*/, ''));
172
+ const hasFeature = (feature: string) => features.some(f => f.startsWith(feature));
173
+ const input = (modality: string) => checked.has(`input modalities: ${modality}`);
174
+ const output = (modality: string) => checked.has(`output modalities: ${modality}`);
175
+
176
+ const chat = output('text') && (checked.has('apis supported: converse') || !!runtimeAPIs?.get('Converse')?.startsWith('✓'));
177
+ const reasoning = detail('Reasoning')?.startsWith('Supported') ?? false;
178
+ const efforts = /effort(?: configurable:| to) ([^).]+)/i.exec(markdown)?.[1];
179
+ const endOfLife = detail('Model EOL date') ?? '';
180
+
181
+ const capabilities = new Set<ModelCapability>();
182
+ const add = (when: boolean, capability: ModelCapability) => {
183
+ if (when) {
184
+ capabilities.add(capability);
185
+ }
186
+ };
187
+ add(chat, 'chat');
188
+ // Converse takes tools for every chat model
189
+ add(chat, 'tools');
190
+ add(chat && hasFeature('Response streaming'), 'streaming');
191
+ add(chat && hasFeature('Structured outputs'), 'structured');
192
+ add(chat && hasFeature('Structured outputs'), 'json');
193
+ add(chat && input('image'), 'vision');
194
+ add(chat && input('video'), 'videoInput');
195
+ add(chat && reasoning, 'reasoning');
196
+ add(input('audio') || input('speech'), 'hearing');
197
+ add(output('speech') || output('audio'), 'audio');
198
+ add(output('image'), 'image');
199
+ add(output('embedding'), 'embedding');
200
+ if (!capabilities.size) {
201
+ return undefined;
202
+ }
203
+
204
+ const text = cardPricing(markdown) ?? offers.get(idKey(id)) ?? offers.get(nameKey(name));
205
+ const pricing: ModelPricing = !text ? {}
206
+ : capabilities.has('embedding') ? { embeddings: { cost: text.input } }
207
+ : { text };
208
+
209
+ return {
210
+ provider: 'aws',
211
+ id,
212
+ name,
213
+ capabilities,
214
+ tier: detail('Model lifecycle') === 'Legacy' ? 'legacy' : detectAWSTier(detectAWSFamily(id), id),
215
+ contextWindow: tokens(detail('Context window')) ?? 0,
216
+ maxOutputTokens: tokens(detail('Max output tokens')),
217
+ pricing,
218
+ reasoningEfforts: reasoning && efforts ? reasoningEfforts(efforts) : undefined,
219
+ // 'No sooner than <date>' is a floor, not a date
220
+ retiresAt: /sooner/i.test(endOfLife) ? undefined : isoDate(endOfLife),
221
+ metadata: {
222
+ providerName: /^## (.+?) — /m.exec(markdown)?.[1].trim(),
223
+ knowledgeCutoff: detail('Knowledge cutoff'),
224
+ // Without in-region inference, requests go through an inference profile (modelPrefix)
225
+ inRegion: access?.get('In-Region endpoint URL')?.includes('https://') ?? false,
226
+ inferenceIds: inferenceIds.length ? inferenceIds : undefined,
227
+ },
228
+ };
229
+ }
230
+
231
+ /**
232
+ * Main scraper function
233
+ */
234
+ export async function scrapeAWS(
235
+ outputDir: string,
236
+ options: { region?: string; concurrency?: number } = {}
237
+ ): Promise<void> {
238
+ const { region = 'us-east-1', concurrency = 8 } = options;
239
+ console.log('\n=== AWS Bedrock Scraper ===\n');
240
+
241
+ const [index, offers] = await Promise.all([fetchMarkdown(`${DOCS}/model-cards.md`), fetchOfferPricing(region)]);
242
+ const pages = [...new Set((index ?? '').match(/model-card-[\w-]+\.md/g))];
243
+ if (!pages.length) {
244
+ throw new Error('No model cards listed in the Bedrock user guide');
245
+ }
246
+ console.log(`✓ ${pages.length} model cards, ${offers.size} priced models in ${region}`);
247
+
248
+ const models: ModelInfo[] = [];
249
+ for (let i = 0; i < pages.length; i += concurrency) {
250
+ await Promise.all(pages.slice(i, i + concurrency).map(async page => {
251
+ const model = parseCard(await fetchMarkdown(`${DOCS}/${page}`) ?? '', offers);
252
+ if (model) {
253
+ models.push(model);
254
+ }
255
+ }));
256
+ }
257
+ models.sort((a, b) => a.id.localeCompare(b.id));
258
+ const unpriced = models.filter(m => !Object.keys(m.pricing).length).map(m => m.id);
259
+ console.log(`✓ Parsed ${models.length} bedrock-runtime models${unpriced.length ? `, no prices for: ${unpriced.join(', ')}` : ''}`);
260
+
261
+ await writeModelJSON(models, path.join(outputDir, 'aws-modelinfo.json'));
262
+ await writeModelTS(models, 'awsModels', path.join(__dirname, '../../src/models/aws.ts'));
263
+ console.log('✓ Generated TypeScript file: src/models/aws.ts\n');
94
264
  }
95
265
 
96
266
  // CLI execution
@@ -98,9 +268,8 @@ if (process.argv[1].endsWith('aws.ts')) {
98
268
  const args = process.argv.slice(2);
99
269
  const outputDir = args.find((arg) => !arg.startsWith('--')) || path.join(__dirname, '../../data');
100
270
  const regionArg = args.find((arg) => arg.startsWith('--region='));
101
- const region = regionArg ? regionArg.split('=')[1] : undefined;
102
271
 
103
- scrapeAWS(outputDir, { region }).catch((error) => {
272
+ scrapeAWS(outputDir, { region: regionArg?.split('=')[1] }).catch((error) => {
104
273
  console.error('✗ AWS Bedrock scraping failed:', error);
105
274
  process.exit(1);
106
275
  });
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Helpers shared by the scrapers that read provider docs pages as Markdown.
3
+ */
4
+
5
+ import { REASONING_EFFORTS, type ReasoningEffort } from '@aeye/core';
6
+
7
+ /**
8
+ * Fetch a docs page as Markdown, or undefined when it doesn't exist.
9
+ */
10
+ export async function fetchMarkdown(url: string): Promise<string | undefined> {
11
+ const response = await fetch(url);
12
+ return response.ok ? response.text() : undefined;
13
+ }
14
+
15
+ /**
16
+ * The body of a `##` or `###` section, up to the next heading of the same or
17
+ * a higher level.
18
+ */
19
+ export function section(markdown: string, heading: string): string {
20
+ const match = new RegExp(`^(#{2,3}) ${heading}\\s*$`, 'm').exec(markdown);
21
+ if (!match) {
22
+ return '';
23
+ }
24
+ const rest = markdown.slice(match.index + match[0].length);
25
+ const end = new RegExp(`^#{2,${match[1].length}} `, 'm').exec(rest);
26
+ return end ? rest.slice(0, end.index) : rest;
27
+ }
28
+
29
+ /**
30
+ * Every `### heading` in a section, with its body.
31
+ */
32
+ export function subsections(markdown: string): Map<string, string> {
33
+ const parts = markdown.split(/^### /m).slice(1);
34
+ return new Map(parts.map(part => {
35
+ const newline = part.indexOf('\n');
36
+ return [part.slice(0, newline).trim(), part.slice(newline)];
37
+ }));
38
+ }
39
+
40
+ /**
41
+ * The text of each `- ` (or `+ `) bullet.
42
+ */
43
+ export function bullets(markdown: string): string[] {
44
+ return markdown.split('\n').flatMap(line => /^[-+] /.test(line) ? [line.slice(2).trim()] : []);
45
+ }
46
+
47
+ /**
48
+ * The cells of a table line.
49
+ */
50
+ function cells(line: string): string[] {
51
+ return line.trim().slice(1, -1).split(/(?<!\\)\|/).map(cell => cell.trim());
52
+ }
53
+
54
+ /**
55
+ * The cells of each table body row.
56
+ */
57
+ export function tableRows(markdown: string): string[][] {
58
+ return markdown.split('\n')
59
+ .filter(line => line.startsWith('|') && !/^\|\s*-/.test(line))
60
+ .slice(1)
61
+ .map(cells);
62
+ }
63
+
64
+ /**
65
+ * The body rows of the first table whose header line matches `header`, each
66
+ * keyed by column name.
67
+ */
68
+ export function tableRecords(markdown: string, header: RegExp): Map<string, string>[] {
69
+ const lines = markdown.split('\n');
70
+ const start = lines.findIndex(line => line.startsWith('|') && header.test(line));
71
+ if (start < 0) {
72
+ return [];
73
+ }
74
+ const end = lines.findIndex((line, i) => i > start && !line.startsWith('|'));
75
+ const columns = cells(lines[start]);
76
+ return tableRows(lines.slice(start, end < 0 ? undefined : end).join('\n'))
77
+ .map(row => new Map(row.map((cell, i) => [columns[i], cell])));
78
+ }
79
+
80
+ /**
81
+ * A `$1.25` price, or a `1,050,000` count, as a number.
82
+ */
83
+ export function amount(text: string): number | undefined {
84
+ const parsed = Number(text.replace(/[$,]/g, ''));
85
+ return text && Number.isFinite(parsed) ? parsed : undefined;
86
+ }
87
+
88
+ /**
89
+ * A date such as `April 8, 2027` as YYYY-MM-DD, or undefined when it isn't one.
90
+ */
91
+ export function isoDate(text: string): string | undefined {
92
+ const parsed = new Date(`${text} UTC`);
93
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString().slice(0, 10);
94
+ }
95
+
96
+ /**
97
+ * The reasoning efforts a list such as `low, medium, high` names, in order.
98
+ */
99
+ export function reasoningEfforts(text: string): ReasoningEffort[] {
100
+ return REASONING_EFFORTS.filter((effort: ReasoningEffort) => new RegExp(`\\b${effort}\\b`).test(text));
101
+ }