Open History to see the last commit
1import { parseSemver } from "@t3tools/shared/semver";
2import * as Cache from "effect/Cache";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as HttpClient from "effect/http/HttpClient";
9import * as HttpClientRequest from "effect/http/HttpClientRequest";
10
11import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
12import { parseGenericCliVersion } from "@t3tools/provider-core/server/snapshotProbe";
13
14export interface ProbedOpenCode {
15 readonly generation: "v1" | "v2";
16 readonly version: string;
17}
18
19// Meant to stop a hung `--version`; wrapped installs can take several seconds to start cold.
20const OPENCODE_VERSION_PROBE_TIMEOUT = "10 seconds";
21const OPENCODE_SERVER_PROBE_TIMEOUT = "5 seconds";
22// 2.x's own CLI decodes `{version, pid}` from `/api/info`; requiring both keeps unrelated JSON out.
23const decodeApiInfo = Schema.decodeUnknownOption(
24 Schema.fromJsonString(Schema.Struct({ version: Schema.String, pid: Schema.Int })),
25);
26const decodeGlobalHealth = Schema.decodeUnknownOption(
27 Schema.fromJsonString(Schema.Struct({ healthy: Schema.Literal(true), version: Schema.String })),
28);
29
30function probed(version: string | null | undefined): ProbedOpenCode | undefined {
31 const major = parseSemver(version ?? "")?.major;
32 if (!version || major === undefined) return undefined;
33 return { generation: major >= 2 ? "v2" : "v1", version };
34}
35
36export const classifyOpenCodeCliVersion = (output: string) =>
37 probed(parseGenericCliVersion(output));
38
39/**
40 * Each serves its web UI's HTML with a 200 on the other's path, so only a JSON body counts. Both
41 * versions answer a wrong password with a 401 on either path, so a 401 says nothing about the
42 * version.
43 */
44function classifyOpenCodeProbeResponse(
45 path: "/api/info" | "/global/health",
46 response: {
47 readonly status: number;
48 readonly contentType: string | undefined;
49 readonly body: string;
50 },
51): ProbedOpenCode | "unauthorized" | undefined {
52 if (response.status === 401) return "unauthorized";
53 const mediaType = response.contentType?.split(";")[0]?.trim().toLowerCase();
54 if (response.status !== 200 || mediaType !== "application/json") return undefined;
55 const version: Option.Option<string> =
56 path === "/api/info"
57 ? Option.map(decodeApiInfo(response.body), (info) => info.version)
58 : Option.map(decodeGlobalHealth(response.body), (health) => health.version);
59 return probed(Option.getOrUndefined(version));
60}
61
62const probeOpenCodeBinary = Effect.fn("probeOpenCodeBinary")(function* (
63 binaryPath: string,
64 environment: NodeJS.ProcessEnv | undefined,
65) {
66 const runtime = yield* OpenCodeRuntime.OpenCodeRuntime;
67 const { stdout } = yield* runtime
68 .runOpenCodeCommand({
69 binaryPath,
70 args: ["--version"],
71 ...(environment === undefined ? {} : { environment }),
72 })
73 .pipe(
74 Effect.timeoutOrElse({
75 duration: OPENCODE_VERSION_PROBE_TIMEOUT,
76 orElse: () =>
77 Effect.fail(
78 new OpenCodeRuntime.OpenCodeRuntimeError({
79 operation: "probeOpenCodeBinary",
80 detail: `OpenCode CLI version probe timed out after ${OPENCODE_VERSION_PROBE_TIMEOUT}.`,
81 }),
82 ),
83 }),
84 );
85 const result = classifyOpenCodeCliVersion(stdout);
86 if (result) return result;
87 return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
88 operation: "probeOpenCodeBinary",
89 detail: `Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${OpenCodeRuntime.MINIMUM_OPENCODE_VERSION} or newer.`,
90 });
91});
92
93// Server failures reach clients through the provider status, so their details are fixed text:
94// the underlying error can carry the configured URL, its credentials, or the password header.
95const probeOpenCodeServer = Effect.fn("probeOpenCodeServer")(function* (
96 serverUrl: string,
97 serverPassword: string,
98) {
99 const client = yield* HttpClient.HttpClient;
100 const baseUrl = URL.parse(serverUrl.trim());
101 if (baseUrl?.protocol !== "http:" && baseUrl?.protocol !== "https:") {
102 return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
103 operation: "probeOpenCodeServer",
104 detail: "The OpenCode server URL is not a valid http:// or https:// URL.",
105 });
106 }
107 // UTF-8, as the 1.x SDK client sends it; `HttpClientRequest.basicAuth` uses Latin-1 `btoa`.
108 const authorization = serverPassword
109 ? `Basic ${Buffer.from(`opencode:${serverPassword}`, "utf8").toString("base64")}`
110 : undefined;
111 for (const path of ["/api/info", "/global/health"] as const) {
112 const url = new URL(baseUrl);
113 url.pathname = `${url.pathname.replace(/\/+$/, "")}${path}`;
114 const request = HttpClientRequest.get(url.href);
115 const result = yield* client
116 .execute(
117 authorization
118 ? HttpClientRequest.setHeader(request, "authorization", authorization)
119 : request,
120 )
121 .pipe(
122 Effect.flatMap((response) =>
123 Effect.map(response.text, (body) =>
124 classifyOpenCodeProbeResponse(path, {
125 status: response.status,
126 contentType: response.headers["content-type"],
127 body,
128 }),
129 ),
130 ),
131 Effect.mapError(
132 (cause) =>
133 new OpenCodeRuntime.OpenCodeRuntimeError({
134 operation: "probeOpenCodeServer",
135 detail: "Couldn't reach the OpenCode server.",
136 cause,
137 }),
138 ),
139 Effect.timeoutOrElse({
140 duration: OPENCODE_SERVER_PROBE_TIMEOUT,
141 orElse: () =>
142 Effect.fail(
143 new OpenCodeRuntime.OpenCodeRuntimeError({
144 operation: "probeOpenCodeServer",
145 detail: "Timed out while checking the OpenCode server version.",
146 }),
147 ),
148 }),
149 );
150 if (result === "unauthorized") {
151 return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
152 operation: "probeOpenCodeServer",
153 detail: "401 Unauthorized: the OpenCode server rejected the password.",
154 });
155 }
156 if (result !== undefined) return result;
157 }
158 return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
159 operation: "probeOpenCodeServer",
160 detail: `The server did not identify itself as OpenCode. T3 Code requires OpenCode v${OpenCodeRuntime.MINIMUM_OPENCODE_VERSION} or newer.`,
161 });
162});
163
164export const probeOpenCodeRuntime = (
165 settings: {
166 readonly binaryPath: string;
167 readonly serverUrl: string;
168 readonly serverPassword: string;
169 },
170 environment?: NodeJS.ProcessEnv,
171): Effect.Effect<
172 ProbedOpenCode,
173 OpenCodeRuntime.OpenCodeRuntimeError,
174 HttpClient.HttpClient | OpenCodeRuntime.OpenCodeRuntime
175> =>
176 settings.serverUrl.trim().length > 0
177 ? probeOpenCodeServer(settings.serverUrl, settings.serverPassword)
178 : probeOpenCodeBinary(settings.binaryPath, environment);
179
180export const makeOpenCodeRuntimeProbe = <E>(probe: Effect.Effect<ProbedOpenCode, E>) =>
181 Effect.map(
182 Cache.makeWith(() => probe, {
183 capacity: 1,
184 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
185 }),
186 (cache) => ({
187 get: Cache.get(cache, undefined),
188 refresh: Cache.refresh(cache, undefined),
189 lastSuccess: Cache.getSuccess(cache, undefined),
190 }),
191 );