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

sync-provider-models.ts

770 lines26.1 KB

1/**
2 * Syncs OpenRouter models into native provider model-meta.ts files.
3 *
4 * For each supported provider (OpenAI, Anthropic, Gemini, Grok), this script:
5 * 1. Reads the OpenRouter model list
6 * 2. Filters models matching the provider prefix
7 * 3. Identifies models missing from the provider's model-meta.ts
8 * 4. Generates and inserts new model constants, array entries, and type map entries
9 *
10 * Usage:
11 * pnpm tsx scripts/sync-provider-models.ts
12 */
13​
14import { execFileSync } from 'node:child_process'
15import { readFile, writeFile } from 'node:fs/promises'
16import { dirname, resolve } from 'node:path'
17import { fileURLToPath } from 'node:url'
18import { models } from './openrouter.models'
19import type { OpenRouterModel } from './openrouter.models'
20​
21const __dirname = dirname(fileURLToPath(import.meta.url))
22const ROOT = resolve(__dirname, '..')
23​
24// ---------------------------------------------------------------------------
25// Provider configuration
26// ---------------------------------------------------------------------------
27​
28/** Seconds in 30 days — models older than this before the last sync are skipped */
29const MAX_MODEL_AGE_SECONDS = 30 * 24 * 60 * 60
30const LAST_RUN_FILE = resolve(ROOT, 'scripts/.sync-models-last-run')
31​
32interface ProviderConfig {
33 /** npm package name for changeset */
34 packageName: string
35 metaFile: string
36 /** How array entries reference the constant, e.g. '.name' or '.id' */
37 arrayRef: '.name' | '.id'
38 /** Which field name is used for context window size */
39 contextField: 'context_window' | 'max_input_tokens'
40 /** Name of the exported chat model array */
41 chatArrayName: string
42 /** Name of the provider options type map */
43 providerOptionsTypeName: string
44 /** Name of the input modalities type map */
45 inputModalitiesTypeName: string
46 /** The supports block template (minus input modalities, which come from OpenRouter) */
47 referenceSupportsBody: string
48 /** Valid input modality types for this provider's ModelMeta interface */
49 validInputModalities: Array<InputModality>
50 /** The satisfies type clause (after 'as const satisfies') */
51 referenceSatisfies: string
52 /** The type string for provider options map entries */
53 referenceProviderOptionsEntry: string
54 /** Whether this provider has both name AND id fields */
55 hasBothNameAndId: boolean
56 /** Whether the provider options type is a mapped type (skip insertion) */
57 providerOptionsIsMappedType: boolean
58 /** Model ID patterns to always skip (matched against stripped ID) */
59 skipPatterns: Array<string>
61​
62const PROVIDER_MAP: Record<string, ProviderConfig> = {
63 'openai/': {
64 packageName: '@tanstack/ai-openai',
65 metaFile: resolve(ROOT, 'packages/typescript/ai-openai/src/model-meta.ts'),
66 arrayRef: '.name',
67 contextField: 'context_window',
68 chatArrayName: 'OPENAI_CHAT_MODELS',
69 providerOptionsTypeName: 'OpenAIChatModelProviderOptionsByName',
70 inputModalitiesTypeName: 'OpenAIModelInputModalitiesByName',
71 validInputModalities: ['text', 'image', 'audio', 'video'],
72 referenceSupportsBody: ` output: ['text'],
73 endpoints: ['chat', 'chat-completions'],
74 features: ['streaming', 'function_calling', 'structured_outputs', 'distillation'],
75 tools: ['web_search', 'web_search_preview', 'file_search', 'image_generation', 'code_interpreter', 'mcp', 'computer_use', 'local_shell', 'shell', 'apply_patch'],`,
76 referenceSatisfies:
77 'ModelMeta<OpenAIBaseOptions & OpenAIReasoningOptions & OpenAIStructuredOutputOptions & OpenAIToolsOptions & OpenAIStreamingOptions & OpenAIMetadataOptions>',
78 referenceProviderOptionsEntry:
79 'OpenAIBaseOptions & OpenAIReasoningOptions & OpenAIStructuredOutputOptions & OpenAIToolsOptions & OpenAIStreamingOptions & OpenAIMetadataOptions',
80 hasBothNameAndId: false,
81 providerOptionsIsMappedType: false,
82 skipPatterns: [
83 'gpt-3.5-', // Legacy GPT-3.5 models
84 'gpt-4-', // Legacy GPT-4 base models (not 4.1+)
85 'gpt-4o', // GPT-4o variants (4o, 4o-mini, 4o-audio, etc.)
86 'gpt-oss-', // Open-source/experimental models
87 'chatgpt-', // ChatGPT branded models
88 ],
89 },
90 'anthropic/': {
91 packageName: '@tanstack/ai-anthropic',
92 metaFile: resolve(
93 ROOT,
94 'packages/typescript/ai-anthropic/src/model-meta.ts',
95 ),
96 arrayRef: '.id',
97 contextField: 'context_window',
98 chatArrayName: 'ANTHROPIC_MODELS',
99 providerOptionsTypeName: 'AnthropicChatModelProviderOptionsByName',
100 inputModalitiesTypeName: 'AnthropicModelInputModalitiesByName',
101 validInputModalities: ['text', 'image', 'audio', 'video', 'document'],
102 referenceSupportsBody: ` extended_thinking: true,
103 priority_tier: true,
104 tools: ['web_search', 'web_fetch', 'code_execution', 'computer_use', 'bash', 'text_editor', 'memory'],`,
105 referenceSatisfies:
106 'ModelMeta<AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & AnthropicThinkingOptions & AnthropicToolChoiceOptions & AnthropicSamplingOptions>',
107 referenceProviderOptionsEntry:
108 'AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & AnthropicThinkingOptions & AnthropicToolChoiceOptions & AnthropicSamplingOptions',
109 hasBothNameAndId: true,
110 providerOptionsIsMappedType: false,
111 skipPatterns: [],
112 },
113 'google/': {
114 packageName: '@tanstack/ai-gemini',
115 metaFile: resolve(ROOT, 'packages/typescript/ai-gemini/src/model-meta.ts'),
116 arrayRef: '.name',
117 contextField: 'max_input_tokens',
118 chatArrayName: 'GEMINI_MODELS',
119 providerOptionsTypeName: 'GeminiChatModelProviderOptionsByName',
120 inputModalitiesTypeName: 'GeminiModelInputModalitiesByName',
121 validInputModalities: ['text', 'image', 'audio', 'video', 'document'],
122 referenceSupportsBody: ` output: ['text'],
123 capabilities: ['batch_api', 'caching', 'function_calling', 'structured_output', 'thinking'],
124 tools: ['code_execution', 'file_search', 'google_search', 'url_context'],`,
125 referenceSatisfies:
126 'ModelMeta<GeminiToolConfigOptions & GeminiSafetyOptions & GeminiCommonConfigOptions & GeminiCachedContentOptions & GeminiStructuredOutputOptions & GeminiThinkingOptions>',
127 referenceProviderOptionsEntry:
128 'GeminiToolConfigOptions & GeminiSafetyOptions & GeminiCommonConfigOptions & GeminiCachedContentOptions & GeminiStructuredOutputOptions & GeminiThinkingOptions',
129 hasBothNameAndId: false,
130 providerOptionsIsMappedType: false,
131 skipPatterns: [
132 'gemma-', // Gemma open-source models (not Gemini API models)
133 ],
134 },
135 'x-ai/': {
136 packageName: '@tanstack/ai-grok',
137 metaFile: resolve(ROOT, 'packages/typescript/ai-grok/src/model-meta.ts'),
138 arrayRef: '.name',
139 contextField: 'context_window',
140 chatArrayName: 'GROK_CHAT_MODELS',
141 providerOptionsTypeName: 'GrokChatModelProviderOptionsByName',
142 inputModalitiesTypeName: 'GrokModelInputModalitiesByName',
143 validInputModalities: ['text', 'image', 'audio', 'video', 'document'],
144 referenceSupportsBody: ` output: ['text'],
145 capabilities: ['reasoning', 'structured_outputs', 'tool_calling'],
146 tools: [],`,
147 referenceSatisfies: 'ModelMeta',
148 referenceProviderOptionsEntry: 'GrokProviderOptions',
149 hasBothNameAndId: false,
150 providerOptionsIsMappedType: true,
151 skipPatterns: [],
152 },
154​
155// ---------------------------------------------------------------------------
156// Utility functions
157// ---------------------------------------------------------------------------
158​
159type InputModality = 'text' | 'image' | 'audio' | 'video' | 'document'
160​
161const MODALITY_MAP: Record<string, InputModality> = {
162 text: 'text',
163 image: 'image',
164 audio: 'audio',
165 video: 'video',
166 file: 'document',
167 document: 'document',
169​
170/**
171 * Map OpenRouter input modalities to our standard modality types.
172 * Same mapping as the existing convert-openrouter-models.ts script.
173 */
174function mapInputModalities(modalities: Array<string>): Array<InputModality> {
175 const mapped = modalities
176 .map((m) => MODALITY_MAP[m.toLowerCase()])
177 .filter((m): m is InputModality => m !== undefined)
178 // Ensure at least 'text' is present
179 if (!mapped.includes('text')) {
180 mapped.unshift('text')
181 }
182 return mapped
184​
185/** Strip the provider prefix from an OpenRouter model ID */
186function stripPrefix(prefix: string, modelId: string): string {
187 return modelId.slice(prefix.length)
189​
190/**
191 * Convert a model ID (after prefix stripping) to a TypeScript constant name.
192 * E.g. 'gpt-6' -> 'GPT_6', 'grok-4.20-multi-agent' -> 'GROK_4_20_MULTI_AGENT'
193 */
194function toConstName(prefix: string, modelId: string): string {
195 const stripped = stripPrefix(prefix, modelId)
196 return stripped
197 .replace(/[-]/g, '_')
198 .replace(/[.]/g, '_')
199 .replace(/[:]/g, '_')
200 .replace(/[/]/g, '_')
201 .toUpperCase()
203​
204/**
205 * Convert an OpenRouter price string to per-million-token pricing.
206 * Same logic as the existing convert script.
207 */
208function convertPrice(priceStr: string | undefined): number {
209 const price = parseFloat(priceStr ?? '0')
210 if (isNaN(price)) return 0
211 const result = price * 1_000_000
212 return Math.round(result * 1e10) / 1e10
214​
215/**
216 * Normalize a model ID for comparison.
217 * Handles cases where the same model uses dots vs dashes
218 * (e.g., Anthropic's 'claude-3-5-haiku' vs OpenRouter's 'claude-3.5-haiku').
219 */
220function normalizeId(id: string): string {
221 return id.replace(/[.]/g, '-')
223​
224/**
225 * Extract existing model IDs from a model-meta file.
226 * Matches BOTH name: 'xxx' AND id: 'xxx' lines to get a complete set,
227 * since providers like Anthropic use different naming between name and id.
228 * Returns a normalized set for comparison purposes.
229 */
230function extractExistingModelIds(content: string): Set<string> {
231 const ids = new Set<string>()
232 // Match both name and id fields inside const blocks
233 const nameRegex = /^\s+name:\s*'([^']+)'/gm
234 const idRegex = /^\s+id:\s*'([^']+)'/gm
235 let match
236 while ((match = nameRegex.exec(content)) !== null) {
237 ids.add(normalizeId(match[1]!))
238 }
239 while ((match = idRegex.exec(content)) !== null) {
240 ids.add(normalizeId(match[1]!))
241 }
242 return ids
244​
245/**
246 * Extract existing constant names from a model-meta file.
247 * Matches: const UPPER_CASE_NAME =
248 */
249function extractExistingConstNames(content: string): Set<string> {
250 const names = new Set<string>()
251 const regex = /^const\s+([A-Z][A-Z0-9_]+)\s*=/gm
252 let match
253 while ((match = regex.exec(content)) !== null) {
254 names.add(match[1]!)
255 }
256 return names
258​
259/**
260 * Check if an OpenRouter model outputs text (for chat model array).
261 */
262function outputsText(model: OpenRouterModel): boolean {
263 return model.architecture.output_modalities.includes('text')
265​
266/**
267 * Check if an OpenRouter model outputs ONLY images (no text output).
268 * Image-only models are skipped entirely because image model arrays
269 * require manual curation with specialized type maps (sizes, provider options).
270 */
271function isImageOnlyModel(model: OpenRouterModel): boolean {
272 return (
273 model.architecture.output_modalities.includes('image') &&
274 !model.architecture.output_modalities.includes('text')
275 )
277​
278/**
279 * Non-chat model family prefixes to exclude from chat model arrays.
280 * These are audio/music/video/image generation models that happen to
281 * include 'text' in their output modalities but are not chat models.
282 */
283const NON_CHAT_MODEL_PREFIXES = [
284 'lyria-', // Google music generation
285 'veo-', // Google video generation
286 'imagen-', // Google image generation
287 'sora-', // OpenAI video generation
288 'dall-e-', // OpenAI image generation
289 'tts-', // Text-to-speech models
291​
292function isNonChatModel(strippedId: string): boolean {
293 return NON_CHAT_MODEL_PREFIXES.some((p) => strippedId.startsWith(p))
295​
296/**
297 * Check if a model should be skipped based on provider-specific patterns.
298 */
299function matchesSkipPattern(
300 strippedId: string,
301 patterns: Array<string>,
302): boolean {
303 return patterns.some((p) => strippedId.startsWith(p))
305​
306/**
307 * Read the last sync run timestamp. Returns epoch seconds, or null if no previous run.
308 */
309async function readLastRunTimestamp(): Promise<number | null> {
310 try {
311 const content = await readFile(LAST_RUN_FILE, 'utf-8')
312 const ts = parseInt(content.trim(), 10)
313 return isNaN(ts) ? null : ts
314 } catch {
315 return null
316 }
318​
319/**
320 * Write the current timestamp as the last sync run.
321 */
322async function writeLastRunTimestamp(): Promise<void> {
323 const now = Math.floor(Date.now() / 1000)
324 await writeFile(LAST_RUN_FILE, String(now) + '\n', 'utf-8')
326​
327/**
328 * Check if a model is too old to sync. Models created more than 30 days
329 * before the last sync run are considered deprecated/legacy and skipped.
330 */
331function isModelTooOld(
332 model: OpenRouterModel,
333 cutoffTimestamp: number,
334): boolean {
335 if (!model.created) return false // No date = don't skip
336 return model.created < cutoffTimestamp
338​
339// ---------------------------------------------------------------------------
340// Model constant generation
341// ---------------------------------------------------------------------------
342​
343function generateModelConstant(
344 model: OpenRouterModel,
345 prefix: string,
346 config: ProviderConfig,
347): string {
348 const constName = toConstName(prefix, model.id)
349 const strippedId = stripPrefix(prefix, model.id)
350​
351 const inputNormal = convertPrice(model.pricing.prompt)
352 const inputCached = convertPrice(model.pricing.input_cache_read)
353 const outputNormal = convertPrice(model.pricing.completion)
354​
355 // Use actual input modalities from OpenRouter data, filtered to what this provider supports
356 const inputModalities = mapInputModalities(
357 model.architecture.input_modalities,
358 ).filter((m) => config.validInputModalities.includes(m))
359 const inputModalitiesStr = inputModalities.map((m) => `'${m}'`).join(', ')
360​
361 const lines: Array<string> = []
362 lines.push(`const ${constName} = {`)
363​
364 // name field
365 lines.push(` name: '${strippedId}',`)
366​
367 // id field (Anthropic has both name and id, set to same value for new models)
368 if (config.hasBothNameAndId) {
369 lines.push(` id: '${strippedId}',`)
370 }
371​
372 // context / max_input_tokens
373 if (model.context_length > 0) {
374 lines.push(
375 ` ${config.contextField}: ${formatNumber(model.context_length)},`,
376 )
377 }
378​
379 // max_output_tokens
380 if (model.top_provider.max_completion_tokens) {
381 lines.push(
382 ` max_output_tokens: ${formatNumber(model.top_provider.max_completion_tokens)},`,
383 )
384 }
385​
386 // supports block (actual input modalities + reference capabilities)
387 lines.push(` supports: {`)
388 lines.push(` input: [${inputModalitiesStr}],`)
389 lines.push(config.referenceSupportsBody)
390 lines.push(` },`)
391​
392 // pricing
393 lines.push(` pricing: {`)
394 lines.push(` input: {`)
395 lines.push(` normal: ${inputNormal},`)
396 if (inputCached > 0) {
397 lines.push(` cached: ${inputCached},`)
398 }
399 lines.push(` },`)
400 lines.push(` output: {`)
401 lines.push(` normal: ${outputNormal},`)
402 lines.push(` },`)
403 lines.push(` },`)
404​
405 lines.push(`} as const satisfies ${config.referenceSatisfies}`)
406​
407 return lines.join('\n')
409​
410/**
411 * Format a number with underscore separators for readability.
412 * E.g. 131072 -> '131_072', 200000 -> '200_000'
413 */
414function formatNumber(n: number): string {
415 if (n < 1000) return String(n)
416 const str = String(n)
417 // Insert underscores every 3 digits from the right
418 const parts: Array<string> = []
419 let remaining = str
420 while (remaining.length > 3) {
421 parts.unshift(remaining.slice(-3))
422 remaining = remaining.slice(0, -3)
423 }
424 parts.unshift(remaining)
425 return parts.join('_')
427​
428// ---------------------------------------------------------------------------
429// File modification
430// ---------------------------------------------------------------------------
431​
432/**
433 * Insert new model constants before the first `export` statement.
434 */
435function insertConstants(content: string, constants: Array<string>): string {
436 const block = '\n' + constants.join('\n\n') + '\n'
437 // Find the first `\nexport ` that is not inside a comment
438 const exportIndex = content.indexOf('\nexport ')
439 if (exportIndex === -1) {
440 // Fallback: append before end of file
441 return content + block
442 }
443 return content.slice(0, exportIndex) + block + content.slice(exportIndex)
445​
446/**
447 * Add entries to an array like: export const ARRAY_NAME = [ ... ] as const
448 * Uses a regex with the `s` flag (dotAll) to match across newlines.
449 */
450function addToArray(
451 content: string,
452 arrayName: string,
453 entries: Array<string>,
454 arrayRef: string,
455): string {
456 // Match the array declaration: export const ARRAY_NAME = [...] as const
457 // Uses [\s\S]*? (non-greedy) instead of [^\]]* to handle ] inside comments
458 const pattern = new RegExp(
459 `(export const ${arrayName} = \\[\\s*[\\s\\S]*?)(\\] as const)`,
460 )
461 const match = pattern.exec(content)
462 if (!match) {
463 console.warn(` Warning: Could not find array '${arrayName}' in file`)
464 return content
465 }
466​
467 const newEntries = entries
468 .map((constName) => ` ${constName}${arrayRef},`)
469 .join('\n')
470 // Use replacer function to prevent $-character interpretation in replacement string
471 return content.replace(
472 pattern,
473 () => `${match[1]}\n${newEntries}\n${match[2]}`,
474 )
476​
477/**
478 * Add entries to a type map like:
479 * export type TypeName = {
480 * ...existing entries...
481 * }
482 */
483function addToTypeMap(
484 content: string,
485 typeName: string,
486 entries: Array<string>,
487): string {
488 // Match: export type TypeName = { ... \n}
489 const pattern = new RegExp(
490 `(export type ${typeName} = \\{[\\s\\S]*?)(\\n\\})`,
491 )
492 const match = pattern.exec(content)
493 if (!match) {
494 console.warn(` Warning: Could not find type map '${typeName}' in file`)
495 return content
496 }
497​
498 const newEntries = entries.join('\n')
499 // Use replacer function to prevent $-character interpretation in replacement string
500 return content.replace(pattern, () => `${match[1]}\n${newEntries}${match[2]}`)
502​
503// ---------------------------------------------------------------------------
504// Git-based change detection
505// ---------------------------------------------------------------------------
506​
507/**
508 * Detect packages with uncommitted changes by running `git diff`.
509 * This captures changes from ALL prior pipeline steps (e.g. convert-openrouter-models.ts)
510 * not just the models added by this script.
511 */
512function detectChangedPackages(): Set<string> {
513 const changed = new Set<string>()
514 try {
515 const diff = execFileSync(
516 'git',
517 ['diff', 'HEAD', '--name-only', '--', 'packages/'],
518 { encoding: 'utf-8', cwd: ROOT },
519 ).trim()
520 if (!diff) return changed
521​
522 for (const line of diff.split('\n')) {
523 // packages/typescript/ai-openrouter/... → @tanstack/ai-openrouter
524 const match = line.match(/^packages\/typescript\/([\w-]+)\//)
525 if (match) {
526 changed.add(`@tanstack/${match[1]}`)
527 }
528 }
529 } catch {
530 // git not available (e.g. running outside a repo) — fall back to empty set
531 }
532 return changed
534​
535// ---------------------------------------------------------------------------
536// Main
537// ---------------------------------------------------------------------------
538​
539async function main() {
540 let totalAdded = 0
541 const changedPackages = new Set<string>()
542​
543 // Determine age cutoff: skip models created >30 days before last run
544 const lastRun = await readLastRunTimestamp()
545 const now = Math.floor(Date.now() / 1000)
546 const cutoffTimestamp = (lastRun ?? now) - MAX_MODEL_AGE_SECONDS
547 const cutoffDate = new Date(cutoffTimestamp * 1000)
548 .toISOString()
549 .split('T')[0]
550 console.log(
551 `Model age cutoff: ${cutoffDate} (skipping models created before this date)`,
552 )
553​
554 for (const [prefix, config] of Object.entries(PROVIDER_MAP)) {
555 console.log(`\nProcessing provider: ${prefix}`)
556​
557 // Filter OpenRouter models for this prefix
558 const providerModels = models.filter((m) => m.id.startsWith(prefix))
559 console.log(
560 ` Found ${providerModels.length} OpenRouter models with prefix '${prefix}'`,
561 )
562​
563 // Read the provider's model-meta.ts
564 let content: string
565 try {
566 content = await readFile(config.metaFile, 'utf-8')
567 } catch {
568 console.warn(` Skipping: could not read ${config.metaFile}`)
569 continue
570 }
571​
572 // Extract existing model IDs (normalized) and constant names
573 const existingIds = extractExistingModelIds(content)
574 const existingConstNames = extractExistingConstNames(content)
575​
576 console.log(
577 ` Existing models in file: ${existingIds.size} IDs, ${existingConstNames.size} constants`,
578 )
579​
580 // Find new models
581 const newModels: Array<{
582 model: OpenRouterModel
583 constName: string
584 strippedId: string
585 }> = []
586​
587 for (const model of providerModels) {
588 const strippedId = stripPrefix(prefix, model.id)
589 const constName = toConstName(prefix, model.id)
590​
591 // Skip models with ':' variants (e.g., 'anthropic/claude-3.7-sonnet:thinking')
592 // These are routing variants, not separate models
593 if (strippedId.includes(':')) {
594 continue
595 }
596​
597 // Skip non-chat model families (audio/music/video/image generation)
598 if (isNonChatModel(strippedId)) {
599 continue
600 }
601​
602 // Skip provider-specific patterns (deprecated/legacy model families)
603 if (matchesSkipPattern(strippedId, config.skipPatterns)) {
604 continue
605 }
606​
607 // Skip models that are too old (created >30 days before last sync)
608 if (isModelTooOld(model, cutoffTimestamp)) {
609 continue
610 }
611​
612 // Normalize for comparison to handle dots-vs-dashes naming differences
613 if (
614 !existingIds.has(normalizeId(strippedId)) &&
615 !existingConstNames.has(constName)
616 ) {
617 newModels.push({ model, constName, strippedId })
618 }
619 }
620​
621 if (newModels.length === 0) {
622 console.log(' No new models to add.')
623 continue
624 }
625​
626 console.log(` Adding ${newModels.length} new models:`)
627 for (const { strippedId, constName } of newModels) {
628 console.log(` - ${strippedId} (${constName})`)
629 }
630​
631 // Filter out image-only models (they need manual curation for size/provider type maps)
632 const filteredModels = newModels.filter(
633 ({ model }) => !isImageOnlyModel(model),
634 )
635 const skippedImageOnly = newModels.length - filteredModels.length
636 if (skippedImageOnly > 0) {
637 console.log(
638 ` Skipping ${skippedImageOnly} image-only models (require manual curation)`,
639 )
640 }
641​
642 if (filteredModels.length === 0) {
643 console.log(' No eligible models to add after filtering.')
644 continue
645 }
646​
647 // Generate constants
648 const constants = filteredModels.map(({ model }) =>
649 generateModelConstant(model, prefix, config),
650 )
651​
652 // Insert constants before first export
653 content = insertConstants(content, constants)
654​
655 // Filter to chat-eligible models: must output text
656 const chatModels = filteredModels.filter(({ model }) => outputsText(model))
657​
658 if (chatModels.length > 0) {
659 content = addToArray(
660 content,
661 config.chatArrayName,
662 chatModels.map(({ constName }) => constName),
663 config.arrayRef,
664 )
665 }
666​
667 // NOTE: We intentionally do NOT add models to image arrays.
668 // Image model arrays have specialized type maps (sizes, provider options)
669 // that require manual curation.
670​
671 // Add to provider options type map (skip for Grok - uses mapped type)
672 if (!config.providerOptionsIsMappedType && chatModels.length > 0) {
673 const providerOptionsEntries = chatModels.map(
674 ({ constName }) =>
675 ` [${constName}${config.arrayRef}]: ${config.referenceProviderOptionsEntry}`,
676 )
677 if (providerOptionsEntries.length > 0) {
678 content = addToTypeMap(
679 content,
680 config.providerOptionsTypeName,
681 providerOptionsEntries,
682 )
683 }
684 }
685​
686 // Add to input modalities type map
687 const modalityEntries = chatModels.map(
688 ({ constName }) =>
689 ` [${constName}${config.arrayRef}]: typeof ${constName}.supports.input`,
690 )
691 if (modalityEntries.length > 0) {
692 content = addToTypeMap(
693 content,
694 config.inputModalitiesTypeName,
695 modalityEntries,
696 )
697 }
698​
699 // Write the modified file
700 await writeFile(config.metaFile, content, 'utf-8')
701 console.log(` Wrote updated file: ${config.metaFile}`)
702 totalAdded += filteredModels.length
703 changedPackages.add(config.packageName)
704 }
705​
706 console.log(`\nDone. Added ${totalAdded} new models total.`)
707​
708 // Record this run's timestamp for future age-based filtering
709 await writeLastRunTimestamp()
710​
711 // Detect all packages with uncommitted changes (includes changes from
712 // convert-openrouter-models.ts which runs before this script)
713 const allChangedPackages = detectChangedPackages()
714 for (const pkg of changedPackages) {
715 allChangedPackages.add(pkg)
716 }
717​
718 if (allChangedPackages.size > 0) {
719 await createChangeset(allChangedPackages)
720 }
722​
723/**
724 * Create or update the sync-models changeset file.
725 * If one already exists, merges the package lists. Otherwise creates a new one.
726 */
727async function createChangeset(changedPackages: Set<string>) {
728 const changesetDir = resolve(ROOT, '.changeset')
729 const { readdir } = await import('node:fs/promises')
730 const files = await readdir(changesetDir)
731 const existing = files.find(
732 (f) => f.startsWith('sync-models') && f.endsWith('.md'),
733 )
734​
735 if (existing) {
736 const existingPath = resolve(changesetDir, existing)
737 const existingContent = await readFile(existingPath, 'utf-8')
738​
739 // Merge existing packages into the set
740 const pkgRegex = /'([^']+)':\s*patch/g
741 let match
742 while ((match = pkgRegex.exec(existingContent)) !== null) {
743 changedPackages.add(match[1]!)
744 }
745​
746 const content = buildChangesetContent(changedPackages)
747 await writeFile(existingPath, content, 'utf-8')
748 console.log(`\nChangeset updated: ${existingPath}`)
749 } else {
750 const changesetFile = resolve(changesetDir, 'sync-models.md')
751 const content = buildChangesetContent(changedPackages)
752 await writeFile(changesetFile, content, 'utf-8')
753 console.log(`\nChangeset created: ${changesetFile}`)
754 }
755​
756 console.log(` Packages: ${Array.from(changedPackages).sort().join(', ')}`)
758​
759function buildChangesetContent(packages: Set<string>): string {
760 const packageLines = Array.from(packages)
761 .sort()
762 .map((pkg) => `'${pkg}': patch`)
763 .join('\n')
764 return `---\n${packageLines}\n---\n\nUpdate model metadata from OpenRouter API\n`
766​
767main().catch((err) => {
768 console.error(err)
769 process.exit(1)
770})