The best way to control Claude Code, Codex and more from any computer or phone

main
ts 71 lines 2.64 KB
Raw
1 import type { OpenCodeClient } from "@opencode/client/effect";
2 import * as Effect from "effect/Effect";
3
4 import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
5 import type { OpenCode2Model } from "./status.ts";
6
7 // Cold catalogs take seconds; model reads already retry empty catalogs.
8 const PROVIDER_NAME_TIMEOUT = "3 seconds";
9
10 const locationOf = (directory: string | undefined) =>
11 directory === undefined ? {} : { location: { directory } };
12
13 const 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
19 const 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 return {
37 providerID: model.providerID,
38 id: model.id,
39 name: model.name,
40 ...(providerName ? { providerName } : {}),
41 variants: model.variants.map((variant) => ({ id: variant.id })),
42 family: model.family,
43 released: model.time.released,
44 deprecated: model.status === "deprecated",
45 };
46 });
47 }),
48 Effect.mapError(
49 (cause) =>
50 new OpenCodeRuntime.OpenCodeRuntimeError({
51 operation: "model.list",
52 detail: "The OpenCode server could not list its models.",
53 cause,
54 }),
55 ),
56 );
57
58 /** Provider names are optional decoration; bound their read so models cannot stall. */
59 export const loadOpenCode2Catalog = (client: OpenCodeClient, directory: string | undefined) =>
60 readCatalog(
61 client,
62 directory,
63 listProviders(client, directory).pipe(Effect.orElseSucceed(() => [])),
64 );
65
66 /** Missing provider names would relabel every model, so a directory read needs them. */
67 export const loadOpenCode2DirectoryCatalog = Effect.fn(
68 "OpenCodeRuntime.loadOpenCode2DirectoryCatalog",
69 )((client: OpenCodeClient, directory: string) =>
70 readCatalog(client, directory, listProviders(client, directory)),
71 );