models-dev.ts 8.7 KB

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