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 type { OpenCode2Model } from "./status.ts";
6
7// Cold catalogs take seconds; model reads already retry empty catalogs.
8const PROVIDER_NAME_TIMEOUT = "3 seconds";
9// Bounds the request alone (server start has its own bounds); a slow list reads as not listed yet.
10const MODEL_LIST_TIMEOUT = "5 seconds";
11
12const listProviders = (client: OpenCodeClient, directory: string) =>
13 client.provider.list({ location: { directory } }).pipe(
14 Effect.timeout(PROVIDER_NAME_TIMEOUT),
15 Effect.map((list) => list.data),
16 );
17
18const readCatalog = <E>(
19 client: OpenCodeClient,
20 directory: string,
21 providers: Effect.Effect<ReadonlyArray<{ readonly id: string; readonly name: string }>, E>,
22): Effect.Effect<ReadonlyArray<OpenCode2Model>, OpenCodeRuntime.OpenCodeRuntimeError> =>
23 Effect.all(
24 {
25 models: client.model.list({ location: { directory } }).pipe(
26 Effect.timeoutOption(MODEL_LIST_TIMEOUT),
27 Effect.map((list) => (list._tag === "Some" ? list.value.data : [])),
28 ),
29 providers,
30 },
31 { concurrency: "unbounded" },
32 ).pipe(
33 Effect.map(({ models, providers }) => {
34 const providerNames = new Map(providers.map((provider) => [provider.id, provider.name]));
35 return models.map((model) => {
36 const providerName = providerNames.get(model.providerID);
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 };
47 });
48 }),
49 Effect.mapError(
50 (cause) =>
51 new OpenCodeRuntime.OpenCodeRuntimeError({
52 operation: "model.list",
53 detail: "The OpenCode server could not list its models.",
54 cause,
55 }),
56 ),
57 );
58
59/** Provider names are optional decoration; bound their read so models cannot stall. */
60export const loadOpenCode2Catalog = (client: OpenCodeClient, directory: string) =>
61 readCatalog(
62 client,
63 directory,
64 listProviders(client, directory).pipe(Effect.orElseSucceed(() => [])),
65 );
66
67/** Missing provider names would relabel every model, so a directory read needs them. */
68export const loadOpenCode2DirectoryCatalog = Effect.fn(
69 "OpenCodeRuntime.loadOpenCode2DirectoryCatalog",
70)((client: OpenCodeClient, directory: string) =>
71 readCatalog(client, directory, listProviders(client, directory)),
72);