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// Cross-version paths return HTML 200s, so require JSON; either version returns 401 for bad passwords.
40function classifyOpenCodeProbeResponse(
41 path: "/api/info" | "/global/health",
42 response: {
43 readonly status: number;
44 readonly contentType: string | undefined;
45 readonly body: string;
46 },
47): ProbedOpenCode | "unauthorized" | undefined {
48 if (response.status === 401) return "unauthorized";
49 const mediaType = response.contentType?.split(";")[0]?.trim().toLowerCase();
50 if (response.status !== 200 || mediaType !== "application/json") return undefined;
51 const version: Option.Option<string> =
52 path === "/api/info"
53 ? Option.map(decodeApiInfo(response.body), (info) => info.version)
54 : Option.map(decodeGlobalHealth(response.body), (health) => health.version);
55 return probed(Option.getOrUndefined(version));
56}
57
58export const probeOpenCodeBinary = Effect.fn("probeOpenCodeBinary")(function* (
59 binaryPath: string,
60 environment: NodeJS.ProcessEnv | undefined,
61) {
62 const runtime = yield* OpenCodeRuntime.OpenCodeRuntime;
63 const { stdout } = yield* runtime
64 .runOpenCodeCommand({
65 binaryPath,
66 args: ["--version"],
67 ...(environment === undefined ? {} : { environment }),
68 })
69 .pipe(
70 Effect.timeoutOrElse({
71 duration: OPENCODE_VERSION_PROBE_TIMEOUT,
72 orElse: () =>
73 Effect.fail(
74 new OpenCodeRuntime.OpenCodeRuntimeError({
75 operation: "probeOpenCodeBinary",
76 detail: `OpenCode CLI version probe timed out after ${OPENCODE_VERSION_PROBE_TIMEOUT}.`,
77 }),
78 ),
79 }),
80 );
81 const result = classifyOpenCodeCliVersion(stdout);
82 if (result) return result;
83 return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
84 operation: "probeOpenCodeBinary",
85 detail: `Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${OpenCodeRuntime.MINIMUM_OPENCODE_VERSION} or newer.`,
86 });
87});
88
89// Use fixed status text; underlying errors may expose URLs, credentials, or password headers.
90const probeOpenCodeServer = Effect.fn("probeOpenCodeServer")(function* (
91 serverUrl: string,
92 serverPassword: string,
93) {
94 const client = yield* HttpClient.HttpClient;
95 const baseUrl = URL.parse(serverUrl.trim());
96 if (baseUrl?.protocol !== "http:" && baseUrl?.protocol !== "https:") {
97 return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
98 operation: "probeOpenCodeServer",
99 detail: "The OpenCode server URL is not a valid http:// or https:// URL.",
100 });
101 }
102 // UTF-8, as the 1.x SDK client sends it; `HttpClientRequest.basicAuth` uses Latin-1 `btoa`.
103 const authorization = serverPassword
104 ? `Basic ${Buffer.from(`opencode:${serverPassword}`, "utf8").toString("base64")}`
105 : undefined;
106 for (const path of ["/api/info", "/global/health"] as const) {
107 const url = new URL(baseUrl);
108 url.pathname = `${url.pathname.replace(/\/+$/, "")}${path}`;
109 const request = HttpClientRequest.get(url.href);
110 const result = yield* client
111 .execute(
112 authorization
113 ? HttpClientRequest.setHeader(request, "authorization", authorization)
114 : request,
115 )
116 .pipe(
117 Effect.flatMap((response) =>
118 Effect.map(response.text, (body) =>
119 classifyOpenCodeProbeResponse(path, {
120 status: response.status,
121 contentType: response.headers["content-type"],
122 body,
123 }),
124 ),
125 ),
126 Effect.mapError(
127 (cause) =>
128 new OpenCodeRuntime.OpenCodeRuntimeError({
129 operation: "probeOpenCodeServer",
130 detail: "Couldn't reach the OpenCode server.",
131 cause,
132 }),
133 ),
134 Effect.timeoutOrElse({
135 duration: OPENCODE_SERVER_PROBE_TIMEOUT,
136 orElse: () =>
137 Effect.fail(
138 new OpenCodeRuntime.OpenCodeRuntimeError({
139 operation: "probeOpenCodeServer",
140 detail: "Timed out while checking the OpenCode server version.",
141 }),
142 ),
143 }),
144 );
145 if (result === "unauthorized") {
146 return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
147 operation: "probeOpenCodeServer",
148 detail: "401 Unauthorized: the OpenCode server rejected the password.",
149 });
150 }
151 if (result !== undefined) return result;
152 }
153 return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
154 operation: "probeOpenCodeServer",
155 detail: `The server did not identify itself as OpenCode. T3 Code requires OpenCode v${OpenCodeRuntime.MINIMUM_OPENCODE_VERSION} or newer.`,
156 });
157});
158
159export const probeOpenCodeRuntime = (
160 settings: {
161 readonly binaryPath: string;
162 readonly serverUrl: string;
163 readonly serverPassword: string;
164 },
165 environment?: NodeJS.ProcessEnv,
166): Effect.Effect<
167 ProbedOpenCode,
168 OpenCodeRuntime.OpenCodeRuntimeError,
169 HttpClient.HttpClient | OpenCodeRuntime.OpenCodeRuntime
170> =>
171 settings.serverUrl.trim().length > 0
172 ? probeOpenCodeServer(settings.serverUrl, settings.serverPassword)
173 : probeOpenCodeBinary(settings.binaryPath, environment);
174
175// Only 2.x is kept: 1.x can be upgraded in place while T3 runs, and 2.x converts the shared
176// database, so going back is unsupported.
177export const makeOpenCodeRuntimeProbe = <E>(probe: Effect.Effect<ProbedOpenCode, E>) =>
178 Effect.map(
179 Cache.makeWith(() => probe, {
180 capacity: 1,
181 timeToLive: (exit) =>
182 Exit.isSuccess(exit) && exit.value.generation === "v2" ? Duration.infinity : Duration.zero,
183 }),
184 (cache) => ({
185 get: Cache.get(cache, undefined),
186 refresh: Cache.refresh(cache, undefined),
187 lastSuccess: Cache.getSuccess(cache, undefined),
188 record: (probed: ProbedOpenCode) => Cache.set(cache, undefined, probed),
189 }),
190 );