models-dev.ts 8.3 KB

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