@@ -2,9 +2,16 @@ import { Global } from "../global"
22import { Log } from "../util/log"
33import path from "path"
44import z from "zod"
5- import { data } from "./models-macro" with { type : "macro" }
65import { Installation } from "../installation"
76import { Flag } from "../flag/flag"
7+ import { lazy } from "@/util/lazy"
8+
9+ // Try to import bundled snapshot (generated at build time)
10+ // Falls back to undefined in dev mode when snapshot doesn't exist
11+ /* @ts -ignore */
12+ const SNAPSHOT = await import ( "./models-snapshot" )
13+ . then ( ( m ) => m . snapshot as Record < string , unknown > )
14+ . catch ( ( ) => undefined )
815
916export namespace ModelsDev {
1017 const log = Log . create ( { service : "models.dev" } )
@@ -76,18 +83,24 @@ export namespace ModelsDev {
7683
7784 export type Provider = z . infer < typeof Provider >
7885
79- export async function get ( ) {
80- refresh ( )
86+ function url ( ) {
87+ return Flag . OPENCODE_MODELS_URL || "https://models.dev"
88+ }
89+
90+ export const Data = lazy ( async ( ) => {
8191 const file = Bun . file ( filepath )
8292 const result = await file . json ( ) . catch ( ( ) => { } )
83- if ( result ) return result as Record < string , Provider >
84- if ( typeof data === "function" ) {
85- const json = await data ( )
86- return JSON . parse ( json ) as Record < string , Provider >
87- }
88- const url = Global . Path . modelsDevUrl
89- const json = await fetch ( `${ url } /api.json` ) . then ( ( x ) => x . text ( ) )
90- return JSON . parse ( json ) as Record < string , Provider >
93+ if ( result ) return result
94+ if ( SNAPSHOT ) return SNAPSHOT
95+ if ( Flag . OPENCODE_DISABLE_MODELS_FETCH ) return { }
96+ const json = await fetch ( `${ url ( ) } /api.json` ) . then ( ( x ) => x . text ( ) )
97+ return JSON . parse ( json )
98+ } )
99+
100+ export async function get ( ) {
101+ refresh ( )
102+ const result = await Data ( )
103+ return result as Record < string , Provider >
91104 }
92105
93106 export async function refresh ( ) {
@@ -96,8 +109,7 @@ export namespace ModelsDev {
96109 log . info ( "refreshing" , {
97110 file,
98111 } )
99- const url = Global . Path . modelsDevUrl
100- const result = await fetch ( `${ url } /api.json` , {
112+ const result = await fetch ( `${ url ( ) } /api.json` , {
101113 headers : {
102114 "User-Agent" : Installation . USER_AGENT ,
103115 } ,
@@ -107,8 +119,18 @@ export namespace ModelsDev {
107119 error : e ,
108120 } )
109121 } )
110- if ( result && result . ok ) await Bun . write ( file , await result . text ( ) )
122+ if ( result && result . ok ) {
123+ await Bun . write ( file , await result . text ( ) )
124+ ModelsDev . Data . reset ( )
125+ }
111126 }
112127}
113128
114- setInterval ( ( ) => ModelsDev . refresh ( ) , 60 * 1000 * 60 ) . unref ( )
129+ if ( ! Flag . OPENCODE_DISABLE_MODELS_FETCH ) {
130+ setInterval (
131+ async ( ) => {
132+ await ModelsDev . refresh ( )
133+ } ,
134+ 60 * 1000 * 60 ,
135+ ) . unref ( )
136+ }
0 commit comments