Open History to see the last commit
1/** Detects whether an OpenCode instance runs 1.x or 2.x, so the driver can pick its runtime. */
2import { parseSemver } from "@t3tools/shared/semver";
3import * as Cache from "effect/Cache";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9import { HttpClient, HttpClientRequest } from "effect/unstable/http";
10
11import * as OpenCodeRuntime from "./opencodeRuntime.ts";
12import { parseGenericCliVersion } from "./providerSnapshot.ts";
13
14export interface ProbedOpenCode {
15 readonly generation: "v1" | "v2";
16 readonly version: string;
17}
18
19const OPENCODE_VERSION_PROBE_TIMEOUT = "4 seconds";
20const OPENCODE_SERVER_PROBE_TIMEOUT = "5 seconds";
21// 2.x's own CLI decodes `{version, pid}` from `/api/info`; requiring both keeps unrelated JSON out.
22const decodeApiInfo = Schema.decodeUnknownOption(
23 Schema.fromJsonString(Schema.Struct({ version: Schema.String, pid: Schema.Int })),
24);
25const decodeGlobalHealth = Schema.decodeUnknownOption(
26 Schema.fromJsonString(Schema.Struct({ healthy: Schema.Literal(true), version: Schema.String })),
27);
28
29function probed(version: string | null | undefined): ProbedOpenCode | undefined {
30 const major = parseSemver(version ?? "")?.major;
31 if (!version || major === undefined) return undefined;
32 return { generation: major >= 2 ? "v2" : "v1", version };
33}
34
35/** `opencode --version` prints `1.18.32` on 1.x and `opencode v2.0.18` on 2.x. */
36export const classifyOpenCodeCliVersion = (output: string) =>
37 probed(parseGenericCliVersion(output));
38
39/**
40 * 2.x answers `/api/info` and 1.x answers `/global/health`. Each serves its web UI's HTML with a
41 * 200 on the other's path, so only a JSON body counts. Both versions answer a wrong password with
42 * a 401 on either path, so a 401 says nothing about the 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 // A path prefix and query on the configured URL are kept: `/base/?x=1` → `/base/api/info?x=1`.
113 const url = new URL(baseUrl);
114 url.pathname = `${url.pathname.replace(/\/+$/, "")}${path}`;
115 const request = HttpClientRequest.get(url.href);
116 const result = yield* client
117 .execute(
118 authorization
119 ? HttpClientRequest.setHeader(request, "authorization", authorization)
120 : request,
121 )
122 .pipe(
123 Effect.flatMap((response) =>
124 Effect.map(response.text, (body) =>
125 classifyOpenCodeProbeResponse(path, {
126 status: response.status,
127 contentType: response.headers["content-type"],
128 body,
129 }),
130 ),
131 ),
132 Effect.mapError(
133 (cause) =>
134 new OpenCodeRuntime.OpenCodeRuntimeError({
135 operation: "probeOpenCodeServer",
136 detail: "Couldn't reach the OpenCode server.",
137 cause,
138 }),
139 ),
140 Effect.timeoutOrElse({
141 duration: OPENCODE_SERVER_PROBE_TIMEOUT,
142 orElse: () =>
143 Effect.fail(
144 new OpenCodeRuntime.OpenCodeRuntimeError({
145 operation: "probeOpenCodeServer",
146 detail: "Timed out while checking the OpenCode server version.",
147 }),
148 ),
149 }),
150 );
151 if (result === "unauthorized") {
152 return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
153 operation: "probeOpenCodeServer",
154 detail: "401 Unauthorized: the OpenCode server rejected the password.",
155 });
156 }
157 if (result !== undefined) return result;
158 }
159 return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
160 operation: "probeOpenCodeServer",
161 detail: `The server did not identify itself as OpenCode. T3 Code requires OpenCode v${OpenCodeRuntime.MINIMUM_OPENCODE_VERSION} or newer.`,
162 });
163});
164
165/** Probes a configured server when `serverUrl` is set, otherwise the local binary. */
166export const probeOpenCodeRuntime = (
167 settings: {
168 readonly binaryPath: string;
169 readonly serverUrl: string;
170 readonly serverPassword: string;
171 },
172 environment?: NodeJS.ProcessEnv,
173): Effect.Effect<
174 ProbedOpenCode,
175 OpenCodeRuntime.OpenCodeRuntimeError,
176 HttpClient.HttpClient | OpenCodeRuntime.OpenCodeRuntime
177> =>
178 settings.serverUrl.trim().length > 0
179 ? probeOpenCodeServer(settings.serverUrl, settings.serverPassword)
180 : probeOpenCodeBinary(settings.binaryPath, environment);
181
182/**
183 * One instance's runtime, remembered after the first successful probe. Settings changes rebuild
184 * the driver; `refresh` re-probes (status checks use it, so an in-place upgrade re-routes). A
185 * failed probe is never remembered. `lastSuccess` never probes, for calls too hot to wait on one.
186 */
187export const makeOpenCodeRuntimeProbe = <E>(probe: Effect.Effect<ProbedOpenCode, E>) =>
188 Effect.map(
189 Cache.makeWith(() => probe, {
190 capacity: 1,
191 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
192 }),
193 (cache) => ({
194 get: Cache.get(cache, undefined),
195 refresh: Cache.refresh(cache, undefined),
196 lastSuccess: Cache.getSuccess(cache, undefined),
197 }),
198 );