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