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
10const listProviders = (client: OpenCodeClient, directory: string) =>
11 client.provider.list({ location: { directory } }).pipe(
12 Effect.timeout(PROVIDER_NAME_TIMEOUT),
13 Effect.map((list) => list.data),
14 );
15
16const readCatalog = <E>(
17 client: OpenCodeClient,
18 directory: string,
19 providers: Effect.Effect<ReadonlyArray<{ readonly id: string; readonly name: string }>, E>,
20): Effect.Effect<ReadonlyArray<OpenCode2Model>, OpenCodeRuntime.OpenCodeRuntimeError> =>
21 Effect.all(
22 {
23 // Callers bound the read: a busy host can hold it past OpenCode's own activation wait.
24 models: client.model.list({ location: { directory } }).pipe(Effect.map((list) => list.data)),
25 providers,
26 },
27 { concurrency: "unbounded" },
28 ).pipe(
29 Effect.map(({ models, providers }) => {
30 const providerNames = new Map(providers.map((provider) => [provider.id, provider.name]));
31 return models.map((model) => {
32 const providerName = providerNames.get(model.providerID);
33 return {
34 providerID: model.providerID,
35 id: model.id,
36 name: model.name,
37 ...(providerName ? { providerName } : {}),
38 variants: model.variants.map((variant) => ({ id: variant.id })),
39 family: model.family,
40 released: model.time.released,
41 deprecated: model.status === "deprecated",
42 };
43 });
44 }),
45 Effect.mapError(
46 (cause) =>
47 new OpenCodeRuntime.OpenCodeRuntimeError({
48 operation: "model.list",
49 detail: "The OpenCode server could not list its models.",
50 cause,
51 }),
52 ),
53 );
54
55/** Provider names are optional decoration; bound their read so models cannot stall. */
56export const loadOpenCode2Catalog = (client: OpenCodeClient, directory: string) =>
57 readCatalog(
58 client,
59 directory,
60 listProviders(client, directory).pipe(Effect.orElseSucceed(() => [])),
61 );
62
63/** Missing provider names would relabel every model, so a directory read needs them. */
64export const loadOpenCode2DirectoryCatalog = Effect.fn(
65 "OpenCodeRuntime.loadOpenCode2DirectoryCatalog",
66)((client: OpenCodeClient, directory: string) =>
67 readCatalog(client, directory, listProviders(client, directory)),
68);