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

sync-provider-models.ts

755 lines26.6 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 * ## Providers deliberately NOT synced
14 *
15 * The sync is only safe when the provider's own model ids can be derived from
16 * OpenRouter's. Adding an entry to `PROVIDER_MAP` for a provider where that
17 * doesn't hold generates ids that 404 at request time, which is worse than no
18 * automation. These are excluded on purpose:
19 *
20 * - **byteplus** (`@tanstack/ai-byteplus`) — OpenRouter lists the same models
21 * under undated slugs (`bytedance-seed/seed-1.6`), but BytePlus Ark
22 * addresses them by *date-suffixed* id (`seed-1-6-250615`), and the suffix
23 * is not derivable from anything OpenRouter publishes. Ark's own `GET
24 * /models` is the catalog, and it is not exhaustive. On top of that the
25 * package's capability tables are live-probe-verified specifically because
26 * the published metadata is wrong in both directions, so a metadata-driven
27 * sync would overwrite probed facts with worse ones. Use `/gap-analysis
28 * byteplus` instead; the probe recipe is in that package's `model-meta.ts`.
29 * - **fal** — media-only provider whose endpoint ids are not OpenRouter
30 * models. fal image fields have their own generator
31 * (`scripts/generate-fal-image-field-map.ts`).
32 * - **elevenlabs** — text-to-speech, music, sound effects, and voice design
33 * ids come from modelschemas via `scripts/sync-elevenlabs-models.ts`, not
34 * OpenRouter. Transcription stays hand-maintained.
35 * - **bedrock** — ids are AWS-region-qualified; see
36 * `scripts/fetch-bedrock-models.ts`.
37 */
38​
39import { execFileSync } from 'node:child_process'
40import { readFile, writeFile } from 'node:fs/promises'
41import { dirname, resolve } from 'node:path'
42import { fileURLToPath } from 'node:url'
43import {
44 isRoutingAlias,
45 toModelConstName,
46 toNativeProviderId,
47} from './model-sync/ids'
48import {
49 applyChatModelCatalogInserts,
50 insertConstants,
51} from './model-sync/native-insert'
52import {
53 buildAnthropicProviderOptionsType,
54 buildProviderSupportsBody,
55} from './model-sync/provider-supports'
56import type { SyncedProvider } from './model-sync/provider-supports'
57import { models } from './openrouter.models'
58import type { OpenRouterModel } from './openrouter.models'
59​
60const __dirname = dirname(fileURLToPath(import.meta.url))
61const ROOT = resolve(__dirname, '..')
62​
63// ---------------------------------------------------------------------------
64// Provider configuration
65// ---------------------------------------------------------------------------
66​
67/** Seconds in 30 days — models older than this before the last sync are skipped */
68const MAX_MODEL_AGE_SECONDS = 30 * 24 * 60 * 60
69const LAST_RUN_FILE = resolve(ROOT, 'scripts/.sync-models-last-run')
70​
71interface ProviderConfig {
72 /** npm package name for changeset */
73 packageName: string
74 metaFile: string
75 /** How array entries reference the constant, e.g. '.name' or '.id' */
76 arrayRef: '.name' | '.id'
77 /** Which field name is used for context window size */
78 contextField: 'context_window' | 'max_input_tokens'
79 /** Name of the exported chat model array */
80 chatArrayName: string
81 /** Name of the provider options type map */
82 providerOptionsTypeName: string
83 /** Name of the input modalities type map */
84 inputModalitiesTypeName: string
85 /**
86 * Name of the per-model tool-capabilities type map. Missing this lets
87 * `ResolveToolCapabilities` fall back to `readonly []` and every provider
88 * tool stops type-checking on the new model.
89 */
90 toolCapabilitiesTypeName?: string
91 /**
92 * Name of the runtime `Record<string, number>` mapping model id →
93 * `max_output_tokens`, if the provider maintains one. Anthropic uses this to
94 * default the required `max_tokens` request field to the model's real ceiling
95 * (issue #849); other providers treat token limits as optional and omit it.
96 */
97 maxOutputTokensMapName?: string
98 /**
99 * Runtime set of models that accept tools plus `output_config.format` in
100 * one request. New Anthropic ids are inserted here. `-fast` variants stay
101 * out: fast mode is a request parameter, not a model id, and the model-meta
102 * test expects every registered model in the set.
103 */
104 combinedToolsAndSchemaSetName?: string
105 /** Provider key for conservative supports generation */
106 kind: SyncedProvider
107 /** Valid input modality types for this provider's ModelMeta interface */
108 validInputModalities: Array<InputModality>
109 /** The satisfies type clause (after 'as const satisfies') */
110 referenceSatisfies: string
111 /** The type string for provider options map entries */
112 referenceProviderOptionsEntry: string
113 /** Whether this provider has both name AND id fields */
114 hasBothNameAndId: boolean
115 /** Whether the provider options type is a mapped type (skip insertion) */
116 providerOptionsIsMappedType: boolean
117 /** Model ID patterns to always skip (matched against stripped ID) */
118 skipPatterns: Array<string>
120​
121const PROVIDER_MAP: Record<string, ProviderConfig> = {
122 'openai/': {
123 packageName: '@tanstack/ai-openai',
124 metaFile: resolve(ROOT, 'packages/ai-openai/src/model-meta.ts'),
125 arrayRef: '.name',
126 contextField: 'context_window',
127 chatArrayName: 'OPENAI_CHAT_MODELS',
128 providerOptionsTypeName: 'OpenAIChatModelProviderOptionsByName',
129 inputModalitiesTypeName: 'OpenAIModelInputModalitiesByName',
130 toolCapabilitiesTypeName: 'OpenAIChatModelToolCapabilitiesByName',
131 validInputModalities: ['text', 'image', 'audio', 'video'],
132 kind: 'openai',
133 referenceSatisfies:
134 'ModelMeta<OpenAIBaseOptions & OpenAIStructuredOutputOptions & OpenAIToolsOptions & OpenAIStreamingOptions & OpenAIMetadataOptions>',
135 referenceProviderOptionsEntry:
136 'OpenAIBaseOptions & OpenAIStructuredOutputOptions & OpenAIToolsOptions & OpenAIStreamingOptions & OpenAIMetadataOptions',
137 hasBothNameAndId: false,
138 providerOptionsIsMappedType: false,
139 skipPatterns: [
140 'gpt-3.5-', // Legacy GPT-3.5 models
141 'gpt-4-', // Legacy GPT-4 base models (not 4.1+)
142 'gpt-4o', // GPT-4o variants (4o, 4o-mini, 4o-audio, etc.)
143 'gpt-oss-', // Open-source/experimental models
144 'chatgpt-', // ChatGPT branded models
145 ],
146 },
147 'anthropic/': {
148 packageName: '@tanstack/ai-anthropic',
149 metaFile: resolve(ROOT, 'packages/ai-anthropic/src/model-meta.ts'),
150 arrayRef: '.id',
151 contextField: 'context_window',
152 chatArrayName: 'ANTHROPIC_MODELS',
153 providerOptionsTypeName: 'AnthropicChatModelProviderOptionsByName',
154 inputModalitiesTypeName: 'AnthropicModelInputModalitiesByName',
155 toolCapabilitiesTypeName: 'AnthropicChatModelToolCapabilitiesByName',
156 maxOutputTokensMapName: 'ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS',
157 combinedToolsAndSchemaSetName: 'ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS',
158 validInputModalities: ['text', 'image', 'audio', 'video', 'document'],
159 kind: 'anthropic',
160 referenceSatisfies:
161 'ModelMeta<AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & AnthropicToolChoiceOptions & AnthropicSamplingOptions>',
162 referenceProviderOptionsEntry:
163 'AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & AnthropicToolChoiceOptions & AnthropicSamplingOptions',
164 hasBothNameAndId: true,
165 providerOptionsIsMappedType: false,
166 skipPatterns: [],
167 },
168 'google/': {
169 packageName: '@tanstack/ai-gemini',
170 metaFile: resolve(ROOT, 'packages/ai-gemini/src/model-meta.ts'),
171 arrayRef: '.name',
172 contextField: 'max_input_tokens',
173 chatArrayName: 'GEMINI_MODELS',
174 providerOptionsTypeName: 'GeminiChatModelProviderOptionsByName',
175 inputModalitiesTypeName: 'GeminiModelInputModalitiesByName',
176 toolCapabilitiesTypeName: 'GeminiChatModelToolCapabilitiesByName',
177 validInputModalities: ['text', 'image', 'audio', 'video', 'document'],
178 kind: 'gemini',
179 referenceSatisfies:
180 'ModelMeta<GeminiToolConfigOptions & GeminiSafetyOptions & GeminiCommonConfigOptions & GeminiCachedContentOptions & GeminiStructuredOutputOptions>',
181 referenceProviderOptionsEntry:
182 'GeminiToolConfigOptions & GeminiSafetyOptions & GeminiCommonConfigOptions & GeminiCachedContentOptions & GeminiStructuredOutputOptions',
183 hasBothNameAndId: false,
184 providerOptionsIsMappedType: false,
185 skipPatterns: [
186 'gemma-', // Gemma open-source models (not Gemini API models)
187 ],
188 },
189 'x-ai/': {
190 packageName: '@tanstack/ai-grok',
191 metaFile: resolve(ROOT, 'packages/ai-grok/src/model-meta.ts'),
192 arrayRef: '.name',
193 contextField: 'context_window',
194 chatArrayName: 'GROK_CHAT_MODELS',
195 providerOptionsTypeName: 'GrokChatModelProviderOptionsByName',
196 inputModalitiesTypeName: 'GrokModelInputModalitiesByName',
197 toolCapabilitiesTypeName: 'GrokChatModelToolCapabilitiesByName',
198 validInputModalities: ['text', 'image', 'audio', 'video', 'document'],
199 kind: 'grok',
200 referenceSatisfies: 'ModelMeta',
201 referenceProviderOptionsEntry: 'GrokProviderOptions',
202 hasBothNameAndId: false,
203 providerOptionsIsMappedType: true,
204 skipPatterns: [],
205 },
207​
208// ---------------------------------------------------------------------------
209// Utility functions
210// ---------------------------------------------------------------------------
211​
212type InputModality = 'text' | 'image' | 'audio' | 'video' | 'document'
213​
214const MODALITY_MAP: Record<string, InputModality> = {
215 text: 'text',
216 image: 'image',
217 audio: 'audio',
218 video: 'video',
219 file: 'document',
220 document: 'document',
222​
223/**
224 * Map OpenRouter input modalities to our standard modality types.
225 * Same mapping as the existing convert-openrouter-models.ts script.
226 */
227function mapInputModalities(modalities: Array<string>): Array<InputModality> {
228 const mapped = modalities
229 .map((m) => MODALITY_MAP[m.toLowerCase()])
230 .filter((m): m is InputModality => m !== undefined)
231 // Ensure at least 'text' is present
232 if (!mapped.includes('text')) {
233 mapped.unshift('text')
234 }
235 return mapped
237​
238/** Strip the provider prefix from an OpenRouter model ID */
239function stripPrefix(prefix: string, modelId: string): string {
240 return modelId.slice(prefix.length)
242​
243/**
244 * Convert an OpenRouter price string to per-million-token pricing.
245 * Same logic as the existing convert script.
246 */
247function convertPrice(priceStr: string | undefined): number {
248 const price = parseFloat(priceStr ?? '0')
249 if (isNaN(price)) return 0
250 const result = price * 1_000_000
251 return Math.round(result * 1e10) / 1e10
253​
254function anthropicOptionsType(model: OpenRouterModel): string {
255 return buildAnthropicProviderOptionsType({
256 supportedParameters: model.supported_parameters,
257 hasCachedPricing: convertPrice(model.pricing.input_cache_read) > 0,
258 })
260​
261function providerOptionsEntryFor(
262 model: OpenRouterModel,
263 config: ProviderConfig,
264): string {
265 if (config.kind === 'anthropic') return anthropicOptionsType(model)
266 return config.referenceProviderOptionsEntry
268​
269function satisfiesClause(
270 model: OpenRouterModel,
271 config: ProviderConfig,
272): string {
273 if (config.kind === 'anthropic') {
274 return `ModelMeta<${anthropicOptionsType(model)}>`
275 }
276 return config.referenceSatisfies
278​
279/**
280 * Normalize a model ID for comparison.
281 * Handles cases where the same model uses dots vs dashes
282 * (e.g., Anthropic's 'claude-3-5-haiku' vs OpenRouter's 'claude-3.5-haiku').
283 */
284function normalizeId(id: string): string {
285 return id.replace(/[.]/g, '-')
287​
288/**
289 * Extract existing model IDs from a model-meta file.
290 * Matches BOTH name: 'xxx' AND id: 'xxx' lines to get a complete set,
291 * since providers like Anthropic use different naming between name and id.
292 * Returns a normalized set for comparison purposes.
293 */
294function extractExistingModelIds(content: string): Set<string> {
295 const ids = new Set<string>()
296 // Match both name and id fields inside const blocks
297 const nameRegex = /^\s+name:\s*'([^']+)'/gm
298 const idRegex = /^\s+id:\s*'([^']+)'/gm
299 let match
300 while ((match = nameRegex.exec(content)) !== null) {
301 ids.add(normalizeId(match[1]!))
302 }
303 while ((match = idRegex.exec(content)) !== null) {
304 ids.add(normalizeId(match[1]!))
305 }
306 return ids
308​
309/**
310 * Extract existing constant names from a model-meta file.
311 * Matches: const UPPER_CASE_NAME =
312 */
313function extractExistingConstNames(content: string): Set<string> {
314 const names = new Set<string>()
315 const regex = /^const\s+([A-Z][A-Z0-9_]+)\s*=/gm
316 let match
317 while ((match = regex.exec(content)) !== null) {
318 names.add(match[1]!)
319 }
320 return names
322​
323/**
324 * Check if an OpenRouter model outputs text (for chat model array).
325 */
326function outputsText(model: OpenRouterModel): boolean {
327 return model.architecture.output_modalities.includes('text')
329​
330/**
331 * Check if an OpenRouter model produces image output.
332 *
333 * Image-generation models are skipped entirely by the sync — regardless of
334 * whether they ALSO output text — because image model arrays require manual
335 * curation with specialized type maps (sizes, provider options, the native
336 * image union). This covers text+image "native" image models such as the
337 * Gemini "Nano Banana" family (`gemini-*-image`, e.g.
338 * `gemini-3.1-flash-lite-image`), which would otherwise be misclassified as
339 * chat models (they output text) and inserted with a bogus `output: ['text']`.
340 */
341function outputsImage(model: OpenRouterModel): boolean {
342 return model.architecture.output_modalities.includes('image')
344​
345/**
346 * Non-chat model family prefixes to exclude from chat model arrays.
347 * These are audio/music/video/image generation models that happen to
348 * include 'text' in their output modalities but are not chat models.
349 */
350const NON_CHAT_MODEL_PREFIXES = [
351 'lyria-', // Google music generation
352 'veo-', // Google video generation
353 'gemini-omni-', // Gemini Omni video (Interactions API), not chat
354 'imagen-', // Google image generation
355 'sora-', // OpenAI video generation
356 'dall-e-', // OpenAI image generation
357 'tts-', // Text-to-speech models
359​
360function isNonChatModel(strippedId: string): boolean {
361 return NON_CHAT_MODEL_PREFIXES.some((p) => strippedId.startsWith(p))
363​
364/**
365 * Check if a model should be skipped based on provider-specific patterns.
366 */
367function matchesSkipPattern(
368 strippedId: string,
369 patterns: Array<string>,
370): boolean {
371 return patterns.some((p) => strippedId.startsWith(p))
373​
374/**
375 * Read the last sync run timestamp. Returns epoch seconds, or null if no previous run.
376 */
377async function readLastRunTimestamp(): Promise<number | null> {
378 try {
379 const content = await readFile(LAST_RUN_FILE, 'utf-8')
380 const ts = parseInt(content.trim(), 10)
381 return isNaN(ts) ? null : ts
382 } catch {
383 return null
384 }
386​
387/**
388 * Write the current timestamp as the last sync run.
389 */
390async function writeLastRunTimestamp(): Promise<void> {
391 const now = Math.floor(Date.now() / 1000)
392 await writeFile(LAST_RUN_FILE, String(now) + '\n', 'utf-8')
394​
395/**
396 * Check if a model is too old to sync. Models created more than 30 days
397 * before the last sync run are considered deprecated/legacy and skipped.
398 */
399function isModelTooOld(
400 model: OpenRouterModel,
401 cutoffTimestamp: number,
402): boolean {
403 if (!model.created) return false // No date = don't skip
404 return model.created < cutoffTimestamp
406​
407// ---------------------------------------------------------------------------
408// Model constant generation
409// ---------------------------------------------------------------------------
410​
411function generateModelConstant(
412 model: OpenRouterModel,
413 prefix: string,
414 config: ProviderConfig,
415): string {
416 const strippedId = stripPrefix(prefix, model.id)
417 const nativeId = toNativeProviderId(strippedId, config.kind)
418 const constName = toModelConstName(nativeId)
419​
420 const inputNormal = convertPrice(model.pricing.prompt)
421 const inputCached = convertPrice(model.pricing.input_cache_read)
422 const outputNormal = convertPrice(model.pricing.completion)
423​
424 // Use actual input modalities from OpenRouter data, filtered to what this provider supports
425 const inputModalities = mapInputModalities(
426 model.architecture.input_modalities,
427 ).filter((m) => config.validInputModalities.includes(m))
428​
429 const lines: Array<string> = []
430 lines.push(`const ${constName} = {`)
431​
432 // name field
433 lines.push(` name: '${nativeId}',`)
434​
435 // id field (Anthropic has both name and id, set to same value for new models)
436 if (config.hasBothNameAndId) {
437 lines.push(` id: '${nativeId}',`)
438 }
439​
440 // context / max_input_tokens
441 if (model.context_length > 0) {
442 lines.push(
443 ` ${config.contextField}: ${formatNumber(model.context_length)},`,
444 )
445 }
446​
447 // max_output_tokens
448 if (model.top_provider.max_completion_tokens) {
449 lines.push(
450 ` max_output_tokens: ${formatNumber(model.top_provider.max_completion_tokens)},`,
451 )
452 }
453​
454 lines.push(` supports: {`)
455 lines.push(
456 buildProviderSupportsBody({
457 provider: config.kind,
458 inputModalities,
459 supportedParameters: model.supported_parameters,
460 reasoningMandatory: model.reasoning?.mandatory === true,
461 }),
462 )
463 lines.push(` },`)
464​
465 // pricing
466 lines.push(` pricing: {`)
467 lines.push(` input: {`)
468 lines.push(` normal: ${inputNormal},`)
469 if (inputCached > 0) {
470 lines.push(` cached: ${inputCached},`)
471 }
472 lines.push(` },`)
473 lines.push(` output: {`)
474 lines.push(` normal: ${outputNormal},`)
475 lines.push(` },`)
476 lines.push(` },`)
477​
478 lines.push(`} as const satisfies ${satisfiesClause(model, config)}`)
479​
480 return lines.join('\n')
482​
483/**
484 * Format a number with underscore separators for readability.
485 * E.g. 131072 -> '131_072', 200000 -> '200_000'
486 */
487function formatNumber(n: number): string {
488 if (n < 1000) return String(n)
489 const str = String(n)
490 // Insert underscores every 3 digits from the right
491 const parts: Array<string> = []
492 let remaining = str
493 while (remaining.length > 3) {
494 parts.unshift(remaining.slice(-3))
495 remaining = remaining.slice(0, -3)
496 }
497 parts.unshift(remaining)
498 return parts.join('_')
500​
501// ---------------------------------------------------------------------------
502// Git-based change detection
503// ---------------------------------------------------------------------------
504​
505/**
506 * Detect packages with uncommitted changes by running `git diff`.
507 * This captures changes from ALL prior pipeline steps (e.g. convert-openrouter-models.ts)
508 * not just the models added by this script.
509 */
510function detectChangedPackages(): Set<string> {
511 const changed = new Set<string>()
512 try {
513 const diff = execFileSync(
514 'git',
515 ['diff', 'HEAD', '--name-only', '--', 'packages/'],
516 { encoding: 'utf-8', cwd: ROOT },
517 ).trim()
518 if (!diff) return changed
519​
520 for (const line of diff.split('\n')) {
521 // packages/ai-openrouter/... → @tanstack/ai-openrouter
522 const match = line.match(/^packages\/([\w-]+)\//)
523 if (match) {
524 changed.add(`@tanstack/${match[1]}`)
525 }
526 }
527 } catch {
528 // git not available (e.g. running outside a repo) — fall back to empty set
529 }
530 return changed
532​
533// ---------------------------------------------------------------------------
534// Main
535// ---------------------------------------------------------------------------
536​
537async function main() {
538 let totalAdded = 0
539 const changedPackages = new Set<string>()
540​
541 // Determine age cutoff: skip models created >30 days before last run
542 const lastRun = await readLastRunTimestamp()
543 const now = Math.floor(Date.now() / 1000)
544 const cutoffTimestamp = (lastRun ?? now) - MAX_MODEL_AGE_SECONDS
545 const cutoffDate = new Date(cutoffTimestamp * 1000)
546 .toISOString()
547 .split('T')[0]
548 console.log(
549 `Model age cutoff: ${cutoffDate} (skipping models created before this date)`,
550 )
551​
552 for (const [prefix, config] of Object.entries(PROVIDER_MAP)) {
553 console.log(`\nProcessing provider: ${prefix}`)
554​
555 // Filter OpenRouter models for this prefix
556 const providerModels = models.filter((m) => m.id.startsWith(prefix))
557 console.log(
558 ` Found ${providerModels.length} OpenRouter models with prefix '${prefix}'`,
559 )
560​
561 // Read the provider's model-meta.ts
562 let content: string
563 try {
564 content = await readFile(config.metaFile, 'utf-8')
565 } catch {
566 console.warn(` Skipping: could not read ${config.metaFile}`)
567 continue
568 }
569​
570 // Extract existing model IDs (normalized) and constant names
571 const existingIds = extractExistingModelIds(content)
572 const existingConstNames = extractExistingConstNames(content)
573​
574 console.log(
575 ` Existing models in file: ${existingIds.size} IDs, ${existingConstNames.size} constants`,
576 )
577​
578 // Find new models
579 const newModels: Array<{
580 model: OpenRouterModel
581 constName: string
582 strippedId: string
583 }> = []
584​
585 for (const model of providerModels) {
586 if (isRoutingAlias(model.id)) {
587 continue
588 }
589​
590 const strippedId = stripPrefix(prefix, model.id)
591 const nativeId = toNativeProviderId(strippedId, config.kind)
592 const constName = toModelConstName(nativeId)
593​
594 // Skip models with ':' variants (e.g., 'anthropic/claude-3.7-sonnet:thinking')
595 // These are routing variants, not separate models
596 if (strippedId.includes(':')) {
597 continue
598 }
599​
600 // Skip non-chat model families (audio/music/video/image generation)
601 if (isNonChatModel(strippedId)) {
602 continue
603 }
604​
605 // Skip provider-specific patterns (deprecated/legacy model families)
606 if (matchesSkipPattern(strippedId, config.skipPatterns)) {
607 continue
608 }
609​
610 // Skip models that are too old (created >30 days before last sync)
611 if (isModelTooOld(model, cutoffTimestamp)) {
612 continue
613 }
614​
615 // Normalize for comparison to handle dots-vs-dashes naming differences
616 if (
617 !existingIds.has(normalizeId(strippedId)) &&
618 !existingConstNames.has(constName)
619 ) {
620 newModels.push({ model, constName, strippedId: nativeId })
621 }
622 }
623​
624 if (newModels.length === 0) {
625 console.log(' No new models to add.')
626 continue
627 }
628​
629 console.log(` Adding ${newModels.length} new models:`)
630 for (const { strippedId, constName } of newModels) {
631 console.log(` - ${strippedId} (${constName})`)
632 }
633​
634 // Filter out image-generation models (they need manual curation for
635 // size/provider type maps + the native image union). This includes
636 // text+image models like the Gemini "Nano Banana" native image family,
637 // not just image-only models.
638 const filteredModels = newModels.filter(({ model }) => !outputsImage(model))
639 const skippedImageModels = newModels.length - filteredModels.length
640 if (skippedImageModels > 0) {
641 console.log(
642 ` Skipping ${skippedImageModels} image-generation models (require manual curation)`,
643 )
644 }
645​
646 if (filteredModels.length === 0) {
647 console.log(' No eligible models to add after filtering.')
648 continue
649 }
650​
651 // Generate constants
652 const constants = filteredModels.map(({ model }) =>
653 generateModelConstant(model, prefix, config),
654 )
655​
656 // Insert constants before first export
657 content = insertConstants(content, constants)
658​
659 // NOTE: We intentionally do NOT add models to image arrays.
660 // Image model arrays have specialized type maps (sizes, provider options)
661 // that require manual curation.
662​
663 const chatModels = filteredModels.filter(({ model }) => outputsText(model))
664 content = applyChatModelCatalogInserts(
665 content,
666 {
667 chatArrayName: config.chatArrayName,
668 arrayRef: config.arrayRef,
669 providerOptionsTypeName: config.providerOptionsTypeName,
670 inputModalitiesTypeName: config.inputModalitiesTypeName,
671 toolCapabilitiesTypeName: config.toolCapabilitiesTypeName,
672 maxOutputTokensMapName: config.maxOutputTokensMapName,
673 combinedToolsAndSchemaSetName: config.combinedToolsAndSchemaSetName,
674 providerOptionsIsMappedType: config.providerOptionsIsMappedType,
675 },
676 chatModels.map(({ model, constName, strippedId }) => ({
677 constName,
678 providerOptionsEntry: providerOptionsEntryFor(model, config),
679 hasMaxOutputTokens: Boolean(model.top_provider.max_completion_tokens),
680 acceptsCombinedToolsAndSchema: !strippedId.endsWith('-fast'),
681 })),
682 )
683​
684 // Write the modified file
685 await writeFile(config.metaFile, content, 'utf-8')
686 console.log(` Wrote updated file: ${config.metaFile}`)
687 totalAdded += filteredModels.length
688 changedPackages.add(config.packageName)
689 }
690​
691 console.log(`\nDone. Added ${totalAdded} new models total.`)
692​
693 // Record this run's timestamp for future age-based filtering
694 await writeLastRunTimestamp()
695​
696 // Detect all packages with uncommitted changes (includes changes from
697 // convert-openrouter-models.ts which runs before this script)
698 const allChangedPackages = detectChangedPackages()
699 for (const pkg of changedPackages) {
700 allChangedPackages.add(pkg)
701 }
702​
703 if (allChangedPackages.size > 0) {
704 await createChangeset(allChangedPackages)
705 }
707​
708/**
709 * Create or update the sync-models changeset file.
710 * If one already exists, merges the package lists. Otherwise creates a new one.
711 */
712async function createChangeset(changedPackages: Set<string>) {
713 const changesetDir = resolve(ROOT, '.changeset')
714 const { readdir } = await import('node:fs/promises')
715 const files = await readdir(changesetDir)
716 const existing = files.find(
717 (f) => f.startsWith('sync-models') && f.endsWith('.md'),
718 )
719​
720 if (existing) {
721 const existingPath = resolve(changesetDir, existing)
722 const existingContent = await readFile(existingPath, 'utf-8')
723​
724 // Merge existing packages into the set
725 const pkgRegex = /'([^']+)':\s*patch/g
726 let match
727 while ((match = pkgRegex.exec(existingContent)) !== null) {
728 changedPackages.add(match[1]!)
729 }
730​
731 const content = buildChangesetContent(changedPackages)
732 await writeFile(existingPath, content, 'utf-8')
733 console.log(`\nChangeset updated: ${existingPath}`)
734 } else {
735 const changesetFile = resolve(changesetDir, 'sync-models.md')
736 const content = buildChangesetContent(changedPackages)
737 await writeFile(changesetFile, content, 'utf-8')
738 console.log(`\nChangeset created: ${changesetFile}`)
739 }
740​
741 console.log(` Packages: ${Array.from(changedPackages).sort().join(', ')}`)
743​
744function buildChangesetContent(packages: Set<string>): string {
745 const packageLines = Array.from(packages)
746 .sort()
747 .map((pkg) => `'${pkg}': patch`)
748 .join('\n')
749 return `---\n${packageLines}\n---\n\nUpdate model metadata from OpenRouter API\n`
751​
752main().catch((err) => {
753 console.error(err)
754 process.exit(1)
755})