catalog.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. export * as Catalog from "./catalog"
  2. import { Context, Effect, Layer, Option, Order, pipe, Schema, Array, Scope, Stream } from "effect"
  3. import { castDraft, enableMapSet, type Draft } from "immer"
  4. import { ModelV2 } from "./model"
  5. import { PluginV2 } from "./plugin"
  6. import { ProviderV2 } from "./provider"
  7. import { Location } from "./location"
  8. import { EventV2 } from "./event"
  9. import { Policy } from "./policy"
  10. import { State } from "./state"
  11. export type ProviderRecord = {
  12. provider: ProviderV2.Info
  13. models: Map<ModelV2.ID, ModelV2.Info>
  14. }
  15. export type DefaultModel = { providerID: ProviderV2.ID; modelID: ModelV2.ID }
  16. export class ProviderNotFoundError extends Schema.TaggedErrorClass<ProviderNotFoundError>()(
  17. "CatalogV2.ProviderNotFound",
  18. {
  19. providerID: ProviderV2.ID,
  20. },
  21. ) {}
  22. export class ModelNotFoundError extends Schema.TaggedErrorClass<ModelNotFoundError>()("CatalogV2.ModelNotFound", {
  23. providerID: ProviderV2.ID,
  24. modelID: ModelV2.ID,
  25. }) {}
  26. export const PolicyActions = Schema.Literals(["provider.use"])
  27. export const Event = {
  28. ModelUpdated: EventV2.define({
  29. type: "catalog.model.updated",
  30. schema: {
  31. model: ModelV2.Info,
  32. },
  33. }),
  34. }
  35. type Data = {
  36. providers: Map<ProviderV2.ID, ProviderRecord>
  37. defaultModel?: DefaultModel
  38. }
  39. export type Editor = {
  40. provider: {
  41. list: () => readonly ProviderRecord[]
  42. get: (providerID: ProviderV2.ID) => ProviderRecord | undefined
  43. update: (providerID: ProviderV2.ID, fn: (provider: Draft<ProviderV2.Info>) => void) => void
  44. remove: (providerID: ProviderV2.ID) => void
  45. }
  46. model: {
  47. get: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => ModelV2.Info | undefined
  48. update: (providerID: ProviderV2.ID, modelID: ModelV2.ID, fn: (model: Draft<ModelV2.Info>) => void) => void
  49. remove: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => void
  50. default: {
  51. get: () => DefaultModel | undefined
  52. set: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => void
  53. }
  54. }
  55. }
  56. export interface Interface {
  57. readonly transform: State.Interface<Data, Editor>["transform"]
  58. readonly provider: {
  59. readonly get: (providerID: ProviderV2.ID) => Effect.Effect<ProviderV2.Info, ProviderNotFoundError>
  60. readonly all: () => Effect.Effect<ProviderV2.Info[]>
  61. readonly available: () => Effect.Effect<ProviderV2.Info[]>
  62. }
  63. readonly model: {
  64. readonly get: (
  65. providerID: ProviderV2.ID,
  66. modelID: ModelV2.ID,
  67. ) => Effect.Effect<ModelV2.Info, ProviderNotFoundError | ModelNotFoundError>
  68. readonly all: () => Effect.Effect<ModelV2.Info[]>
  69. readonly available: () => Effect.Effect<ModelV2.Info[]>
  70. readonly default: () => Effect.Effect<Option.Option<ModelV2.Info>>
  71. readonly small: (providerID: ProviderV2.ID) => Effect.Effect<Option.Option<ModelV2.Info>>
  72. }
  73. }
  74. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Catalog") {}
  75. enableMapSet()
  76. export const layer = Layer.effect(
  77. Service,
  78. Effect.gen(function* () {
  79. const location = yield* Location.Service
  80. const plugin = yield* PluginV2.Service
  81. const events = yield* EventV2.Service
  82. const policy = yield* Policy.Service
  83. const scope = yield* Scope.Scope
  84. const resolve = (model: ModelV2.Info) => {
  85. const provider = state.get().providers.get(model.providerID)!.provider
  86. const endpoint =
  87. model.endpoint.type === "unknown"
  88. ? provider.endpoint
  89. : model.endpoint.type === "aisdk" && provider.endpoint.type === "aisdk" && !model.endpoint.url
  90. ? { ...model.endpoint, url: provider.endpoint.url }
  91. : model.endpoint
  92. const options = {
  93. headers: {
  94. ...provider.options.headers,
  95. ...model.options.headers,
  96. },
  97. body: {
  98. ...provider.options.body,
  99. ...model.options.body,
  100. },
  101. aisdk: {
  102. provider: {
  103. ...provider.options.aisdk.provider,
  104. ...model.options.aisdk.provider,
  105. },
  106. request: model.options.aisdk.request,
  107. },
  108. variant: model.options.variant,
  109. }
  110. return new ModelV2.Info({
  111. ...model,
  112. endpoint,
  113. options,
  114. })
  115. }
  116. function* getRecord(providerID: ProviderV2.ID) {
  117. const match = state.get().providers.get(providerID)
  118. if (!match) return yield* new ProviderNotFoundError({ providerID })
  119. return match
  120. }
  121. const normalizeEndpoint = (item: Draft<ProviderV2.Info> | Draft<ModelV2.Info>) => {
  122. if (item.endpoint.type !== "aisdk" || typeof item.options.aisdk.provider.baseURL !== "string") return
  123. item.endpoint.url = item.options.aisdk.provider.baseURL
  124. delete item.options.aisdk.provider.baseURL
  125. }
  126. const state = State.create<Data, Editor>({
  127. initial: () => ({ providers: new Map() }),
  128. editor: (draft) => {
  129. const result: Editor = {
  130. provider: {
  131. list: () => Array.fromIterable(draft.providers.values()) as ProviderRecord[],
  132. get: (providerID) => draft.providers.get(providerID),
  133. update: (providerID, fn) => {
  134. let current = draft.providers.get(providerID)
  135. if (!current) {
  136. current = castDraft({
  137. provider: ProviderV2.Info.empty(providerID),
  138. models: new Map<ModelV2.ID, ModelV2.Info>(),
  139. })
  140. draft.providers.set(providerID, current)
  141. }
  142. fn(current.provider)
  143. normalizeEndpoint(current.provider)
  144. },
  145. remove: (providerID) => {
  146. draft.providers.delete(providerID)
  147. },
  148. },
  149. model: {
  150. get: (providerID, modelID) => draft.providers.get(providerID)?.models.get(modelID),
  151. update: (providerID, modelID, fn) => {
  152. let record = draft.providers.get(providerID)
  153. if (!record) {
  154. record = castDraft({
  155. provider: ProviderV2.Info.empty(providerID),
  156. models: new Map<ModelV2.ID, ModelV2.Info>(),
  157. })
  158. draft.providers.set(providerID, record)
  159. }
  160. const model = record.models.get(modelID) ?? castDraft(ModelV2.Info.empty(providerID, modelID))
  161. if (!record.models.has(modelID)) record.models.set(modelID, model)
  162. fn(model)
  163. model.id = modelID
  164. model.providerID = providerID
  165. normalizeEndpoint(model)
  166. },
  167. remove: (providerID, modelID) => {
  168. draft.providers.get(providerID)?.models.delete(modelID)
  169. },
  170. default: {
  171. get: () => draft.defaultModel,
  172. set: (providerID, modelID) => {
  173. draft.defaultModel = { providerID, modelID }
  174. },
  175. },
  176. },
  177. }
  178. return result
  179. },
  180. finalize: Effect.fn("CatalogV2.finalize")(function* (catalog, reason) {
  181. if (reason !== "plugin.added") yield* plugin.trigger("catalog.transform", catalog, {}).pipe(Effect.asVoid)
  182. if (!policy.hasStatements()) return
  183. for (const record of [...catalog.provider.list()]) {
  184. if ((yield* policy.evaluate("provider.use", record.provider.id, "allow")) === "deny") {
  185. catalog.provider.remove(record.provider.id)
  186. }
  187. }
  188. }),
  189. })
  190. yield* events.subscribe(PluginV2.Event.Added).pipe(
  191. // Plugin registries are location scoped even though the event bus is process scoped.
  192. Stream.filter(
  193. (event) =>
  194. event.location?.directory === location.directory && event.location.workspaceID === location.workspaceID,
  195. ),
  196. Stream.runForEach((event) =>
  197. state.update((catalog) => plugin.triggerFor(event.data.id, "catalog.transform", catalog, {}), "plugin.added"),
  198. ),
  199. Effect.forkIn(scope, { startImmediately: true }),
  200. )
  201. const result: Interface = {
  202. transform: state.transform,
  203. provider: {
  204. get: Effect.fn("CatalogV2.provider.get")(function* (providerID) {
  205. const record = yield* getRecord(providerID)
  206. return record.provider
  207. }),
  208. all: Effect.fn("CatalogV2.provider.all")(function* () {
  209. return Array.fromIterable(state.get().providers.values()).map((record) => record.provider)
  210. }),
  211. available: Effect.fn("CatalogV2.provider.available")(function* () {
  212. return Array.fromIterable(state.get().providers.values())
  213. .map((record) => record.provider)
  214. .filter((provider) => provider.enabled)
  215. }),
  216. },
  217. model: {
  218. get: Effect.fn("CatalogV2.model.get")(function* (providerID, modelID) {
  219. const record = yield* getRecord(providerID)
  220. const model = record.models.get(modelID)
  221. if (!model) return yield* new ModelNotFoundError({ providerID, modelID })
  222. return resolve(model)
  223. }),
  224. all: Effect.fn("CatalogV2.model.all")(function* () {
  225. return pipe(
  226. Array.fromIterable(state.get().providers.values()),
  227. Array.flatMap((record) => Array.fromIterable(record.models.values())),
  228. Array.map(resolve),
  229. Array.sortWith((item) => item.time.released.epochMilliseconds, Order.flip(Order.Number)),
  230. )
  231. }),
  232. available: Effect.fn("CatalogV2.model.available")(function* () {
  233. return (yield* result.model.all()).filter((model) => {
  234. const record = state.get().providers.get(model.providerID)
  235. return record?.provider.enabled !== false && model.enabled
  236. })
  237. }),
  238. default: Effect.fn("CatalogV2.model.default")(function* () {
  239. const defaultModel = state.get().defaultModel
  240. if (defaultModel) {
  241. const model = yield* result.model.get(defaultModel.providerID, defaultModel.modelID).pipe(Effect.option)
  242. if (Option.isSome(model) && model.value.enabled) return model
  243. }
  244. return pipe(
  245. yield* result.model.available(),
  246. Array.sortWith((item) => item.time.released.epochMilliseconds, Order.flip(Order.Number)),
  247. Array.head,
  248. )
  249. }),
  250. small: Effect.fn("CatalogV2.model.small")(function* (providerID) {
  251. const record = state.get().providers.get(providerID)
  252. if (!record) return Option.none<ModelV2.Info>()
  253. if (providerID === ProviderV2.ID.opencode) {
  254. const gpt5Nano = record.models.get(ModelV2.ID.make("gpt-5-nano"))
  255. if (gpt5Nano?.enabled && gpt5Nano.status === "active") return Option.some(resolve(gpt5Nano))
  256. }
  257. const candidates = pipe(
  258. Array.fromIterable(record.models.values()),
  259. Array.filter(
  260. (model) =>
  261. model.providerID === providerID &&
  262. model.enabled &&
  263. model.status === "active" &&
  264. model.capabilities.input.some((item) => item.startsWith("text")) &&
  265. model.capabilities.output.some((item) => item.startsWith("text")),
  266. ),
  267. Array.map((model) => ({
  268. model,
  269. cost: model.cost[0] ? model.cost[0].input + model.cost[0].output : 999,
  270. age: (Date.now() - model.time.released.epochMilliseconds) / (1000 * 60 * 60 * 24 * 30),
  271. small: SMALL_MODEL_RE.test(`${model.id} ${model.family ?? ""} ${model.name}`.toLowerCase()),
  272. })),
  273. Array.filter((item) => item.cost > 0 && item.age <= 18),
  274. )
  275. const pick = (items: typeof candidates) => {
  276. const maxCost = Math.max(...items.map((item) => item.cost), 0.01)
  277. const maxAge = Math.max(...items.map((item) => item.age), 0.01)
  278. return pipe(
  279. items,
  280. Array.sortWith((item) => (item.cost / maxCost) * 0.8 + (item.age / maxAge) * 0.2, Order.Number),
  281. Array.map((item) => resolve(item.model)),
  282. Array.head,
  283. )
  284. }
  285. return pipe(
  286. candidates,
  287. Array.filter((item) => item.small),
  288. (items) => (items.length > 0 ? pick(items) : pick(candidates)),
  289. )
  290. }),
  291. },
  292. }
  293. return Service.of(result)
  294. }),
  295. )
  296. const SMALL_MODEL_RE = /\b(nano|flash|lite|mini|haiku|small|fast)\b/
  297. export const locationLayer = layer.pipe(
  298. Layer.provideMerge(PluginV2.locationLayer),
  299. Layer.provideMerge(Policy.locationLayer),
  300. )