models-dev.ts 8.8 KB

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