Open History to see the last commit
1import type { OpenCodeClient } from "@opencode/client/effect";
2import * as Effect from "effect/Effect";
3
4import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
5import { openCodePrice, type OpenCode2Model } from "./status.ts";
6
7// Cold catalogs take seconds; model reads already retry empty catalogs.
8const PROVIDER_NAME_TIMEOUT = "3 seconds";
9
10const locationOf = (directory: string | undefined) =>
11 directory === undefined ? {} : { location: { directory } };
12
13const listProviders = (client: OpenCodeClient, directory: string | undefined) =>
14 client.provider.list(locationOf(directory)).pipe(
15 Effect.timeout(PROVIDER_NAME_TIMEOUT),
16 Effect.map((list) => list.data),
17 );
18
19const readCatalog = <E>(
20 client: OpenCodeClient,
21 directory: string | undefined,
22 providers: Effect.Effect<ReadonlyArray<{ readonly id: string; readonly name: string }>, E>,
23): Effect.Effect<ReadonlyArray<OpenCode2Model>, OpenCodeRuntime.OpenCodeRuntimeError> =>
24 Effect.all(
25 {
26 // Callers bound the read: a busy host can hold it past OpenCode's own activation wait.
27 models: client.model.list(locationOf(directory)).pipe(Effect.map((list) => list.data)),
28 providers,
29 },
30 { concurrency: "unbounded" },
31 ).pipe(
32 Effect.map(({ models, providers }) => {
33 const providerNames = new Map(providers.map((provider) => [provider.id, provider.name]));
34 return models.map((model) => {
35 const providerName = providerNames.get(model.providerID);
36 const baseCost = model.cost.find((cost) => cost.tier === undefined);
37 return {
38 providerID: model.providerID,
39 id: model.id,
40 name: model.name,
41 ...(providerName ? { providerName } : {}),
42 variants: model.variants.map((variant) => ({ id: variant.id })),
43 family: model.family,
44 released: model.time.released,
45 deprecated: model.status === "deprecated",
46 ...(baseCost ? { price: openCodePrice(baseCost) } : {}),
47 };
48 });
49 }),
50 Effect.mapError(
51 (cause) =>
52 new OpenCodeRuntime.OpenCodeRuntimeError({
53 operation: "model.list",
54 detail: "The OpenCode server could not list its models.",
55 cause,
56 }),
57 ),
58 );
59
60/** Provider names are optional decoration; bound their read so models cannot stall. */
61export const loadOpenCode2Catalog = (client: OpenCodeClient, directory: string | undefined) =>
62 readCatalog(
63 client,
64 directory,
65 listProviders(client, directory).pipe(Effect.orElseSucceed(() => [])),
66 );
67
68/** Missing provider names would relabel every model, so a read nothing settles needs them. */
69export const loadOpenCode2DirectoryCatalog = Effect.fn(
70 "OpenCodeRuntime.loadOpenCode2DirectoryCatalog",
71)((client: OpenCodeClient, directory: string | undefined) =>
72 readCatalog(client, directory, listProviders(client, directory)),
73);