Open History to see the last commit
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, and the model-meta test pins
102 * `claude-opus-5-fast` as excluded.
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>
119}
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 },
206}
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',
221}
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
236}
237
238/** Strip the provider prefix from an OpenRouter model ID */
239function stripPrefix(prefix: string, modelId: string): string {
240 return modelId.slice(prefix.length)
241}
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
252}
253
254function anthropicOptionsType(model: OpenRouterModel): string {
255 return buildAnthropicProviderOptionsType({
256 supportedParameters: model.supported_parameters,
257 hasCachedPricing: convertPrice(model.pricing.input_cache_read) > 0,
258 })
259}
260
261function providerOptionsEntryFor(
262 model: OpenRouterModel,
263 config: ProviderConfig,
264): string {
265 if (config.kind === 'anthropic') return anthropicOptionsType(model)
266 return config.referenceProviderOptionsEntry
267}
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
277}
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, '-')
286}
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
307}
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
321}
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')
328}
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')
343}
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 'imagen-', // Google image generation
354 'sora-', // OpenAI video generation
355 'dall-e-', // OpenAI image generation
356 'tts-', // Text-to-speech models
357]
358
359function isNonChatModel(strippedId: string): boolean {
360 return NON_CHAT_MODEL_PREFIXES.some((p) => strippedId.startsWith(p))
361}
362
363/**
364 * Check if a model should be skipped based on provider-specific patterns.
365 */
366function matchesSkipPattern(
367 strippedId: string,
368 patterns: Array<string>,
369): boolean {
370 return patterns.some((p) => strippedId.startsWith(p))
371}
372
373/**
374 * Read the last sync run timestamp. Returns epoch seconds, or null if no previous run.
375 */
376async function readLastRunTimestamp(): Promise<number | null> {
377 try {
378 const content = await readFile(LAST_RUN_FILE, 'utf-8')
379 const ts = parseInt(content.trim(), 10)
380 return isNaN(ts) ? null : ts
381 } catch {
382 return null
383 }
384}
385
386/**
387 * Write the current timestamp as the last sync run.
388 */
389async function writeLastRunTimestamp(): Promise<void> {
390 const now = Math.floor(Date.now() / 1000)
391 await writeFile(LAST_RUN_FILE, String(now) + '\n', 'utf-8')
392}
393
394/**
395 * Check if a model is too old to sync. Models created more than 30 days
396 * before the last sync run are considered deprecated/legacy and skipped.
397 */
398function isModelTooOld(
399 model: OpenRouterModel,
400 cutoffTimestamp: number,
401): boolean {
402 if (!model.created) return false // No date = don't skip
403 return model.created < cutoffTimestamp
404}
405
406// ---------------------------------------------------------------------------
407// Model constant generation
408// ---------------------------------------------------------------------------
409
410function generateModelConstant(
411 model: OpenRouterModel,
412 prefix: string,
413 config: ProviderConfig,
414): string {
415 const strippedId = stripPrefix(prefix, model.id)
416 const nativeId = toNativeProviderId(strippedId, config.kind)
417 const constName = toModelConstName(nativeId)
418
419 const inputNormal = convertPrice(model.pricing.prompt)
420 const inputCached = convertPrice(model.pricing.input_cache_read)
421 const outputNormal = convertPrice(model.pricing.completion)
422
423 // Use actual input modalities from OpenRouter data, filtered to what this provider supports
424 const inputModalities = mapInputModalities(
425 model.architecture.input_modalities,
426 ).filter((m) => config.validInputModalities.includes(m))
427
428 const lines: Array<string> = []
429 lines.push(`const ${constName} = {`)
430
431 // name field
432 lines.push(` name: '${nativeId}',`)
433
434 // id field (Anthropic has both name and id, set to same value for new models)
435 if (config.hasBothNameAndId) {
436 lines.push(` id: '${nativeId}',`)
437 }
438
439 // context / max_input_tokens
440 if (model.context_length > 0) {
441 lines.push(
442 ` ${config.contextField}: ${formatNumber(model.context_length)},`,
443 )
444 }
445
446 // max_output_tokens
447 if (model.top_provider.max_completion_tokens) {
448 lines.push(
449 ` max_output_tokens: ${formatNumber(model.top_provider.max_completion_tokens)},`,
450 )
451 }
452
453 lines.push(` supports: {`)
454 lines.push(
455 buildProviderSupportsBody({
456 provider: config.kind,
457 inputModalities,
458 supportedParameters: model.supported_parameters,
459 reasoningMandatory: model.reasoning?.mandatory === true,
460 }),
461 )
462 lines.push(` },`)
463
464 // pricing
465 lines.push(` pricing: {`)
466 lines.push(` input: {`)
467 lines.push(` normal: ${inputNormal},`)
468 if (inputCached > 0) {
469 lines.push(` cached: ${inputCached},`)
470 }
471 lines.push(` },`)
472 lines.push(` output: {`)
473 lines.push(` normal: ${outputNormal},`)
474 lines.push(` },`)
475 lines.push(` },`)
476
477 lines.push(`} as const satisfies ${satisfiesClause(model, config)}`)
478
479 return lines.join('\n')
480}
481
482/**
483 * Format a number with underscore separators for readability.
484 * E.g. 131072 -> '131_072', 200000 -> '200_000'
485 */
486function formatNumber(n: number): string {
487 if (n < 1000) return String(n)
488 const str = String(n)
489 // Insert underscores every 3 digits from the right
490 const parts: Array<string> = []
491 let remaining = str
492 while (remaining.length > 3) {
493 parts.unshift(remaining.slice(-3))
494 remaining = remaining.slice(0, -3)
495 }
496 parts.unshift(remaining)
497 return parts.join('_')
498}
499
500// ---------------------------------------------------------------------------
501// Git-based change detection
502// ---------------------------------------------------------------------------
503
504/**
505 * Detect packages with uncommitted changes by running `git diff`.
506 * This captures changes from ALL prior pipeline steps (e.g. convert-openrouter-models.ts)
507 * not just the models added by this script.
508 */
509function detectChangedPackages(): Set<string> {
510 const changed = new Set<string>()
511 try {
512 const diff = execFileSync(
513 'git',
514 ['diff', 'HEAD', '--name-only', '--', 'packages/'],
515 { encoding: 'utf-8', cwd: ROOT },
516 ).trim()
517 if (!diff) return changed
518
519 for (const line of diff.split('\n')) {
520 // packages/ai-openrouter/... → @tanstack/ai-openrouter
521 const match = line.match(/^packages\/([\w-]+)\//)
522 if (match) {
523 changed.add(`@tanstack/${match[1]}`)
524 }
525 }
526 } catch {
527 // git not available (e.g. running outside a repo) — fall back to empty set
528 }
529 return changed
530}
531
532// ---------------------------------------------------------------------------
533// Main
534// ---------------------------------------------------------------------------
535
536async function main() {
537 let totalAdded = 0
538 const changedPackages = new Set<string>()
539
540 // Determine age cutoff: skip models created >30 days before last run
541 const lastRun = await readLastRunTimestamp()
542 const now = Math.floor(Date.now() / 1000)
543 const cutoffTimestamp = (lastRun ?? now) - MAX_MODEL_AGE_SECONDS
544 const cutoffDate = new Date(cutoffTimestamp * 1000)
545 .toISOString()
546 .split('T')[0]
547 console.log(
548 `Model age cutoff: ${cutoffDate} (skipping models created before this date)`,
549 )
550
551 for (const [prefix, config] of Object.entries(PROVIDER_MAP)) {
552 console.log(`\nProcessing provider: ${prefix}`)
553
554 // Filter OpenRouter models for this prefix
555 const providerModels = models.filter((m) => m.id.startsWith(prefix))
556 console.log(
557 ` Found ${providerModels.length} OpenRouter models with prefix '${prefix}'`,
558 )
559
560 // Read the provider's model-meta.ts
561 let content: string
562 try {
563 content = await readFile(config.metaFile, 'utf-8')
564 } catch {
565 console.warn(` Skipping: could not read ${config.metaFile}`)
566 continue
567 }
568
569 // Extract existing model IDs (normalized) and constant names
570 const existingIds = extractExistingModelIds(content)
571 const existingConstNames = extractExistingConstNames(content)
572
573 console.log(
574 ` Existing models in file: ${existingIds.size} IDs, ${existingConstNames.size} constants`,
575 )
576
577 // Find new models
578 const newModels: Array<{
579 model: OpenRouterModel
580 constName: string
581 strippedId: string
582 }> = []
583
584 for (const model of providerModels) {
585 if (isRoutingAlias(model.id)) {
586 continue
587 }
588
589 const strippedId = stripPrefix(prefix, model.id)
590 const nativeId = toNativeProviderId(strippedId, config.kind)
591 const constName = toModelConstName(nativeId)
592
593 // Skip models with ':' variants (e.g., 'anthropic/claude-3.7-sonnet:thinking')
594 // These are routing variants, not separate models
595 if (strippedId.includes(':')) {
596 continue
597 }
598
599 // Skip non-chat model families (audio/music/video/image generation)
600 if (isNonChatModel(strippedId)) {
601 continue
602 }
603
604 // Skip provider-specific patterns (deprecated/legacy model families)
605 if (matchesSkipPattern(strippedId, config.skipPatterns)) {
606 continue
607 }
608
609 // Skip models that are too old (created >30 days before last sync)
610 if (isModelTooOld(model, cutoffTimestamp)) {
611 continue
612 }
613
614 // Normalize for comparison to handle dots-vs-dashes naming differences
615 if (
616 !existingIds.has(normalizeId(strippedId)) &&
617 !existingConstNames.has(constName)
618 ) {
619 newModels.push({ model, constName, strippedId: nativeId })
620 }
621 }
622
623 if (newModels.length === 0) {
624 console.log(' No new models to add.')
625 continue
626 }
627
628 console.log(` Adding ${newModels.length} new models:`)
629 for (const { strippedId, constName } of newModels) {
630 console.log(` - ${strippedId} (${constName})`)
631 }
632
633 // Filter out image-generation models (they need manual curation for
634 // size/provider type maps + the native image union). This includes
635 // text+image models like the Gemini "Nano Banana" native image family,
636 // not just image-only models.
637 const filteredModels = newModels.filter(({ model }) => !outputsImage(model))
638 const skippedImageModels = newModels.length - filteredModels.length
639 if (skippedImageModels > 0) {
640 console.log(
641 ` Skipping ${skippedImageModels} image-generation models (require manual curation)`,
642 )
643 }
644
645 if (filteredModels.length === 0) {
646 console.log(' No eligible models to add after filtering.')
647 continue
648 }
649
650 // Generate constants
651 const constants = filteredModels.map(({ model }) =>
652 generateModelConstant(model, prefix, config),
653 )
654
655 // Insert constants before first export
656 content = insertConstants(content, constants)
657
658 // NOTE: We intentionally do NOT add models to image arrays.
659 // Image model arrays have specialized type maps (sizes, provider options)
660 // that require manual curation.
661
662 const chatModels = filteredModels.filter(({ model }) => outputsText(model))
663 content = applyChatModelCatalogInserts(
664 content,
665 {
666 chatArrayName: config.chatArrayName,
667 arrayRef: config.arrayRef,
668 providerOptionsTypeName: config.providerOptionsTypeName,
669 inputModalitiesTypeName: config.inputModalitiesTypeName,
670 toolCapabilitiesTypeName: config.toolCapabilitiesTypeName,
671 maxOutputTokensMapName: config.maxOutputTokensMapName,
672 combinedToolsAndSchemaSetName: config.combinedToolsAndSchemaSetName,
673 providerOptionsIsMappedType: config.providerOptionsIsMappedType,
674 },
675 chatModels.map(({ model, constName, strippedId }) => ({
676 constName,
677 providerOptionsEntry: providerOptionsEntryFor(model, config),
678 hasMaxOutputTokens: Boolean(model.top_provider.max_completion_tokens),
679 acceptsCombinedToolsAndSchema: !strippedId.endsWith('-fast'),
680 })),
681 )
682
683 // Write the modified file
684 await writeFile(config.metaFile, content, 'utf-8')
685 console.log(` Wrote updated file: ${config.metaFile}`)
686 totalAdded += filteredModels.length
687 changedPackages.add(config.packageName)
688 }
689
690 console.log(`\nDone. Added ${totalAdded} new models total.`)
691
692 // Record this run's timestamp for future age-based filtering
693 await writeLastRunTimestamp()
694
695 // Detect all packages with uncommitted changes (includes changes from
696 // convert-openrouter-models.ts which runs before this script)
697 const allChangedPackages = detectChangedPackages()
698 for (const pkg of changedPackages) {
699 allChangedPackages.add(pkg)
700 }
701
702 if (allChangedPackages.size > 0) {
703 await createChangeset(allChangedPackages)
704 }
705}
706
707/**
708 * Create or update the sync-models changeset file.
709 * If one already exists, merges the package lists. Otherwise creates a new one.
710 */
711async function createChangeset(changedPackages: Set<string>) {
712 const changesetDir = resolve(ROOT, '.changeset')
713 const { readdir } = await import('node:fs/promises')
714 const files = await readdir(changesetDir)
715 const existing = files.find(
716 (f) => f.startsWith('sync-models') && f.endsWith('.md'),
717 )
718
719 if (existing) {
720 const existingPath = resolve(changesetDir, existing)
721 const existingContent = await readFile(existingPath, 'utf-8')
722
723 // Merge existing packages into the set
724 const pkgRegex = /'([^']+)':\s*patch/g
725 let match
726 while ((match = pkgRegex.exec(existingContent)) !== null) {
727 changedPackages.add(match[1]!)
728 }
729
730 const content = buildChangesetContent(changedPackages)
731 await writeFile(existingPath, content, 'utf-8')
732 console.log(`\nChangeset updated: ${existingPath}`)
733 } else {
734 const changesetFile = resolve(changesetDir, 'sync-models.md')
735 const content = buildChangesetContent(changedPackages)
736 await writeFile(changesetFile, content, 'utf-8')
737 console.log(`\nChangeset created: ${changesetFile}`)
738 }
739
740 console.log(` Packages: ${Array.from(changedPackages).sort().join(', ')}`)
741}
742
743function buildChangesetContent(packages: Set<string>): string {
744 const packageLines = Array.from(packages)
745 .sort()
746 .map((pkg) => `'${pkg}': patch`)
747 .join('\n')
748 return `---\n${packageLines}\n---\n\nUpdate model metadata from OpenRouter API\n`
749}
750
751main().catch((err) => {
752 console.error(err)
753 process.exit(1)
754})