models-dev.ts 7.4 KB

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