models-dev.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import path from "path"
  2. import { Context, Duration, Effect, Layer, Option, Schedule, Schema } from "effect"
  3. import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http"
  4. import { Global } from "./global"
  5. import { Flag } from "./flag/flag"
  6. import { Flock } from "./util/flock"
  7. import { Hash } from "./util/hash"
  8. import { FSUtil } from "./fs-util"
  9. import { InstallationChannel, InstallationVersion } from "./installation/version"
  10. import { EventV2 } from "./event"
  11. export const CatalogModelStatus = Schema.Literals(["alpha", "beta", "deprecated"])
  12. export type CatalogModelStatus = typeof CatalogModelStatus.Type
  13. const USER_AGENT = `opencode/${InstallationChannel}/${InstallationVersion}/${Flag.OPENCODE_CLIENT}`
  14. const CostTier = Schema.Struct({
  15. input: Schema.Finite,
  16. output: Schema.Finite,
  17. cache_read: Schema.optional(Schema.Finite),
  18. cache_write: Schema.optional(Schema.Finite),
  19. tier: Schema.Struct({
  20. type: Schema.Literal("context"),
  21. size: Schema.Finite,
  22. }),
  23. })
  24. const Cost = Schema.Struct({
  25. input: Schema.Finite,
  26. output: Schema.Finite,
  27. cache_read: Schema.optional(Schema.Finite),
  28. cache_write: Schema.optional(Schema.Finite),
  29. tiers: Schema.optional(Schema.Array(CostTier)),
  30. context_over_200k: Schema.optional(
  31. Schema.Struct({
  32. input: Schema.Finite,
  33. output: Schema.Finite,
  34. cache_read: Schema.optional(Schema.Finite),
  35. cache_write: Schema.optional(Schema.Finite),
  36. }),
  37. ),
  38. })
  39. export const Model = Schema.Struct({
  40. id: Schema.String,
  41. name: Schema.String,
  42. family: Schema.optional(Schema.String),
  43. release_date: Schema.String,
  44. attachment: Schema.Boolean,
  45. reasoning: Schema.Boolean,
  46. temperature: Schema.Boolean,
  47. tool_call: Schema.Boolean,
  48. interleaved: Schema.optional(
  49. Schema.Union([
  50. Schema.Literal(true),
  51. Schema.Struct({
  52. field: Schema.Literals(["reasoning_content", "reasoning_details"]),
  53. }),
  54. ]),
  55. ),
  56. cost: Schema.optional(Cost),
  57. limit: Schema.Struct({
  58. context: Schema.Finite,
  59. input: Schema.optional(Schema.Finite),
  60. output: Schema.Finite,
  61. }),
  62. modalities: Schema.optional(
  63. Schema.Struct({
  64. input: Schema.Array(Schema.Literals(["text", "audio", "image", "video", "pdf"])),
  65. output: Schema.Array(Schema.Literals(["text", "audio", "image", "video", "pdf"])),
  66. }),
  67. ),
  68. experimental: Schema.optional(
  69. Schema.Struct({
  70. modes: Schema.optional(
  71. Schema.Record(
  72. Schema.String,
  73. Schema.Struct({
  74. cost: Schema.optional(Cost),
  75. provider: Schema.optional(
  76. Schema.Struct({
  77. body: Schema.optional(Schema.Record(Schema.String, Schema.MutableJson)),
  78. headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
  79. }),
  80. ),
  81. }),
  82. ),
  83. ),
  84. }),
  85. ),
  86. status: Schema.optional(CatalogModelStatus),
  87. provider: Schema.optional(
  88. Schema.Struct({ npm: Schema.optional(Schema.String), api: Schema.optional(Schema.String) }),
  89. ),
  90. })
  91. export type Model = Schema.Schema.Type<typeof Model>
  92. export const Provider = Schema.Struct({
  93. api: Schema.optional(Schema.String),
  94. name: Schema.String,
  95. env: Schema.Array(Schema.String),
  96. id: Schema.String,
  97. npm: Schema.optional(Schema.String),
  98. models: Schema.Record(Schema.String, Model),
  99. })
  100. export type Provider = Schema.Schema.Type<typeof Provider>
  101. export const Event = {
  102. Refreshed: EventV2.define({
  103. type: "models-dev.refreshed",
  104. schema: {},
  105. }),
  106. }
  107. declare const OPENCODE_MODELS_DEV: Record<string, Provider> | undefined
  108. export interface Interface {
  109. readonly get: () => Effect.Effect<Record<string, Provider>>
  110. readonly refresh: (force?: boolean) => Effect.Effect<void>
  111. }
  112. export class Service extends Context.Service<Service, Interface>()("@opencode/ModelsDev") {}
  113. export const layer = Layer.effect(
  114. Service,
  115. Effect.gen(function* () {
  116. const fs = yield* FSUtil.Service
  117. const events = yield* EventV2.Service
  118. const http = HttpClient.filterStatusOk(
  119. (yield* HttpClient.HttpClient).pipe(
  120. HttpClient.retryTransient({
  121. retryOn: "errors-and-responses",
  122. times: 2,
  123. schedule: Schedule.exponential(200).pipe(Schedule.jittered),
  124. }),
  125. ),
  126. )
  127. const source = Flag.OPENCODE_MODELS_URL || "https://models.dev"
  128. const filepath = path.join(
  129. Global.Path.cache,
  130. source === "https://models.dev" ? "models.json" : `models-${Hash.fast(source)}.json`,
  131. )
  132. const ttl = Duration.minutes(5)
  133. const lockKey = `models-dev:${filepath}`
  134. const fresh = Effect.fnUntraced(function* () {
  135. const stat = yield* fs.stat(filepath).pipe(Effect.catch(() => Effect.succeed(undefined)))
  136. if (!stat) return false
  137. const mtime = Option.getOrElse(stat.mtime, () => new Date(0)).getTime()
  138. return Date.now() - mtime < Duration.toMillis(ttl)
  139. })
  140. const fetchApi = Effect.fn("ModelsDev.fetchApi")(function* () {
  141. return yield* HttpClientRequest.get(`${source}/api.json`).pipe(
  142. HttpClientRequest.setHeader("User-Agent", USER_AGENT),
  143. http.execute,
  144. Effect.flatMap((res) => res.text),
  145. Effect.timeout("10 seconds"),
  146. )
  147. })
  148. const loadFromDisk = fs.readJson(Flag.OPENCODE_MODELS_PATH ?? filepath).pipe(
  149. Effect.catch((error) => {
  150. if (
  151. Flag.OPENCODE_MODELS_PATH === undefined &&
  152. error._tag === "FileSystemError" &&
  153. error.method === "readJson"
  154. ) {
  155. return fs.remove(filepath, { force: true }).pipe(Effect.ignore, Effect.as(undefined))
  156. }
  157. return Effect.succeed(undefined)
  158. }),
  159. Effect.map((v) => v as Record<string, Provider> | undefined),
  160. )
  161. const loadSnapshot = Effect.sync(() =>
  162. typeof OPENCODE_MODELS_DEV === "undefined" ? undefined : OPENCODE_MODELS_DEV,
  163. )
  164. const fetchAndWrite = Effect.fn("ModelsDev.fetchAndWrite")(function* () {
  165. const text = yield* fetchApi()
  166. const tempfile = `${filepath}.${process.pid}.${Date.now()}.tmp`
  167. yield* fs.writeWithDirs(tempfile, text).pipe(
  168. Effect.andThen(fs.rename(tempfile, filepath)),
  169. Effect.catch((error) =>
  170. Effect.gen(function* () {
  171. yield* fs.remove(tempfile, { force: true }).pipe(Effect.ignore)
  172. return yield* Effect.fail(error)
  173. }),
  174. ),
  175. )
  176. return text
  177. })
  178. const populate = Effect.gen(function* () {
  179. const fromDisk = yield* loadFromDisk
  180. if (fromDisk) return fromDisk
  181. const snapshot = yield* loadSnapshot
  182. if (snapshot) return snapshot
  183. if (Flag.OPENCODE_DISABLE_MODELS_FETCH) return {}
  184. // Flock is cross-process: concurrent opencode CLIs can race on this cache file.
  185. const text = yield* Effect.scoped(
  186. Effect.gen(function* () {
  187. yield* Flock.effect(lockKey)
  188. return yield* fetchAndWrite()
  189. }),
  190. )
  191. return JSON.parse(text) as Record<string, Provider>
  192. }).pipe(Effect.withSpan("ModelsDev.populate"), Effect.orDie)
  193. const [cachedGet, invalidate] = yield* Effect.cachedInvalidateWithTTL(populate, Duration.infinity)
  194. const get = (): Effect.Effect<Record<string, Provider>> => cachedGet
  195. const refresh = Effect.fn("ModelsDev.refresh")(function* (force = false) {
  196. if (!force && (yield* fresh())) return
  197. yield* Effect.scoped(
  198. Effect.gen(function* () {
  199. yield* Flock.effect(lockKey)
  200. // Re-check under the lock: another process may have refreshed between
  201. // our outer check and lock acquisition.
  202. if (!force && (yield* fresh())) return
  203. yield* fetchAndWrite()
  204. yield* invalidate
  205. yield* events.publish(Event.Refreshed, {})
  206. }),
  207. ).pipe(
  208. Effect.tapCause((cause) =>
  209. Effect.logError("Failed to fetch models.dev").pipe(Effect.annotateLogs("cause", cause)),
  210. ),
  211. Effect.ignore,
  212. )
  213. })
  214. if (!Flag.OPENCODE_DISABLE_MODELS_FETCH && !process.argv.includes("--get-yargs-completions")) {
  215. // Schedule.spaced runs the effect once, then waits between completions.
  216. yield* Effect.forkScoped(refresh().pipe(Effect.repeat(Schedule.spaced("60 minutes")), Effect.ignore))
  217. }
  218. return Service.of({ get, refresh })
  219. }),
  220. )
  221. export const defaultLayer = layer.pipe(
  222. Layer.provide(FetchHttpClient.layer),
  223. Layer.provide(FSUtil.defaultLayer),
  224. Layer.provide(EventV2.defaultLayer),
  225. )
  226. export * as ModelsDev from "./models-dev"